Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): move an MPS CLAHE clip tensor to the CPU before casting it to float64 (#4971)

Dmytro Mishkin50c7e82dc0f8
diff --git a/changelog.d/4971.fixed.md b/changelog.d/4971.fixed.md
new file mode 100644
index 000000000..038a93818
--- /dev/null
+++ b/changelog.d/4971.fixed.md
@@ -0,0 +1,4 @@
+`RandomClahe` and the per-sample CLAHE path now compute their clip thresholds correctly when the clip tensor is on MPS
+(#4970). The limits were moved to the CPU in float64 with a single `.to("cpu", torch.float64)`, which returns zeros
+on torch 2.14, so every tile histogram was clipped at one count (a mean error of 0.16 on a 256x256 image), and raises
+`TypeError` on torch 2.5.1. Parameters drawn by the default generator stay on the CPU and were not affected.
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index fd09d6327..badffc6e3 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -210,8 +210,9 @@ def _compute_luts(
if isinstance(clip, torch.Tensor):
# Match Python scalar arithmetic before rounding each image's threshold, then broadcast
# over its tiles and channels. Keeping the limits in tensors avoids compile guards on draws.
- # MPS cannot store doubles; compute its thresholds on CPU before copying them with the LUTs.
- limits = clip.to(device="cpu", dtype=torch.float64) if clip.device.type == "mps" else clip.double()
+ # MPS cannot store doubles; compute its thresholds on CPU before copying them with the LUTs. Move first,
+ # then cast: a single clip.to("cpu", torch.float64) from MPS raises on torch 2.5.1 and returns zeros on 2.14.
+ limits = clip.cpu().double() if clip.device.type == "mps" else clip.double()
max_vals = (limits * pixels).div(num_bins, rounding_mode="floor").clamp(min=1)
max_vals = max_vals.to(histos).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)
limited = histos.clamp(max=max_vals)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 888f76270..6e571e6cb 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4469,6 +4469,20 @@ class TestRandomClahe(BaseTester):
torch.autograd.grad(expected, input_data, weights)[0],
)
+ def test_clip_limit_on_the_input_device(self, device, dtype):
+ # The per-sample thresholds are computed in float64, on the CPU for an MPS clip tensor. A single
+ # clip.to("cpu", torch.float64) from MPS raised on torch 2.5.1 and returned zeros on torch 2.14, which
+ # clipped every tile histogram at 1. 16x16 tiles make a limit of 40 differ from that floor.
+ torch.manual_seed(0)
+ input_data = torch.rand(2, 1, 32, 32).pow(3).to(device=device, dtype=dtype)
+ aug = RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0)
+ params = aug.forward_parameters(input_data.shape)
+ params["clip_limit_factor"] = torch.tensor([0.5, 40.0], device=device, dtype=dtype)
+ expected = torch.cat(
+ [kornia.enhance.equalize_clahe(input_data[i : i + 1], clip, (2, 2)) for i, clip in enumerate((0.5, 40.0))]
+ )
+ self.assert_close(aug(input_data, params=params), expected)
+
def test_same_on_batch(self, device, dtype):
torch.manual_seed(0)
input_data = torch.rand(1, 1, 32, 32).to(device=device, dtype=dtype).repeat(2, 1, 1, 1)
diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.py
index 62c56b4f3..f47e3f360 100644
--- a/tests/geometry/solvers/test_homogeneous.py
+++ b/tests/geometry/solvers/test_homogeneous.py
@@ -37,7 +37,8 @@ def _make_rank3_matrix(null_vec: torch.Tensor, device, dtype) -> torch.Tensor:
"""
# Build the 4x4 matrix whose columns span the orthogonal complement of null_vec.
# We use a Gram-Schmidt orthonormalisation relative to null_vec.
- n = null_vec.to(device="cpu", dtype=torch.float64)
+ # move, then cast: a single .to("cpu", torch.float64) from MPS returns zeros on torch 2.14
+ n = null_vec.cpu().double()
n = n / n.norm()
# Start from the standard basis and remove the component along n.