Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): deprecate RandomAutoContrast clip_output (#6325)

Puttala Jeevan Kumar9ac0a1e0d440
diff --git a/changelog.d/6325.fixed.md b/changelog.d/6325.fixed.md
new file mode 100644
index 000000000..5d750e18f
--- /dev/null
+++ b/changelog.d/6325.fixed.md
@@ -0,0 +1 @@
+`RandomAutoContrast` emits a `DeprecationWarning` when `clip_output` is passed; the argument will be removed in a future release. It never changed the output, because `normalize_min_max` already returns values in `[0, 1]`. Its default clamp also zeroed the gradient wherever a channel's minimum or maximum was shared by several pixels on torch 2.14 and later. The clamp is gone, so the gradient no longer depends on the torch version.
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index 574a6c03e..1dfbc0e5c 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -15,6 +15,9 @@
# limitations under the License.
#
+from __future__ import annotations
+
+import warnings
from typing import Any, Dict, Optional
import torch
@@ -23,6 +26,17 @@ from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.enhance import normalize_min_max
+def _warn_clip_output_deprecated(clip_output: Optional[bool]) -> None:
+ if clip_output is not None:
+ warnings.warn(
+ "`clip_output` of `RandomAutoContrast` is deprecated since kornia 0.9.1 and has no effect: "
+ "`kornia.enhance.normalize_min_max` already returns values in [0, 1]. It will be removed in a "
+ "future release; stop passing it, and pass `same_on_batch`, `p` and `keepdim` by keyword.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+
+
class RandomAutoContrast(IntensityAugmentationBase2D):
r"""Apply a random auto-contrast of a torch.Tensor image.
@@ -30,10 +44,9 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
- clip_output: has no effect on the output. The transform is
- :func:`kornia.enhance.normalize_min_max`, which already maps each sample's channels onto ``[0, 1]``,
- so clamping to that interval cannot change a value -- including for inputs outside ``[0, 1]``. Kept
- for signature compatibility. Tracked in `#4436 <https://github.com/kornia/kornia/issues/4436>`_.
+ clip_output: deprecated since 0.9.1 and ignored; passing it emits a :class:`DeprecationWarning`,
+ and it will be removed in a future release. :func:`kornia.enhance.normalize_min_max` already maps
+ each sample's channels onto ``[0, 1]``. See `#4436 <https://github.com/kornia/kornia/issues/4436>`_.
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
@@ -51,11 +64,12 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
"""
def __init__(
- self, clip_output: bool = True, same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
+ self, clip_output: Optional[bool] = None, same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
) -> None:
+ _warn_clip_output_deprecated(clip_output)
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.clip_output = clip_output
+ self.clip_output = True if clip_output is None else clip_output
def apply_transform(
self,
@@ -64,9 +78,4 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- out = normalize_min_max(input)
-
- if self.clip_output:
- return out.clamp(0.0, 1.0)
-
- return out
+ return normalize_min_max(input)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 4b68d22cf..8d49e9019 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -22,6 +22,7 @@ import pickle
import re
import subprocess
import sys
+import warnings
from typing import Any, Dict, Optional, Tuple, Type
from unittest.mock import patch
@@ -6127,18 +6128,55 @@ class TestRandomAutoContrast(BaseTester):
out = aug(x_data)
assert out.shape == x_data.shape
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("args", "kwargs", "clip_output"),
+ [((), {"clip_output": True}, True), ((), {"clip_output": False}, False), ((False,), {}, False)],
+ )
+ def test_clip_output_deprecated(self, args, kwargs, clip_output):
+ with pytest.warns(DeprecationWarning, match="clip_output") as record:
+ aug = kornia.augmentation.RandomAutoContrast(*args, **kwargs)
+ assert [w.filename for w in record if "clip_output" in str(w.message)] == [__file__]
+ assert aug.clip_output is clip_output
+
+ @pytest.mark.device_agnostic
+ def test_no_warning_without_clip_output(self):
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ aug = kornia.augmentation.RandomAutoContrast(p=1.0)
+ kornia.augmentation.auto.operations.AutoContrast()
+ kornia.augmentation.auto.AutoAugment()
+ assert aug.clip_output is True
+
+ @pytest.mark.parametrize("clip_output", [None, True, False])
@pytest.mark.parametrize(("scale", "shift"), [(1.0, 0.0), (2.0, 0.0), (1.0, -1.0), (0.0, 0.5)])
- def test_clip_output_does_not_change_the_output(self, scale, shift, device, dtype):
- # #4436: normalize_min_max already lands in [0, 1], so the documented clamp is a no-op, even for the
- # out-of-range inputs a caller would reach for it to protect against. The constant image (scale 0)
- # comes back as zeros either way.
+ def test_clip_output_does_not_change_the_output(self, clip_output, scale, shift, device, dtype):
torch.manual_seed(0)
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype) * scale + shift
- clipped = kornia.augmentation.RandomAutoContrast(clip_output=True, p=1.0)(x.clone())
- unclipped = kornia.augmentation.RandomAutoContrast(clip_output=False, p=1.0)(x.clone())
- self.assert_close(clipped, unclipped, rtol=0.0, atol=0.0)
- assert unclipped.min().item() >= 0.0
- assert unclipped.max().item() <= 1.0
+ if clip_output is None:
+ aug = kornia.augmentation.RandomAutoContrast(p=1.0)
+ else:
+ with pytest.warns(DeprecationWarning, match="clip_output"):
+ aug = kornia.augmentation.RandomAutoContrast(clip_output=clip_output, p=1.0)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ actual = aug(x)
+ self.assert_close(actual, kornia.enhance.normalize_min_max(x), rtol=0.0, atol=0.0)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("clip_output", [None, True, False])
+ def test_quantized_input_gradient(self, clip_output):
+ # Repeated extrema with unequal weights expose the clamp's boundary gradient (#4436).
+ x = (torch.arange(16, dtype=torch.float64).repeat(2).reshape(1, 1, 4, 8) / 16).requires_grad_()
+ weights = torch.arange(32, dtype=torch.float64).reshape_as(x) / 32
+ if clip_output is None:
+ aug = kornia.augmentation.RandomAutoContrast(p=1.0)
+ else:
+ with pytest.warns(DeprecationWarning, match="clip_output"):
+ aug = kornia.augmentation.RandomAutoContrast(clip_output=clip_output, p=1.0)
+ actual = torch.autograd.grad((aug(x) * weights).sum(), x)[0]
+ expected = torch.autograd.grad((kornia.enhance.normalize_min_max(x) * weights).sum(), x)[0]
+ self.assert_close(actual, expected, rtol=0.0, atol=0.0)
@pytest.mark.slow
def test_gradcheck(self, device):
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 88791aec6..d82b856c9 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -1223,7 +1223,8 @@ class TestConventionAugmentationBase2D(BaseTester):
@pytest.mark.parametrize("clip_output", [False, True])
def test_autocontrast_empty_batch_4429(self, probability, clip_output, device, dtype):
data = torch.empty(0, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)
- augmentation = K.RandomAutoContrast(p=probability, clip_output=clip_output)
+ with pytest.warns(DeprecationWarning, match="clip_output"):
+ augmentation = K.RandomAutoContrast(p=probability, clip_output=clip_output)
output = augmentation(data)
replay = augmentation(data, params=augmentation._params)
for actual in (output, replay):