Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): raise the named range error for equalize and CLAHE on MPS (#4663)

Ethan Stoner2f7639327b6d
diff --git a/changelog.d/4663.fixed.md b/changelog.d/4663.fixed.md
new file mode 100644
index 000000000..fa55595bc
--- /dev/null
+++ b/changelog.d/4663.fixed.md
@@ -0,0 +1,5 @@
+`equalize`, `equalize_clahe`, `RandomEqualize` and `RandomClahe` now raise the same `RuntimeError` naming the
+`[0, 1]` input range on MPS as on the CPU, instead of torch's raw `gather: index ... is out of bounds` error.
+On MPS the check is the same asynchronous `torch._assert_async` from torch 2.13; older releases have no
+MPS kernel for it, so there the condition is read on the host at one device sync per call and is skipped
+under `torch.compile`.
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 3d1ddd5ae..866e9c6fd 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -56,11 +56,9 @@ class RandomClahe(IntensityAugmentationBase2D):
:func:`kornia.enhance.equalize`. As for :class:`RandomEqualize`, the rejection is not exactly at
the boundary: the check guards the 256-entry lookup indexed with ``(input * 255).long()``, so a
value less than one 8-bit code outside ``[0, 1]``, at either end, is still admitted, up to the
- rounding of ``input * 255`` in the input's dtype. The check runs on the CPU and on CUDA. **It is
- skipped on MPS by design** -- materializing the condition there would drain the queued stream on
- every call -- so an MPS image keeps the pre-existing behaviour: torch ``2.14`` raises the raw
- ``gather`` error (`#4600 <https://github.com/kornia/kornia/issues/4600>`_), while ``2.5.1``
- leaves the gather unchecked and returns an in-range image as if the input had been valid.
+ rounding of ``input * 255`` in the input's dtype. 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, which costs one device sync per call and is skipped under ``torch.compile``.
Convention:
- ``clip_limit`` is drawn per sample and each image is equalized with its own draw. Both eager and
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index ca948c72d..a6c530727 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -44,8 +44,7 @@ class RandomEqualize(IntensityAugmentationBase2D):
- this class raises on an out-of-``[0, 1]`` input instead of transforming it. See
:class:`~kornia.augmentation.IntensityAugmentationBase2D` for the policies used by the other
intensity augmentations. :class:`RandomClahe` also raises out of range, with a message naming
- :func:`kornia.enhance.equalize_clahe` and the range; its check is skipped on MPS, where the raw
- indexing error survives on torch ``2.14``.
+ :func:`kornia.enhance.equalize_clahe` and the range.
- the rejection is not exactly at the boundary: the check guards the 256-entry lookup indexed with
``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]``, at either end, is
still admitted, up to the rounding of ``input * 255`` in the input's dtype: in ``float16``,
@@ -53,13 +52,10 @@ class RandomEqualize(IntensityAugmentationBase2D):
.. note::
This function internally uses :func:`kornia.enhance.equalize`, which expects the input in
- :math:`[0, 1]` and raises a ``RuntimeError`` for values it cannot equalize. Where the value check
- runs, its message names that range; kornia skips the check for an MPS image, and what happens
- there depends on torch: from ``2.14`` the lookup raises a raw indexing error
- (``AcceleratorError: gather: index 260 is out of bounds for dimension with size 256``), while
- ``2.5.1`` and ``2.9.1`` leave the MPS gather unchecked and return an out-of-range image silently.
- That MPS gap is what `#4431 <https://github.com/kornia/kornia/issues/4431>`_ left behind when it
- was closed, and is tracked in `#4600 <https://github.com/kornia/kornia/issues/4600>`_.
+ :math:`[0, 1]` and raises a ``RuntimeError`` naming that range for values it cannot equalize. 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, which costs one device sync per call and is
+ skipped under ``torch.compile``.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 3f20029ea..d54d154be 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -25,12 +25,13 @@ 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,
)
-from kornia.core.utils import _torch_histc_cast
+from kornia.core.utils import _torch_histc_cast, is_compiling
from kornia.image.utils import perform_keep_shape_image, perform_keep_shape_video
@@ -48,6 +49,28 @@ def _assert_async_value_check(cond: torch.Tensor, msg: str) -> None:
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 adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
@@ -973,8 +996,9 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
# Input is expected in [0, 1]. The histogram index below is clamped, but the LUT lookup indexes
# with the unclamped ``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;
- # inputs the lookup can index keep working exactly as before.
- _assert_async_value_check(
+ # 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(
((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.",
@@ -1066,8 +1090,9 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
.. note::
The input is expected in :math:`[0, 1]`, and each channel is equalized from a 256-bin histogram.
Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError``
- naming the range. The check runs on CPU and CUDA (via ``torch._assert_async``); on MPS it is
- skipped, as for :func:`adjust_gamma`.
+ 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``.
Example:
>>> x = torch.rand(1, 2, 3, 3)
@@ -1098,8 +1123,9 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
with no more than 255 voxels per channel is returned unchanged up to floating-point roundoff; just
above that, whether it changes
depends on the values. Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`)
- raise a ``RuntimeError`` naming the range. The check runs on CPU and CUDA (via
- ``torch._assert_async``); on MPS it is skipped.
+ 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``.
"""
# Scales each channel independently (each (D, H, W) volume), batched over (B, C).
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 72d4afa26..c7837e408 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -26,7 +26,7 @@ import torch.nn.functional as F
from kornia.core.utils import _normalize_to_float32_or_float64
from kornia.image.utils import perform_keep_shape_image
-from .adjust import _assert_async_value_check
+from .adjust import _lookup_value_check
from .histogram import histogram
@@ -406,8 +406,9 @@ def equalize_clahe(
.. note::
The input is expected in :math:`[0, 1]`; each tile is equalized from a 256-bin lookup table.
Values the lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError``
- naming the range. The check runs on CPU and CUDA (via ``torch._assert_async``); on MPS it is
- skipped, as for :func:`kornia.enhance.equalize`.
+ 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`.
"""
if not isinstance(clip_limit, float):
@@ -437,8 +438,9 @@ 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; inputs the lookup can index are unchanged.
- _assert_async_value_check(
+ # 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(
((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.",
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index d4637e5ce..809d77c42 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -25,7 +25,6 @@ import torch
import kornia.augmentation as K
from kornia.augmentation.random_generator import RectangleEraseGenerator
from kornia.color import rgb_to_hsv
-from kornia.core._compat import torch_version_ge
from kornia.core.exceptions import BaseError, ImageError, ShapeError
from kornia.enhance import (
AdjustBrightnessAccumulative,
@@ -234,24 +233,17 @@ class TestIntensityValueRangeConventions(BaseTester):
assert set().union(*groups) == set(_INTENSITY_FACTORIES) and len(_INTENSITY_FACTORIES) == 35
if name in _REJECTS_AUDIT_FIXTURES and device.type == "cuda":
# torch._assert_async on a false condition is a device-side assert on CUDA, which poisons
- # the context for every later test in the process. On MPS the check is skipped by design
- # and the raw histogram gather raises instead (an AcceleratorError, a RuntimeError subclass).
+ # the context for every later test in the process. On MPS kornia checks the same
+ # condition (#4600), so the named error is raised there as on the CPU.
pytest.skip("CUDA: the value assert is a device-side assert that invalidates the context")
if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):
pytest.skip("reflection_pad2d is unavailable for this device/dtype")
fixtures = _out_of_range_fixtures(device, dtype)
if name in _REJECTS_AUDIT_FIXTURES:
- # The rejection has to be the VALUE check, not any RuntimeError: on the CPU the message
- # names the range, and on MPS the check is skipped so the raw gather error surfaces (#4600) --
- # from torch 2.14; 2.5.1 and 2.9.1 leave the MPS gather unchecked and return silently.
- if device.type == "mps" and not torch_version_ge(2, 14):
- for image in fixtures.values():
- out = _run(name, image)
- assert bool(torch.isfinite(out).all())
- return
- rejection = r"\[0, 1\]" if device.type == "cpu" else "out of bounds"
+ # The rejection has to be the VALUE check, not any RuntimeError: its message names the
+ # range, on the CPU and on MPS alike (#4600).
for image in fixtures.values():
- with pytest.raises(RuntimeError, match=rejection):
+ with pytest.raises(RuntimeError, match=r"\[0, 1\]"):
_run(name, image)
return
# A clamped output is exactly 0.0 or 1.0, and the pass-through outputs sit near 2.0 or
@@ -559,22 +551,18 @@ class TestIntensityValueRangeConventions(BaseTester):
# torch.manual_seed(0); K.RandomEqualize(p=1.0)(x)
# executed 2026-09-15 (torch 2.14.0, cpu) -> the last two raise `RuntimeError: equalize expects
# input values in [0, 1]. Scale the image into that range first, for example image / 255.0 for
- # 8-bit data.`, the first two return a 64-level image. MPS skips the value check, and the same two
- # inputs raise the raw `gather: index ... is out of bounds` there (an AcceleratorError, which is a
- # RuntimeError). The guard compares `input * 255` in the input's dtype, so `1.00390625` (1 + 1/256,
- # under one code above 1) is admitted in float32 and float64 but rounds onto 256 and raises in float16.
+ # 8-bit data.`, the first two return a 64-level image. MPS runs the same check and raises the
+ # same message (#4600). The guard compares `input * 255` in the input's dtype, so
+ # `1.00390625` (1 + 1/256, under one code above 1) is admitted in float32 and float64 but rounds onto
+ # 256 and raises in float16.
def test_convention_random_equalize_rejects_out_of_range_with_named_range(self, device, dtype):
if device.type == "cuda":
pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
- # Only kornia's own check names the range; MPS skips it and surfaces torch's gather error from
- # torch 2.14 (2.5.1 and 2.9.1 leave the MPS gather unchecked and return the image silently).
- match = r"\[0, 1\]" if device.type == "cpu" else "out of bounds"
+ # Only kornia's own check names the range; it runs on MPS as well, so it raises there too.
+ match = r"\[0, 1\]"
ramp = torch.linspace(0, 1, 64).reshape(1, 1, 8, 8).to(device=device, dtype=dtype)
for image in (ramp * 2.0, ramp - 1.0):
torch.manual_seed(_FORWARD_SEED)
- if device.type == "mps" and not torch_version_ge(2, 14):
- assert bool(torch.isfinite(K.RandomEqualize(p=1.0)(image)).all())
- continue
with pytest.raises(RuntimeError, match=match):
_sync(K.RandomEqualize(p=1.0)(image).device)
# Less than one 8-bit code outside the range is admitted at either end: `ramp - 0.003` has
@@ -607,8 +595,8 @@ class TestIntensityValueRangeConventions(BaseTester):
# torch.manual_seed(0); y = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.0)(v); y.sum().backward()
# print(torch.equal(y, v), v.grad.flatten().tolist())
# executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) -> both
- # classes raise (`equalize expects input values in [0, 1]`, `index ... is out of bounds`), then
- # `True [nan, 1.0, 1.0, nan, 1.0, 1.0]`.
+ # classes raise (`equalize expects input values in [0, 1]`, `index ... is out of bounds`; on mps the
+ # named message since #4600), then `True [nan, 1.0, 1.0, nan, 1.0, 1.0]`.
def test_wart_p_gate_computes_the_skipped_samples_4576(self, device, dtype):
if device.type == "cuda":
pytest.skip("not on CUDA: the value asserts are device-side asserts that poison the context")
@@ -618,12 +606,8 @@ class TestIntensityValueRangeConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
# It has to be the value check that fires, not merely some RuntimeError: the claim is that
# the transform ran on a sample `p=0.0` was supposed to skip.
- gate_rejection = r"\[0, 1\]|out of bounds" if device.type == "cpu" else "out of bounds"
- if device.type == "mps" and not torch_version_ge(2, 14):
- # The transform still runs on the skipped samples, but 2.5.1 leaves the MPS gather
- # unchecked, so the out-of-range rows come back silently instead of raising.
- assert bool(torch.isfinite(cls(p=0.0)(image)).all())
- continue
+ # MPS runs the value check too since #4600, so only the named error qualifies there.
+ gate_rejection = r"\[0, 1\]|out of bounds" if device.type == "cpu" else r"\[0, 1\]"
with pytest.raises(RuntimeError, match=gate_rejection):
_sync(cls(p=0.0)(image).device)
values = torch.tensor([0.0, 0.25, 1.0]).reshape(1, 1, 1, 3).repeat(2, 1, 1, 1)
@@ -1825,30 +1809,19 @@ class TestIntensityColourConventions(BaseTester):
# RandomClahe rejects an out-of-[0, 1] input with a message naming `equalize_clahe` and the range
# (the fix for #4564; the raw indexing error of the histogram gather used to be all a caller got).
# Not on CUDA, where an out-of-range index is a device-side assert that poisons the context. On MPS
- # the check is SKIPPED BY DESIGN -- `_assert_async_value_check` returns early there, because
- # materializing the condition would drain the queued stream -- so MPS keeps the old behaviour and the
- # pin keeps its two torch legs: 2.14 raises the raw `gather` error (#4600), 2.5.1 returns silently.
+ # `_lookup_value_check` runs the same condition, so the same named error is raised (#4600).
# Snippet used to generate expected:
# torch.manual_seed(1234); x = torch.rand(1, 3, 16, 16) * 2
# torch.manual_seed(0); K.RandomClahe(p=1.0)(x)
# executed 2026-09-16 (torch 2.14.0) -> cpu `RuntimeError: equalize_clahe expects input values in
- # [0, 1]. Scale the image into that range first, ...`; mps `AcceleratorError: gather: index 487 is
- # out of bounds for dimension 5 with size 256`.
+ # [0, 1]. Scale the image into that range first, ...`; mps the same message since #4600 (before it,
+ # `AcceleratorError: gather: index 487 is out of bounds for dimension 5 with size 256`).
def test_convention_random_clahe_out_of_range_error_names_the_range_4564(self, device, dtype):
if device.type == "cuda":
pytest.skip("not on CUDA: the index error is a device-side assert that poisons the context")
torch.manual_seed(_FIXTURE_SEED)
image = (torch.rand(1, 3, 16, 16) * 2).to(device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
- if device.type == "mps":
- # The value check is skipped on MPS, so the outcome is torch's, not kornia's.
- if not torch_version_ge(2, 14):
- out = K.RandomClahe(p=1.0)(image)
- assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0
- else:
- with pytest.raises(RuntimeError, match="out of bounds"):
- _sync(K.RandomClahe(p=1.0)(image).device)
- return
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]") as info:
_sync(K.RandomClahe(p=1.0)(image).device)
# `match` alone would be satisfied by a message that never mentions how to fix it.
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index f6ed08521..81cb451e3 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -21,10 +21,18 @@ from torch import Tensor
import kornia
from kornia.constants import pi
+from kornia.core._compat import torch_version_ge
from testing.base import BaseTester
+def _sync(device) -> None:
+ # MPS dispatches asynchronously, so a kernel error raised by the forward under test would
+ # otherwise surface inside an unrelated later test.
+ if device.type == "mps":
+ torch.mps.synchronize()
+
+
class TestInvert(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
@@ -899,12 +907,13 @@ class TestEqualize(BaseTester):
@pytest.mark.parametrize("scale, shift", [(2.0, 0.0), (1.0, -1.0)])
def test_out_of_range_input_names_the_range(self, scale, shift, device, dtype):
# kornia#4431: an input the 256-bin lookup cannot index used to fail with a raw
- # "index 259 is out of bounds" from the gather.
- if device.type != "cpu":
- pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")
+ # "index 259 is out of bounds" from the gather. MPS range-checks it too (kornia#4600): from
+ # torch 2.13 the assert is asynchronous there, so the message arrives at the sync.
+ 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) * scale + shift
with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
- kornia.enhance.equalize(x)
+ _sync(kornia.enhance.equalize(x).device)
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.
@@ -918,6 +927,19 @@ class TestEqualize(BaseTester):
compiled = torch.compile(kornia.enhance.equalize, fullgraph=True, backend="eager")
self.assert_close(compiled(x), kornia.enhance.equalize(x))
+ def test_dynamo_fullgraph_out_of_range_input_names_the_range(self, device, dtype):
+ # The compiled graph has to carry the same check: on MPS kornia#4600 is only fixed while
+ # compiling if the asynchronous assert is traced, because a host read cannot be.
+ 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")
+ x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * 2.0
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.enhance.equalize, fullgraph=True, backend="eager")
+ with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
+ _sync(compiled(x).device)
+
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 3
@@ -943,13 +965,13 @@ class TestEqualize(BaseTester):
class TestEqualize3D(BaseTester):
@pytest.mark.parametrize("scale, shift", [(1.5, 0.0), (1.0, -0.5)])
def test_out_of_range_input_names_the_range(self, scale, shift, device, dtype):
- # kornia#4432: the 3D path shares the lookup and failed the same way.
- if device.type != "cpu":
- pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")
+ # kornia#4432: the 3D path shares the lookup, so it shares the MPS fix too (kornia#4600).
+ 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(1, 1, 5, 7, 9, device=device, dtype=dtype) * scale + shift
with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
- kornia.enhance.equalize3d(x)
+ _sync(kornia.enhance.equalize3d(x).device)
def test_at_most_255_voxels_per_channel_is_unchanged(self, device, dtype):
# As the docstring states: the lookup step is an integer division by 255.
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index 53cc21534..ace625fbb 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -21,11 +21,19 @@ import pytest
import torch
from kornia import enhance
+from kornia.core._compat import torch_version_ge
from kornia.geometry import rotate
from testing.base import BaseTester
+def _sync(device) -> None:
+ # MPS dispatches asynchronously, so a kernel error raised by the forward under test would
+ # otherwise surface inside an unrelated later test.
+ if device.type == "mps":
+ torch.mps.synchronize()
+
+
class TestEqualization(BaseTester):
def test_smoke(self, device, dtype):
C, H, W = 1, 10, 20
@@ -172,13 +180,15 @@ class TestEqualization(BaseTester):
@pytest.mark.parametrize("scale, shift", [(2.0, 0.0), (1.0, -1.0)])
def test_out_of_range_input_names_the_range(self, scale, shift, device, dtype):
# kornia#4564: the tile-LUT gather used to fail with a raw
- # "index ... is out of bounds for dimension 5 with size 256".
- if device.type != "cpu":
- pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")
+ # "index ... is out of bounds for dimension 5 with size 256". MPS range-checks it too
+ # (kornia#4600): from torch 2.13 the assert is asynchronous there, so the message arrives at
+ # the sync.
+ 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) * scale + shift
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
- enhance.equalize_clahe(x)
+ _sync(enhance.equalize_clahe(x).device)
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.
@@ -192,6 +202,20 @@ class TestEqualization(BaseTester):
compiled = torch.compile(enhance.equalize_clahe, fullgraph=True, backend="eager")
self.assert_close(compiled(x), enhance.equalize_clahe(x))
+ def test_dynamo_fullgraph_out_of_range_input_names_the_range(self, device, dtype):
+ # The compiled graph has to carry the same check: on MPS kornia#4600 is only fixed while
+ # compiling if the asynchronous assert is traced, because a host read cannot be.
+ 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")
+ torch.manual_seed(0)
+ x = torch.rand(2, 3, 32, 40, device=device, dtype=dtype) * 2.0
+ torch._dynamo.reset()
+ compiled = torch.compile(enhance.equalize_clahe, 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