π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): skip neutral ColorJitter adjustments (#4828)
NiteeshGowda720bc9a5ccb1af
diff --git a/changelog.d/4828.fixed.md b/changelog.d/4828.fixed.mdnew file mode 100644index 000000000..b006f0102--- /dev/null+++ b/changelog.d/4828.fixed.md@@ -0,0 +1 @@+`ColorJitter` skips a step whose factors are all neutral again, as it did before v0.9.0rc1, instead of computing every step and discarding the neutral ones: `ColorJitter(brightness=0.2)` accepts one- and four-channel images again, and an eager call no longer pays for the neutral colour-space round trips. Outputs for inputs that were accepted before are unchanged (#4813).diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex d21b8934a..43fb14953 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -16,7 +16,7 @@#from collections.abc import Sequence-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import Any, Callable, Dict, List, Optional, Tuple, Unionimport torchfrom torch.distributions import Distribution@@ -54,21 +54,74 @@ def _adjust_hue(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:return _contiguous_output(adjust_hue(input, factor * 2 * pi))-def _apply_transform_cond(- index: int,+_StepFn = Callable[[torch.Tensor, torch.Tensor], torch.Tensor]+_Steps = Tuple[_StepFn, _StepFn, _StepFn, _StepFn]+_FACTOR_KEYS = ("brightness_factor", "contrast_factor", "saturation_factor", "hue_factor")+++def _apply_order_cond(+ branches: _Steps,+ neutral: Tuple[float, float, float, float],+ order: Tuple[int, ...],input: torch.Tensor,- brightness: torch.Tensor,- contrast: torch.Tensor,- saturation: torch.Tensor,- hue: torch.Tensor,+ factors: Tuple[torch.Tensor, ...],) -> torch.Tensor:- if index == 0:- return torch.cond((brightness - 1 != 0).any(), _adjust_brightness, _identity, (input, brightness))- if index == 1:- return torch.cond((contrast != 1).any(), _adjust_contrast, _identity, (input, contrast))- if index == 2:- return torch.cond((saturation != 1).any(), _adjust_saturation, _identity, (input, saturation))- return torch.cond((hue != 0).any(), _adjust_hue, _identity, (input, hue))+ # torch.cond runs only the selected branch, so a neutral step is skipped without a data-dependent Python+ # branch and the loop stays fullgraph-compilable. It traces both branches, so it needs an RGB input.+ for idx in order:+ factor = factors[idx]+ input = torch.cond((factor != neutral[idx]).any(), branches[idx], _identity, (input, factor))+ return input+++def _dispatch_color_steps(+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ fixed_order: Optional[Tuple[int, ...]],+ cond_fn: Optional[Callable[[Tuple[int, ...], torch.Tensor, Tuple[torch.Tensor, ...]], torch.Tensor]],+ neutral: Tuple[float, float, float, float],+ steps: _Steps,+) -> torch.Tensor:+ """Apply the four colour steps in order, skipping a step whose factors all equal its ``neutral`` value.++ Shared by :class:`ColorJiggle` and :class:`ColorJitter`. A fixed order on an RGB input goes through ``cond_fn``+ (a :func:`_apply_order_cond` over the same ``neutral`` values) in eager and compiled mode alike; every other+ call uses Python ``.any()`` guards, which accept any channel count for the skipped steps. ``cond_fn`` is+ ``None`` for a random order and where Dynamo, which ``torch.cond`` requires, is unavailable.+ """+ factors = tuple(params[key] for key in _FACTOR_KEYS)+ if fixed_order is not None and cond_fn is not None and input.shape[-3] == 3:+ # An eager torch.cond enters Dynamo, whose one-time setup calls+ # ``Distribution.set_default_validate_args(False)`` process-wide; restore the caller's setting.+ validate_args = Distribution._validate_args+ try:+ return cond_fn(fixed_order, input, factors)+ finally:+ if Distribution._validate_args != validate_args:+ Distribution.set_default_validate_args(validate_args)++ order = fixed_order if fixed_order is not None else params["order"].tolist()+ for idx in order:+ if (factors[idx] != neutral[idx]).any():+ input = steps[idx](input, factors[idx])+ return input+++def _brightness_step(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return adjust_brightness(input, factor - 1)+++def _hue_step(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return adjust_hue(input, factor * 2 * pi)+++_NEUTRAL = (1.0, 1.0, 1.0, 0.0)+_STEPS: _Steps = (_brightness_step, adjust_contrast, adjust_saturation, _hue_step)+_BRANCHES: _Steps = (_adjust_brightness, _adjust_contrast, _adjust_saturation, _adjust_hue)+++def _apply_cond(order: Tuple[int, ...], input: torch.Tensor, factors: Tuple[torch.Tensor, ...]) -> torch.Tensor:+ return _apply_order_cond(_BRANCHES, _NEUTRAL, order, input, factors)class ColorJiggle(IntensityAugmentationBase2D):@@ -177,7 +230,7 @@ class ColorJiggle(IntensityAugmentationBase2D):self._fixed_order: Optional[Tuple[int, ...]] = order# torch.cond raises where Dynamo is unavailable (torch 2.5.1 on Python 3.13), so a fixed order keeps# the Python dispatch there. Checked here because Dynamo cannot trace the check inside forward.- self._cond_dispatch = order is not None and torch._dynamo.is_dynamo_supported()+ self._cond_fn = _apply_cond if order is not None and torch._dynamo.is_dynamo_supported() else Nonedef apply_transform(self,@@ -189,46 +242,5 @@ class ColorJiggle(IntensityAugmentationBase2D):# A fixed order runs the same torch.cond dispatcher in eager and compiled mode. Every torch.cond# branch is traced, including branches that are not selected at runtime, so the dispatcher is# restricted to RGB inputs: tracing the hue/saturation branches would otherwise reject the neutral- # one- and four-channel configurations accepted by the Python dispatch below.- if self._cond_dispatch and input.shape[-3] == 3:- # An eager torch.cond enters Dynamo, whose one-time setup calls- # ``Distribution.set_default_validate_args(False)`` process-wide; restore the caller's setting.- validate_args = Distribution._validate_args- try:- jittered = input- for idx in self._fixed_order:- jittered = _apply_transform_cond(- idx,- jittered,- params["brightness_factor"],- params["contrast_factor"],- params["saturation_factor"],- params["hue_factor"],- )- finally:- if Distribution._validate_args != validate_args:- Distribution.set_default_validate_args(validate_args)- return jittered-- transforms = [- lambda img: (- adjust_brightness(img, params["brightness_factor"] - 1)- if (params["brightness_factor"] - 1 != 0).any()- else img- ),- lambda img: (- adjust_contrast(img, params["contrast_factor"]) if (params["contrast_factor"] != 1).any() else img- ),- lambda img: (- adjust_saturation(img, params["saturation_factor"]) if (params["saturation_factor"] != 1).any() else img- ),- lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi) if (params["hue_factor"] != 0).any() else img,- ]-- jittered = input- order = self._fixed_order if self._fixed_order is not None else params["order"].tolist()- for idx in order:- t = transforms[idx]- jittered = t(jittered)-- return jittered+ # one- and four-channel configurations accepted by the Python dispatch.+ return _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, _STEPS)diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex a6a81520b..876548280 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -22,6 +22,13 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.color_jiggle import (+ _adjust_hue,+ _apply_order_cond,+ _contiguous_output,+ _dispatch_color_steps,+ _Steps,+)from kornia.constants import pifrom kornia.enhance import (adjust_brightness_accumulative,@@ -31,6 +38,27 @@ from kornia.enhance import ()+def _adjust_brightness(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_brightness_accumulative(input, factor))+++def _adjust_contrast(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_contrast_with_mean_subtraction(input, factor))+++def _adjust_saturation(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_saturation_with_gray_subtraction(input, factor))+++# The brightness step tests its factor against 0 instead of the neutral 1 (#4785).+_NEUTRAL = (0.0, 1.0, 1.0, 0.0)+_BRANCHES: _Steps = (_adjust_brightness, _adjust_contrast, _adjust_saturation, _adjust_hue)+++def _apply_cond(order: Tuple[int, ...], input: torch.Tensor, factors: Tuple[torch.Tensor, ...]) -> torch.Tensor:+ return _apply_order_cond(_BRANCHES, _NEUTRAL, order, input, factors)++class ColorJitter(IntensityAugmentationBase2D):r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.@@ -54,9 +82,9 @@ class ColorJitter(IntensityAugmentationBase2D):to the batch form (False).order: a fixed application order, as indices into (brightness, contrast, saturation, hue); a subsetapplies only those, and a repeated index raises ``ValueError``. ``None`` (the default) draws a random- order on every call. A fixed order makes the transform ``torch.compile`` fullgraph-safe. The parameter- generator still draws an ``order`` entry into ``_params``, and with a fixed order that entry is ignored,- including on replay.+ order on every call. A fixed order makes the transform ``torch.compile`` fullgraph-safe for RGB inputs.+ The parameter generator still draws an ``order`` entry into ``_params``, and with a fixed order that+ entry is ignored, including on replay.Shape:- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`- Output: :math:`(B, C, H, W)`@@ -65,16 +93,11 @@ class ColorJitter(IntensityAugmentationBase2D):- see :class:`ColorJiggle` for how the two classes relate. This class takes the brightness factor asdrawn, a multiplier whose identity is ``1``, and a scalar ``brightness`` above ``1`` draws from``[0, 1 + brightness]``, as torchvision does.- - a step's result is discarded only when every factor in the batch equals its guard value -- ``1`` for- contrast and saturation, ``0`` for hue and, as the #4785 warning below states, for brightness;- otherwise the brightness, contrast and (three-channel) saturation steps clamp the whole batch into- ``[0, 1]``. A fixed ``order`` without index ``0`` skips the brightness step.-- .. warning::- Every step in the order is computed even when its factors are neutral, so the hue step rejects any- channel count but three and the saturation step any but one or three whatever the factors:- ``ColorJitter(brightness=0.2)`` raises on a grayscale image. An eager call also pays for the neutral- steps' colour-space round trips. Tracked in `#4813 <https://github.com/kornia/kornia/issues/4813>`_.+ - a step is skipped when every factor in the batch equals its guard value -- ``1`` for contrast and+ saturation, ``0`` for hue and, as the #4785 warning below states, for brightness -- so a skipped step+ accepts any channel count. Otherwise the step runs on the whole batch, and the brightness, contrast and+ (three-channel) saturation steps clamp the whole batch into ``[0, 1]``. A fixed ``order`` without+ index ``0`` skips the brightness step... warning::The brightness step is skipped for a factor of ``0`` instead of the neutral ``1``: a batch whose factors@@ -155,6 +178,9 @@ class ColorJitter(IntensityAugmentationBase2D):if len(order) != len(set(order)):raise ValueError(f"`order` must not repeat an index; each adjustment applies at most once. Got {order}")self._fixed_order: Optional[Tuple[int, ...]] = order+ # torch.cond raises where Dynamo is unavailable (torch 2.5.1 on Python 3.13), so a fixed order keeps+ # the Python dispatch there. Checked here because Dynamo cannot trace the check inside forward.+ self._cond_fn = _apply_cond if order is not None and torch._dynamo.is_dynamo_supported() else None# native functionsself._brightness_fn = adjust_brightness_accumulative@@ -169,33 +195,13 @@ class ColorJitter(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- # torch.where (compute-then-select) rather than a Python `if ... .any() else img`:- # numerically identical (the op runs on the whole batch or not at all, exactly as the- # guard decided) but without a data-dependent branch, so it stays fullgraph-compilable.- transforms = [- lambda img: torch.where(- (params["brightness_factor"] != 0).any(), self._brightness_fn(img, params["brightness_factor"]), img- ),- lambda img: torch.where(- (params["contrast_factor"] != 1).any(), self._contrast_fn(img, params["contrast_factor"]), img- ),- lambda img: torch.where(- (params["saturation_factor"] != 1).any(), self._saturation_fn(img, params["saturation_factor"]), img- ),- lambda img: torch.where(- (params["hue_factor"] != 0).any(), self._hue_fn(img, params["hue_factor"] * 2 * pi), img- ),- ]-- # A fixed order is a static Python sequence (fullgraph); otherwise iterate the random- # per-call `order` tensor (inherently data-dependent, not fullgraph-compilable).- order: Sequence[int] = self._fixed_order if self._fixed_order is not None else params["order"]-- jittered = input- for idx in order:- jittered = transforms[idx](jittered)-- return jittered+ # The same dispatch as ColorJiggle: a fixed order on an RGB input runs torch.cond in eager and compiled+ # mode, every other call the Python guards, which accept any channel count for a skipped step.+ steps: _Steps = (self._brightness_fn, self._contrast_fn, self._saturation_fn, self._adjust_hue_turns)+ return _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, steps)++ def _adjust_hue_turns(self, input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return self._hue_fn(input, factor * 2 * pi)def compile(self,@@ -207,6 +213,18 @@ class ColorJitter(IntensityAugmentationBase2D):options: Optional[Dict[Any, Any]] = None,disable: bool = False,) -> "ColorJitter":+ # A fixed order on an RGB input runs every step through the torch.cond dispatcher, which is compiled+ # as one graph; the four helpers serve the random order and non-RGB inputs.+ if self._cond_fn is not None:+ self._cond_fn = torch.compile(+ self._cond_fn,+ fullgraph=fullgraph,+ dynamic=dynamic,+ backend=backend,+ mode=mode,+ options=options,+ disable=disable,+ )self._brightness_fn = torch.compile(self._brightness_fn,fullgraph=fullgraph,diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 7d3545d43..58afbb910 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -1823,6 +1823,80 @@ class TestColorJitter(BaseTester):fresh = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))assert torch.compile(fresh, fullgraph=True)(img).shape == img.shape+ @pytest.mark.device_agnostic+ def test_fixed_order_keeps_distribution_validation(self):+ # The eager torch.cond dispatch enters Dynamo, whose one-time setup turns off+ # torch.distributions argument validation process-wide. A fresh interpreter is needed because that+ # setup runs once per process, so an earlier Dynamo entry in this one would hide the leak.+ script = (+ "import torch\n"+ "from torch.distributions import Distribution\n"+ "from kornia.augmentation import ColorJitter\n"+ "Distribution.set_default_validate_args(True)\n"+ "ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))(torch.rand(2, 3, 8, 8))\n"+ "assert Distribution._validate_args, 'ColorJitter disabled Distribution validation'\n"+ )+ # Trusted, fixed command (the current interpreter running a literal script); no external input.+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", script],+ capture_output=True,+ text=True,+ check=False,+ timeout=300,+ )+ assert result.returncode == 0, result.stderr++ def test_fixed_order_falls_back_without_cond(self, device, dtype, monkeypatch):+ # torch.cond raises "requires dynamo support" where Dynamo is unavailable (torch 2.5.1 on Python+ # 3.13), so a fixed order must fall back to the Python dispatch there.+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ op = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ params = op.forward_parameters(image.shape)+ expected = op(image, params=params)+ monkeypatch.setattr(torch._dynamo, "is_dynamo_supported", lambda: False)+ fallback = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ assert torch.equal(fallback(image, params=params), expected)++ @pytest.mark.parametrize(+ ("step", "factors"),+ [+ (0, [0.0, 0.0]),+ (0, [1.0, 1.0]),+ (0, [0.0, 1.2]),+ (1, [1.0, 1.0]),+ (1, [1.0, 1.2]),+ (2, [1.0, 1.0]),+ (2, [1.0, 0.8]),+ (3, [0.0, 0.0]),+ (3, [0.0, 0.05]),+ ],+ ids=[+ "brightness-0",+ "brightness-1",+ "brightness-mixed",+ "contrast-1",+ "contrast-mixed",+ "saturation-1",+ "saturation-mixed",+ "hue-0",+ "hue-mixed",+ ],+ )+ def test_fixed_order_guards_match_sampled_order(self, device, dtype, step, factors):+ # A fixed order on an RGB input dispatches through torch.cond, a sampled order through Python guards+ # (#4813). Both must skip the same factors, and run a step on the whole batch when any factor in it is+ # not neutral: a skipped step returns the out-of-range pixels as they are, a step that runs clamps them,+ # and a hue step that runs zeroes the pixel whose largest channel is 0.+ pixels = torch.tensor([[-0.5, -0.5], [0.25, -0.2], [1.75, 0.0]], device=device, dtype=dtype)+ image = pixels.reshape(1, 3, 1, 2).repeat(2, 1, 1, 1)+ op = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(step,))+ params = op.forward_parameters(image.shape)+ key = ("brightness_factor", "contrast_factor", "saturation_factor", "hue_factor")[step]+ params[key] = torch.tensor(factors, device=params[key].device, dtype=params[key].dtype)+ params["order"] = torch.tensor([step], device=params["order"].device, dtype=params["order"].dtype)+ sampled = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0)+ assert torch.equal(op(image, params=params), sampled(image, params=params))+def test_color_jitter(self, device, dtype):if dtype == torch.float16:pytest.skip("not work for half-precision")@@ -2228,6 +2302,7 @@ class TestColorJitter(BaseTester):self.assert_close(f(input), expected)self.assert_close(f.transform_matrix, expected_transform)+ @pytest.mark.parametrize("fixed", [True, False], ids=["fixed-order", "sampled-order"])@pytest.mark.parametrize("jitter_kwargs,order",[@@ -2238,7 +2313,9 @@ class TestColorJitter(BaseTester):],ids=["brightness", "contrast", "saturation", "hue"],)- def test_compile_uses_helpers(self, device, dtype, jitter_kwargs, order):+ def test_compile_uses_helpers(self, device, dtype, jitter_kwargs, order, fixed):+ # .compile() must replace what apply_transform executes (#4038): the torch.cond dispatcher for a fixed+ # order on an RGB input, the four step helpers for a sampled order.compiled_graphs = []def backend(graph_module, _example_inputs):@@ -2250,8 +2327,9 @@ class TestColorJitter(BaseTester):device=device,dtype=dtype,)- f = ColorJitter(**jitter_kwargs, p=1.0, order=order)+ f = ColorJitter(**jitter_kwargs, p=1.0, order=order if fixed else None)params = f.forward_parameters(input.shape)+ params["order"] = torch.tensor(order, device=params["order"].device, dtype=params["order"].dtype)expected = f(input, params=params)assert not torch.equal(expected, input)diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 5ecc6e696..8f8ee010d 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -25,7 +25,7 @@ import torchimport kornia.augmentation as Kfrom kornia.augmentation.random_generator import RectangleEraseGenerator-from kornia.core.exceptions import BaseError, ImageError, ShapeError+from kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.enhance import (adjust_brightness,adjust_contrast,@@ -1489,21 +1489,20 @@ class TestIntensityColourConventions(BaseTester):with pytest.raises(ValueError, match="shape of"):K.ColorJiggle(*factors, p=1.0)(image)- # Issue #4813: ColorJitter computes every step in the order, neutral or not, so the hue and saturation steps- # reject a channel count that the configuration never asks them to touch -- where ColorJiggle, above, and- # torchvision accept it. A fix that skips neutral steps flips the non-RGB legs; the RGB leg is the control.+ # Issue #4813: ColorJitter skips a step whose factors are all neutral, so the hue and saturation steps accept+ # a channel count that the configuration never asks them to touch, as ColorJiggle and torchvision do, in the+ # random and the fixed order alike. A non-neutral hue still needs three channels.+ @pytest.mark.parametrize("order", [None, (0, 1, 2, 3)])@pytest.mark.parametrize("channels", [1, 3, 4])- def test_wart_color_jitter_computes_neutral_steps_4813(self, device, dtype, channels):+ def test_color_jitter_skips_neutral_steps_4813(self, device, dtype, channels, order):torch.manual_seed(_FIXTURE_SEED)image = torch.rand(2, channels, 5, 5).to(device=device, dtype=dtype)for factors in ((0.0, 0.0, 0.0, 0.0), (0.2, 0.0, 0.0, 0.0), (0.0, 0.2, 0.0, 0.0)):torch.manual_seed(_FORWARD_SEED)- if channels == 3:- assert K.ColorJitter(*factors, p=1.0)(image).shape == image.shape- else:- # Which neutral step raises first depends on the drawn order.- with pytest.raises((ValueError, ImageError)):- K.ColorJitter(*factors, p=1.0)(image)+ assert K.ColorJitter(*factors, p=1.0, order=order)(image).shape == image.shape+ if channels != 3:+ with pytest.raises(ValueError, match="shape of"):+ K.ColorJitter(hue=0.1, p=1.0, order=order)(image)# The erasing box is clamped from below as well as above: scale=(0, 0) still erases one pixel and a 1x1# image is always erased in full.