π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(enhance): build equalize_clahe tile histograms in one scatter_add_ (#4611)
Dipak Chaudharie428628d0c63
diff --git a/changelog.d/4611.fixed.md b/changelog.d/4611.fixed.mdnew file mode 100644index 000000000..bc3fd75d2--- /dev/null+++ b/changelog.d/4611.fixed.md@@ -0,0 +1 @@+`equalize_clahe`, and so `RandomClahe`, builds every tile histogram with one `scatter_add_` instead of one `torch.histc` call per tile, which is 192 kernel launches for a 256x256 RGB image on the default 8x8 grid. The histograms and the output are bit-identical to before on CPU. On MPS the tile histogram now matches the CPU one for inputs marginally outside `[0, 1]` (for example `1.0000001` or `-1e-7`), which `torch.histc` on MPS counted and the CPU kernel skips.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex cc9ee4599..db58fc1fe 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -23,7 +23,7 @@ from typing import Tupleimport torchimport torch.nn.functional as F-from kornia.core.utils import _torch_histc_cast+from kornia.core.utils import _normalize_to_float32_or_float64from kornia.image.utils import perform_keep_shape_imagefrom .histogram import histogram@@ -134,8 +134,34 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[intreturn interp_tiles-def _my_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:- return _torch_histc_cast(tiles, bins=bins, min=0, max=1)+def _tiles_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:+ r"""Histogram every tile over ``[0, 1]`` in one pass, matching a per-tile CPU ``torch.histc``.++ One ``scatter_add_`` counts all tiles, instead of one ``histc`` launch per tile, and keeps a static+ output shape so the function stays a single dynamo graph. The index is computed as ``histc``+ computes it, in the same float32/float64 promotion as ``_torch_histc_cast``: ``floor(x * bins)``,+ with ``x == 1`` in the last bin. Values outside ``[0, 1]`` and NaN are not counted, which the CPU+ ``histc`` also skips; they go to one extra overflow column per tile that is dropped. (``histc`` on+ MPS counts values marginally outside ``[0, 1]``, so there this matches CPU rather than MPS.)++ Args:+ tiles: flattened tiles. (T, P)+ bins: number of bins.++ Returns:+ Per-tile counts in the dtype of ``tiles``. (T, bins)++ """+ num_tiles = tiles.shape[0]+ x = tiles.to(_normalize_to_float32_or_float64(tiles.dtype))+ # clamp keeps [0, 1] unchanged and NaN as NaN, so the comparison is False exactly where histc skips.+ in_range = x.clamp(0, 1) == x+ idx = (x * bins).to(torch.int64).clamp_(0, bins - 1)+ # this mask is what drops out-of-range values; without it they land in the first or last bin+ idx = torch.where(in_range, idx, bins)+ counts = torch.zeros(num_tiles, bins + 1, dtype=x.dtype, device=x.device)+ counts.scatter_add_(1, idx, torch.ones_like(x))+ return counts[:, :bins].to(tiles.dtype)def _compute_luts(@@ -162,10 +188,7 @@ def _compute_luts(pixels: int = th * twtiles: torch.Tensor = tiles_x_im.view(-1, pixels) # test with view # T x (THxTW)if not diff:- if torch.jit.is_scripting():- histos = torch.stack([_torch_histc_cast(tile, bins=num_bins, min=0, max=1) for tile in tiles])- else:- histos = torch.stack(list(map(_my_histc, tiles, [num_bins] * len(tiles))))+ histos = _tiles_histc(tiles, num_bins)else:bins: torch.Tensor = torch.linspace(0, 1, num_bins, device=tiles.device)# histogram already returns (T, num_bins); squeeze() dropped the tile axis for a single tilediff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.pyindex 02ad064fb..fced6a776 100644--- a/tests/enhance/test_equalization.py+++ b/tests/enhance/test_equalization.py@@ -111,6 +111,31 @@ class TestEqualization(BaseTester):assert out.shape == img.shapeassert torch.isfinite(out).all()+ def test_histogram_skips_out_of_range(self, device, dtype):+ # torch.histc on CPU counts only values inside [min, max] and _tiles_histc must too. 1.0000001 and+ # -1e-7 are inside the window equalize_clahe admits (see RandomClahe's warning and #4564), and MPS's+ # torch.histc counts them, so this also pins CPU/MPS parity.+ from kornia.enhance.equalization import _tiles_histc++ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("1.0000001 and -1e-7 round to 1 and 0 in half precision")+ tiles = torch.tensor([[0.5, 1.0000001, -1e-7, 0.25]], device=device, dtype=dtype)+ expected = torch.tensor([[0.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(_tiles_histc(tiles, 4), expected)++ def test_dynamo(self, device, dtype, torch_optimizer):+ # The tile histograms keep a static shape, so equalize_clahe is one dynamo graph. A data-dependent+ # op such as bincount splits it into six; torch.compile without fullgraph=True would not notice.+ img = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)++ def op(x):+ return enhance.equalize_clahe(x, 40.0, (2, 2))++ torch._dynamo.reset()+ explanation = torch._dynamo.explain(op)(img)+ assert explanation.graph_break_count == 0, explanation.break_reasons+ self.assert_close(torch_optimizer(op)(img), op(img))+@pytest.mark.parametrize("grid_size", [(2, 2), (2, 3), (3, 2)])def test_gradcheck(self, device, grid_size):torch.random.manual_seed(4)