π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf: accelerate ColorJiggle eager and compiled execution (#4717)
Dmytro Mishkin525c08c32d19
diff --git a/changelog.d/4717.added.md b/changelog.d/4717.added.mdnew file mode 100644index 000000000..3c7cee993--- /dev/null+++ b/changelog.d/4717.added.md@@ -0,0 +1 @@+`ColorJiggle` now accepts a fixed `order` for deterministic application and full-graph compilation on RGB inputs.diff --git a/changelog.d/4717.fixed.md b/changelog.d/4717.fixed.mdnew file mode 100644index 000000000..970b77bd9--- /dev/null+++ b/changelog.d/4717.fixed.md@@ -0,0 +1 @@+`ColorJiggle` and `adjust_saturation` now avoid a redundant RGB-to-HSV round trip in float32 and float64, improving eager and compiled performance. At tied RGB extrema, the direct formula uses PyTorch's symmetric max/min subgradient instead of the arbitrary first-channel subgradient from the HSV branch.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex 6f079b24a..c2cb160e8 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -78,9 +78,9 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):then expands it at application time, while the plasma classes with ``same_on_batch=True`` store anexpanded ``(B, C, H, W)`` view with shared storage for the batch; ``RandomPlasmaShadow`` stores``(B, 1, H, W)``. :class:`ColorJiggle` and :class:`ColorJitter` both draw an application ``order``;- it is shared by the whole batch. Only :class:`ColorJitter` takes a fixed ``order`` constructor- argument. Without one, on either class, an ``order`` tensor passed as a forward keyword, or- replayed ``params``, replaces the drawn order for that call; a fixed order ignores both.+ it is shared by the whole batch. Both take a fixed ``order`` constructor argument. Without one,+ an ``order`` tensor passed as a forward keyword, or replayed ``params``, replaces the drawn order+ for that call; a fixed order ignores both.- where a class documents bounds for a parameter, an explicit range outside them usually raises atconstruction. These checks run on the forward pass instead: :class:`RandomGamma`'s non-negativity checkson ``gamma`` and ``gain``, which live in :func:`kornia.enhance.adjust_gamma`, anddiff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex fae81fa25..b29228f61 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -15,6 +15,7 @@# limitations under the License.#+from collections.abc import Sequencefrom typing import Any, Dict, List, Optional, Tuple, Unionimport torch@@ -25,6 +26,50 @@ from kornia.constants import pifrom kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation+def _contiguous_output(output: torch.Tensor) -> torch.Tensor:+ return output.contiguous()+++def _identity(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ # torch.cond rejects an output that aliases an input, so a neutral factor returns a copy. Every+ # branch returns a contiguous tensor: their forward and backward metadata must agree under Inductor,+ # which rejects preserve_format branches for channels-last and transposed inputs.+ return input.contiguous().clone()+++def _adjust_brightness(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_brightness(input, factor - 1))+++def _adjust_contrast(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_contrast(input, factor))+++def _adjust_saturation(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ return _contiguous_output(adjust_saturation(input, factor))+++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,+ input: torch.Tensor,+ brightness: torch.Tensor,+ contrast: torch.Tensor,+ saturation: torch.Tensor,+ hue: 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))++class ColorJiggle(IntensityAugmentationBase2D):r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.@@ -41,6 +86,10 @@ class ColorJiggle(IntensityAugmentationBase2D):same_on_batch: apply the same transformation across the batch.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).+ order: a fixed application order, as indices into (brightness, contrast, saturation, hue); a subset+ applies only those. ``None`` (the default) draws a random 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)`@@ -53,9 +102,8 @@ class ColorJiggle(IntensityAugmentationBase2D):the ``order`` diverges, because this class draws it on the sampler device where:class:`ColorJitter` always draws it on the CPU; and this class returns its factors in the dtypeof its constructor arguments (``float32`` for Python floats) where :class:`ColorJitter` keeps- the sampler dtype. Only :class:`ColorJitter` takes an ``order`` constructor argument that- replaces its sampled order with a fixed one. The classes use different primitives for three- adjustments:+ the sampler dtype. Both classes accept an ``order`` constructor argument that replaces the sampled+ order with a fixed one. The classes use different primitives for three adjustments::func:`kornia.enhance.adjust_brightness` against:func:`kornia.enhance.adjust_brightness_accumulative`,:func:`kornia.enhance.adjust_contrast` against@@ -72,6 +120,13 @@ class ColorJiggle(IntensityAugmentationBase2D):suit the steps that actually run: the saturation and hue steps need three channels, but``ColorJiggle(0, 0, 0, 0)`` and a brightness- or contrast-only configuration accept any channelcount, including the ``C = 1`` and ``C = 4`` on which :class:`ColorJitter` raises.+ - a fixed ``order`` makes a three-channel transform ``torch.compile`` fullgraph-safe while preserving+ lazy neutral-factor skips: eager and compiled calls both dispatch each step through ``torch.cond``,+ and the result is contiguous even for a channels-last input. The default sampled tensor order, and+ neutral one- and four-channel configurations, keep the Python dispatch path. Differentiating a+ compiled fixed-order transform needs torch ``2.7`` or newer with the ``inductor`` backend: on+ ``2.5.1`` and ``2.6.0`` the forward pass compiles but the backward pass raises, while the+ ``aot_eager`` backend works on each.- the ``[0, 2]`` bound applies to both argument forms: an explicit ``brightness`` range reachingabove ``2``, such as ``(0.0, 3.0)``, and a scalar whose implied ``[1 - x, 1 + x]`` does, such as``1.5``, are both rejected at construction with@@ -124,6 +179,7 @@ class ColorJiggle(IntensityAugmentationBase2D):same_on_batch: bool = False,p: float = 1.0,keepdim: bool = False,+ order: Optional[Sequence[int]] = None,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self.brightness = brightness@@ -131,6 +187,13 @@ class ColorJiggle(IntensityAugmentationBase2D):self.saturation = saturationself.hue = hueself._param_generator = rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)+ if order is not None:+ order = tuple(int(i) for i in order)+ if not set(order) <= {0, 1, 2, 3}:+ raise ValueError(+ f"`order` entries must be in 0..3 (brightness, contrast, saturation, hue). Got {order}"+ )+ self._fixed_order: Optional[Tuple[int, ...]] = orderdef apply_transform(self,@@ -139,6 +202,23 @@ class ColorJiggle(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ # 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._fixed_order is not None and input.shape[-3] == 3:+ 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"],+ )+ return jittered+transforms = [lambda img: (adjust_brightness(img, params["brightness_factor"] - 1)@@ -155,7 +235,8 @@ class ColorJiggle(IntensityAugmentationBase2D):]jittered = input- for idx in params["order"].tolist():+ 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)diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 7a2d3a6a2..67a505234 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -67,7 +67,7 @@ class ColorJitter(IntensityAugmentationBase2D):``order`` diverges, because this class always draws it on the CPU where :class:`ColorJiggle`draws it on the sampler device; and this class keeps the sampler dtype for its factors where:class:`ColorJiggle` returns them in the dtype of its constructor arguments (``float32`` for- Python floats). Only this class takes an ``order`` constructor argument that replaces the+ Python floats). Both classes accept an ``order`` constructor argument that replaces thesampled order with a fixed one. The classes use different primitives for three adjustments::func:`kornia.enhance.adjust_brightness_accumulative` against:func:`kornia.enhance.adjust_brightness`,diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.pyindex c15bf4c30..d41b54cf6 100644--- a/kornia/augmentation/_2d/intensity/saturation.py+++ b/kornia/augmentation/_2d/intensity/saturation.py@@ -45,12 +45,13 @@ class RandomSaturation(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:- - the input must have three channels: the scaling is computed in HSV, and any other channel count- raises a ``ValueError`` on the forward pass.+ - the input must have three channels: the scaling is defined on the HSV saturation, and any other+ channel count raises a ``ValueError`` on the forward pass.- the drawn factor reaches :func:`kornia.enhance.adjust_saturation` unchanged -- it is notre-based the way :class:`RandomBrightness` re-bases its own -- and ``1.0`` is the identity for a- pixel with no negative channel. That primitive round-trips through HSV, so the identity holds only- up to floating-point error, and the error is larger in half precision than in ``float32``.+ pixel with no negative channel. That primitive divides by the value channel plus a small epsilon,+ and in half precision and integer dtypes it round-trips through HSV, so the identity holds only up+ to floating-point error, and the error is larger in half precision than in ``float32``.- there is no final RGB clamp, but the primitive clamps the HSV saturation component into``[0, 1]``. An out-of-range RGB input can remain outside that interval or be mapped into it. At afactor of ``1.0`` a pixel above ``1`` with no negative channel comes back unchanged, while a pixeldiff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex d54d154be..4ae62d98f 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -187,16 +187,42 @@ def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -torch.Size([2, 3, 3, 3])"""- # convert the rgb image to hsv- x_hsv: torch.Tensor = rgb_to_hsv(image)+ KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")+ if len(image.shape) < 3 or image.shape[-3] != 3:+ raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- # perform the conversion- x_adjusted: torch.Tensor = adjust_saturation_raw(x_hsv, factor)+ # Reordering the HSV arithmetic has visibly different rounding in half precision (up to+ # ~7e-3 in float16 and ~6e-2 in bfloat16 over the unit cube). Keep the established path there;+ # the direct formula below agrees to float32 precision and targets the common augmentation dtype.+ if not image.is_floating_point() or image.dtype in (torch.float16, torch.bfloat16):+ return hsv_to_rgb(adjust_saturation_raw(rgb_to_hsv(image), factor))- # convert back to rgb- out: torch.Tensor = hsv_to_rgb(x_adjusted)+ if isinstance(factor, float):+ factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)+ else:+ factor = factor.to(image.device, image.dtype)- return out+ while len(factor.shape) != len(image.shape):+ factor = factor[..., None]+ if factor.shape[-3] != 1:+ raise ValueError(f"Factor must hold one value per image, not per channel. Got shape {factor.shape}")++ # Scaling saturation in HSV keeps value (the maximum RGB channel) and hue fixed, so it is+ # equivalent to scaling each channel's distance from the minimum RGB channel. Expressing that+ # relation directly avoids materialising an HSV image and the expensive HSV-to-RGB sextant+ # selection. Keep rgb_to_hsv's guarded divisors so gradients stay finite at black and+ # grayscale pixels.+ max_rgb = image.amax(dim=-3, keepdim=True)+ min_rgb = image.amin(dim=-3, keepdim=True)+ delta = max_rgb - min_rgb+ value_divisor = torch.where(max_rgb == 0, torch.ones_like(max_rgb), max_rgb + 1e-8)+ saturation = delta / value_divisor+ saturation = torch.clamp(saturation * factor, min=0, max=1)++ adjusted_delta = max_rgb * saturation+ delta_divisor = torch.where(delta == 0, torch.ones_like(delta), delta)+ return (image - min_rgb) * (adjusted_delta / delta_divisor) + (max_rgb - adjusted_delta)def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex e264720e6..8f73a4740 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -1333,6 +1333,55 @@ class TestColorJiggle(BaseTester):res = f(input)self.assert_close(res[0], res[1])+ def test_fixed_order(self, device, dtype):+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ op = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))+ params = op.forward_parameters(image.shape)+ expected = op(image, params=params)+ params["order"] = torch.tensor([3, 2, 1, 0], device=device, dtype=torch.long)+ self.assert_close(op(image, params=params), expected)+ # The fixed order dispatches through torch.cond, the sampled order through Python branches.+ params["order"] = torch.tensor([0, 1, 2, 3], device=device, dtype=torch.long)+ sampled = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0)+ assert torch.equal(sampled(image, params=params), expected)+ with pytest.raises(ValueError, match=r"entries must be in 0\.\.3"):+ ColorJiggle(order=(0, 1, 9))++ def test_dynamo_fixed_order(self, device, dtype):+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype, requires_grad=True)+ op = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ params = op.forward_parameters(image.shape)+ compiled = torch.compile(op, fullgraph=True)+ expected = op(image, params=params)+ actual = compiled(image, params=params)+ self.assert_close(actual, expected)+ expected_grad = torch.autograd.grad(expected.sum(), image, retain_graph=True)[0]+ actual_grad = torch.autograd.grad(actual.sum(), image, retain_graph=True)[0]+ self.assert_close(actual_grad, expected_grad)++ # The full forward samples factors in graph while using the fixed application order.+ fresh = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ assert torch.compile(fresh, fullgraph=True)(image).shape == image.shape++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("layout", ["channels_last", "transposed"])+ def test_dynamo_fixed_order_noncontiguous(self, layout):+ image = torch.rand(2, 3, 8, 10)+ if layout == "channels_last":+ image = image.to(memory_format=torch.channels_last)+ else:+ image = image.transpose(-1, -2)+ image.requires_grad_()++ op = ColorJiggle(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)+ actual = torch.compile(op, fullgraph=True)(image, params=params)+ self.assert_close(actual, expected)+ expected_grad = torch.autograd.grad(expected.sum(), image, retain_graph=True)[0]+ actual_grad = torch.autograd.grad(actual.sum(), image)[0]+ self.assert_close(actual_grad, expected_grad)+def _get_expected_brightness(self, device, dtype):return torch.tensor([diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 809d77c42..92e9e0a1f 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -854,9 +854,9 @@ class TestIntensityColourConventions(BaseTester):self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(above), above)# Row 6c-08, the order and channel-count details:- # - a fixed constructor `order` ignores a forward `order=` tensor;- # - ColorJiggle has no constructor order, and a forward `order=` tensor replaces the drawn one, so- # leaving the hue step out lets a one-channel image through;+ # - on ColorJiggle and ColorJitter, a fixed constructor `order` ignores a forward `order=` tensor;+ # - without a constructor order, a forward `order=` tensor replaces ColorJiggle's drawn one, so leaving+ # the hue step out lets a one-channel image through;# - ColorJitter's saturation step (adjust_saturation_with_gray_subtraction) rejects four channels,# clamps a three-channel image, and returns a one-channel image unchanged.# Snippet used to generate expected:@@ -876,6 +876,8 @@ class TestIntensityColourConventions(BaseTester):fixed = K.ColorJitter(brightness=(0.5, 0.5), order=(1,), p=1.0)torch.manual_seed(_FORWARD_SEED)assert torch.equal(fixed(image, order=torch.tensor([0])), fixed(image))+ fixed_jiggle = K.ColorJiggle(brightness=(0.5, 0.5), order=(1,), p=1.0)+ assert torch.equal(fixed_jiggle(image, order=torch.tensor([0])), fixed_jiggle(image))assert float((K.ColorJitter(brightness=(0.5, 0.5), p=1.0, order=(0,))(image) - image).abs().max()) > 0.1gray = image[:, :1].contiguous()diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 81cb451e3..640158578 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -126,6 +126,54 @@ class TestAdjustSaturation(BaseTester):f = kornia.enhance.AdjustSaturation(torch.ones(2))self.assert_close(f(data), expected)+ def test_saturation_matches_hsv_reference_per_batch_factor(self, device, dtype):+ # Keep adjust_saturation's HSV semantics while allowing its implementation to avoid+ # materializing an HSV image. The values avoid hue-sector boundaries, where equivalent+ # formulas can legitimately differ by a small floating-point rounding error.+ image = torch.tensor(+ [+ [[[0.2, 0.4]], [[0.8, 0.7]], [[0.5, 0.1]]],+ [[[0.9, 0.3]], [[0.2, 0.8]], [[0.6, 0.5]]],+ ],+ device=device,+ dtype=dtype,+ )+ factor = torch.tensor([0.0, 1.5], device=device, dtype=dtype)++ hsv = kornia.color.rgb_to_hsv(image)+ expected_hsv = hsv.clone()+ expected_hsv[:, 1:2] = (hsv[:, 1:2] * factor[:, None, None, None]).clamp(0, 1)+ expected = kornia.color.hsv_to_rgb(expected_hsv)++ self.assert_close(kornia.enhance.adjust_saturation(image, factor), expected, low_tolerance=True)++ def test_zero_delta_gradient_is_finite(self, device, dtype):+ image = torch.tensor([0.0, 0.5], device=device, dtype=dtype).view(2, 1, 1, 1).expand(2, 3, 2, 2).clone()+ image.requires_grad_()+ result = kornia.enhance.adjust_saturation(image, 1.5)+ (gradient,) = torch.autograd.grad(result.sum(), image)+ assert torch.isfinite(result).all()+ assert torch.isfinite(gradient).all()++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("dtype", [torch.uint8, torch.int32])+ def test_integer_input_matches_hsv_reference(self, dtype):+ image = torch.tensor([1, 0, 0], dtype=dtype).view(1, 3, 1, 1)+ expected = kornia.color.hsv_to_rgb(kornia.enhance.adjust_saturation_raw(kornia.color.rgb_to_hsv(image), 0.5))+ self.assert_close(kornia.enhance.adjust_saturation(image, 0.5), expected)++ def test_per_channel_factor_raises(self, device, dtype):+ image = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)+ with pytest.raises(ValueError):+ kornia.enhance.adjust_saturation(image, torch.ones(2, 3, device=device, dtype=dtype))++ @pytest.mark.device_agnostic+ def test_tied_extrema_use_symmetric_subgradient(self):+ image = torch.tensor([0.8, 0.8, 0.2], dtype=torch.float64).view(1, 3, 1, 1).requires_grad_()+ result = kornia.enhance.adjust_saturation(image, 0.5)+ (gradient,) = torch.autograd.grad(result.sum(), image)+ self.assert_close(gradient.flatten(), torch.tensor([1.25, 1.25, 0.5], dtype=torch.float64))+def test_saturation_with_gray_subtraction_one_batch(self, device, dtype):data = torch.tensor([@@ -145,6 +193,11 @@ class TestAdjustSaturation(BaseTester):img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)self.gradcheck(kornia.enhance.adjust_saturation, (img, 2.0))+ def test_gradcheck_factor(self, device):+ img = torch.rand(2, 3, 2, 3, device=device, dtype=torch.float64)+ factor = torch.tensor([0.8, 1.2], device=device, dtype=torch.float64)+ self.gradcheck(kornia.enhance.adjust_saturation, (img, factor))+def test_gradcheck_with_gray_subtraction(self, device):batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)