Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): make adjust_contrast torch.compile-compatible + fix validation (#3787)

Edgar Ribaf79a84a27abc
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 8d6802386..77e915e48 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -369,7 +369,9 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
while len(factor.shape) != len(image.shape):
factor = factor[..., None]
- KORNIA_CHECK(any(factor >= 0), "Contrast factor must be positive.")
+ # `bool(tensor)` is untraceable by dynamo; skip the data-dependent validation under compile.
+ if not torch.compiler.is_compiling():
+ KORNIA_CHECK(bool((factor >= 0).all()), "Contrast factor must be positive.")
# Apply contrast factor to each channel
img_adjust: torch.Tensor = image * factor
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index bdc977504..2baf17a54 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -573,6 +573,13 @@ class TestAdjustContrast(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0))
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ op = kornia.enhance.adjust_contrast
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img, 1.5), op_optimized(img, 1.5))
+
class TestAdjustBrightness(BaseTester):
@pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])