Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): name the [0, 1] range in equalize_clahe out-of-range errors (#4585)

yi1117648f59b9718
diff --git a/changelog.d/4585.fixed.md b/changelog.d/4585.fixed.md
new file mode 100644
index 000000000..9a0328fe1
--- /dev/null
+++ b/changelog.d/4585.fixed.md
@@ -0,0 +1,6 @@
+`kornia.enhance.equalize_clahe` and `kornia.augmentation.RandomClahe` now raise a `RuntimeError`
+naming the `[0, 1]` input range for values the 256-bin tile lookup cannot index, instead of a raw
+`index ... is out of bounds for dimension 5 with size 256` from the gather β€” the same named-range
+treatment `equalize` got in #4489. The check uses `torch._assert_async`, so it adds no device sync
+and `torch.compile` fullgraph still works; inputs the lookup can index (including values a hair
+above 1) are unchanged.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 6e170e76f..6a92e38e0 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -333,8 +333,8 @@ Augmentations
:class:`kornia.augmentation.RandomClahe` and
:class:`kornia.augmentation.RandomJPEG` are importable and documented but absent
from ``kornia.augmentation.__all__``, so they are outside the audited set above;
- ``RandomClahe`` raises out of range with a raw indexing error
- (`#4564 <https://github.com/kornia/kornia/issues/4564>`_) and ``RandomJPEG``
+ ``RandomClahe`` raises out of range with a message naming the range, except on
+ MPS, where the check is skipped and a raw indexing error survives; and ``RandomJPEG``
clamps the decoded RGB output into ``[0, 1]``. The decoding can produce intermediate
values even when every input value is negative or every input value is above ``1``;
such images need not become solid black or white.
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 27e39b49e..eb611839f 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -49,18 +49,17 @@ class RandomClahe(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- .. warning::
- An input outside ``[0, 1]`` reaches :func:`kornia.enhance.equalize_clahe` unchecked and comes
- back as a raw torch indexing error that names neither this class nor the range it needs. As for
- :class:`RandomEqualize`, the rejection is not exactly at the boundary: the failing index is 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. Tracked in
- `#4564 <https://github.com/kornia/kornia/issues/4564>`_. Unlike :class:`RandomEqualize`, CLAHE has
- no value check on any device, so the raw error is what every caller gets on the CPU. On MPS the
- outcome depends on 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.
+ Convention:
+ - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming
+ :func:`kornia.enhance.equalize_clahe` and that range, the way :class:`RandomEqualize` raises for
+ :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.
.. warning::
``clip_limit`` is drawn per sample, but the first sample's value is applied to the whole batch.
@@ -77,7 +76,9 @@ class RandomClahe(IntensityAugmentationBase2D):
instead.
.. note::
- This function internally uses :func:`kornia.enhance.equalize_clahe`.
+ This function internally uses :func:`kornia.enhance.equalize_clahe`, which expects the input in
+ :math:`[0, 1]` and raises a ``RuntimeError`` naming that range for values its 256-bin lookup
+ cannot index.
Examples:
>>> img = torch.rand(1, 10, 20)
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index b50cad12f..ca948c72d 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -43,8 +43,9 @@ class RandomEqualize(IntensityAugmentationBase2D):
Convention:
- 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 raw indexing error
- that names neither the class nor the range (`#4564 <https://github.com/kornia/kornia/issues/4564>`_).
+ 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``.
- 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``,
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index db58fc1fe..67e79b7c4 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -26,6 +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 .histogram import histogram
@@ -385,6 +386,12 @@ def equalize_clahe(
>>> res.shape
torch.Size([2, 3, 10, 20])
+ .. 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`.
+
"""
if not isinstance(clip_limit, float):
raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")
@@ -401,6 +408,15 @@ def equalize_clahe(
if grid_size[0] <= 0 or grid_size[1] <= 0:
raise ValueError(f"Input grid_size elements must be positive. Got {grid_size}")
+ # 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(
+ ((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.",
+ )
+
imgs: torch.Tensor = input # B x C x H x W
# hist_tiles: torch.Tensor # B x GH x GW x C x TH x TW # not supported by JIT
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 06901ca3e..f747aa74a 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -1829,29 +1829,67 @@ class TestIntensityColourConventions(BaseTester):
jpeg = K.RandomJPEG(50.0, p=1.0)._param_generator
assert (float(jpeg.jpeg_quality_sampler.low), float(jpeg.jpeg_quality_sampler.high)) == (1.0, 100.0)
- # Issue #4564: RandomClahe rejects an out-of-[0, 1] input with the raw indexing error of the
- # histogram gather, naming neither the class nor the range RandomEqualize names (#4489). Not on CUDA,
- # where the out-of-range index is a device-side assert that poisons the context; on MPS the error is
- # an AcceleratorError, a RuntimeError subclass, reading `gather: index ... is out of bounds`.
+ # 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.
# 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-15 (torch 2.14.0, cpu) -> `RuntimeError: index 430 is out of bounds for
- # dimension 5 with size 256`.
- def test_wart_random_clahe_out_of_range_error_is_raw_4564(self, device, dtype):
+ # 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`.
+ 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" and not torch_version_ge(2, 14):
- # 2.5.1 leaves the MPS gather unchecked: the call returns an in-range image as if valid.
- out = K.RandomClahe(p=1.0)(image)
- assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0
+ 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="out of bounds") as info:
+ with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]") as info:
_sync(K.RandomClahe(p=1.0)(image).device)
- assert "RandomClahe" not in str(info.value) and "[0, 1]" not in str(info.value)
+ # `match` alone would be satisfied by a message that never mentions how to fix it.
+ assert "image / 255.0" in str(info.value)
+
+ # The rejection is one 8-bit code wide either side of [0, 1], not exactly at the bound: the guard is
+ # the 256-entry lookup indexed with `(input * 255).long()`, so the admitted band is
+ # `(-1/255, 1 + 1/255)`. Without this leg a `>=`/`<=` widening of the check survives every other pin.
+ # Snippet used to generate expected:
+ # for v in (1.0, 0.0, 1 + 0.5/255, 1 + 1.5/255, -0.5/255, -1.5/255):
+ # img = torch.full((1, 1, 16, 16), 0.5); img[0, 0, 0, 0] = v; equalize_clahe(img)
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> admitted, admitted, admitted, RAISES, admitted, RAISES.
+ @pytest.mark.parametrize(
+ ("value", "admitted"),
+ [
+ (1.0, True),
+ (0.0, True),
+ (1.0 + 0.5 / 255, True),
+ (1.0 + 1.5 / 255, False),
+ (-0.5 / 255, True),
+ (-1.5 / 255, False),
+ ],
+ )
+ def test_convention_random_clahe_admitted_band_is_one_code_wide(self, device, dtype, value, admitted):
+ if device.type in ("cuda", "mps"):
+ pytest.skip("the value check runs on the CPU only: CUDA poisons the context, MPS skips it")
+ image = torch.full((1, 1, 16, 16), 0.5, device=device, dtype=dtype)
+ image[0, 0, 0, 0] = value
+ torch.manual_seed(_FORWARD_SEED)
+ if admitted:
+ assert K.RandomClahe(p=1.0)(image).isfinite().all()
+ else:
+ with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
+ K.RandomClahe(p=1.0)(image)
# Divisibility is not the axis that decides whether `grid_size` works: a SQUARE grid is padded up to
# a whole number of tiles, so it works whether or not it divides the image. `_compute_tiles` is
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index fced6a776..86de5feb5 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -160,6 +160,29 @@ class TestEqualization(BaseTester):
# equalize_clahe is only a function
pass
+ @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)")
+ 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)
+
+ 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
+ assert enhance.equalize_clahe(x).shape == x.shape
+
+ def test_dynamo_fullgraph(self, device, dtype):
+ # The range check must not introduce a graph break.
+ x = torch.rand(2, 3, 32, 40, device=device, dtype=dtype)
+ torch._dynamo.reset()
+ compiled = torch.compile(enhance.equalize_clahe, fullgraph=True, backend="eager")
+ self.assert_close(compiled(x), enhance.equalize_clahe(x))
+
@pytest.fixture()
def img(self, device, dtype):
height, width = 20, 20