Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): avoid eager cond overhead for fixed color order (#5450)

Karnajeet Gosavi7cf74506910b
diff --git a/changelog.d/5450.fixed.md b/changelog.d/5450.fixed.md
new file mode 100644
index 000000000..c51edc71c
--- /dev/null
+++ b/changelog.d/5450.fixed.md
@@ -0,0 +1 @@
+Made the eager backward pass of `ColorJiggle` and `ColorJitter` with a fixed `order` about 30x faster (about 170 ms to 6 ms with gradients on a `(8, 3, 64, 64)` CPU batch) by selecting each step with `torch.where` instead of `torch.cond`. Every step is now computed even when its range is neutral, so without gradients a fixed order with a step configured off (for example `hue=0`) costs up to about 1.6x more than before.
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index cb9329238..624a4998a 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -20,7 +20,6 @@ from collections.abc import Sequence
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
-from torch.distributions import Distribution
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
@@ -31,13 +30,6 @@ 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))
@@ -66,11 +58,13 @@ def _apply_order_cond(
input: torch.Tensor,
factors: Tuple[torch.Tensor, ...],
) -> torch.Tensor:
- # 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.
+ # Every step runs, and torch.where keeps its output only when a factor in the batch is not neutral. There is
+ # no data-dependent Python branch, so eager and compiled mode run this same code path, and fullgraph
+ # compilation holds. A step runs even when it is skipped, so this path needs an RGB input.
for idx in order:
factor = factors[idx]
- input = torch.cond((factor != neutral[idx]).any(), branches[idx], _identity, (input, factor))
+ output = branches[idx](input, factor)
+ input = torch.where((factor != neutral[idx]).any(), output, input)
return input
@@ -85,28 +79,22 @@ def _dispatch_color_steps(
"""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.
+ (a :func:`_apply_order_cond` over the same ``neutral`` values) in eager and compiled mode alike. It computes
+ all four steps and selects each result with :func:`torch.where`. Every other call uses Python ``.any()``
+ guards, which run only the steps that apply and accept any channel count for the skipped ones. ``cond_fn`` is
+ ``None`` for a random order.
"""
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)
+ return cond_fn(fixed_order, input, factors)
order = fixed_order if fixed_order is not None else params["order"].tolist()
output = input
for idx in order:
if (factors[idx] != neutral[idx]).any():
output = steps[idx](output, factors[idx])
- # With every step skipped, return a copy, as the torch.cond path and ``p=0`` do, so that writing into the
- # output never changes the caller's input.
+ # With every step skipped, return a copy, as the fixed-order dispatcher and ``p=0`` do, so that writing into
+ # the output never changes the caller's input.
return output.clone() if output is input else output
@@ -231,9 +219,7 @@ class ColorJiggle(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
+ self._cond_fn = _apply_cond if order is not None else None
def apply_transform(
self,
@@ -242,8 +228,7 @@ 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.
+ # A fixed order on an RGB input runs the branch-free dispatcher in eager and compiled mode alike. It is
+ # restricted to RGB inputs because it runs the hue and saturation steps, which require three channels,
+ # even when they are skipped.
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.py
index 7ec8059cc..63b119633 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -166,9 +166,7 @@ class ColorJitter(_PicklableCompileMixin, 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
+ self._cond_fn = _apply_cond if order is not None else None
# native functions
self._brightness_fn = adjust_brightness_accumulative
@@ -183,8 +181,8 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- # 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.
+ # The same branch-free dispatch as ColorJiggle for fixed RGB orders; other inputs use 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)
@@ -212,8 +210,8 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):
"disable": disable,
},
)
- # 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.
+ # A fixed order on an RGB input runs every step through the branch-free dispatcher; 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,
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 843fcdbc0..340f20654 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -1341,7 +1341,7 @@ class TestColorJiggle(BaseTester):
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.
+ # Both fixed and sampled orders apply the same per-step transforms.
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)
@@ -1352,9 +1352,7 @@ class TestColorJiggle(BaseTester):
@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.
+ # A fresh interpreter makes this guard independent of any earlier Dynamo entry in the test process.
script = (
"import torch\n"
"from torch.distributions import Distribution\n"
@@ -1373,16 +1371,29 @@ class TestColorJiggle(BaseTester):
)
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.
+ def test_fixed_order_dispatch_on_every_platform(self, device, dtype, monkeypatch):
+ # The torch.where dispatcher needs no Dynamo, so a fixed order runs it where Dynamo is unavailable
+ # (torch 2.5.1 on Python 3.13) too: one code path on every platform.
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=(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 = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))
- assert torch.equal(fallback(image, params=params), expected)
+ without_dynamo = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))
+ assert without_dynamo._cond_fn is not None
+ assert torch.equal(without_dynamo(image, params=params), expected)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("augmentation", [ColorJiggle, ColorJitter])
+ def test_fixed_order_eager_does_not_call_cond(self, augmentation, monkeypatch):
+ def fail(*args, **kwargs):
+ raise AssertionError("eager fixed-order dispatch must not call torch.cond")
+
+ monkeypatch.setattr(torch, "cond", fail)
+ image = torch.rand(2, 3, 8, 8, requires_grad=True)
+ output = augmentation(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))(image)
+ output.sum().backward()
+ assert image.grad is not None
def test_dynamo_fixed_order(self, device, dtype):
image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype, requires_grad=True)
@@ -1759,7 +1770,7 @@ class TestColorJiggle(BaseTester):
image = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)
hue = kornia.color.rgb_to_hsv(image)[:, 0]
# A float64 range gives float64 factors. The random order and a fixed `order` apply the hue step
- # through separate functions (the per-step loop and the `torch.cond` branch table).
+ # through separate functions (the per-step loop and the fixed-order branch table).
aug = ColorJiggle(hue=torch.tensor((0.5, 0.5), dtype=torch.float64), p=1.0, order=order)
shifted = kornia.color.rgb_to_hsv(aug(image))[:, 0]
error = torch.remainder(shifted - hue, 2 * torch.pi) - torch.pi
@@ -1839,9 +1850,7 @@ class TestColorJitter(BaseTester):
@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.
+ # A fresh interpreter makes this guard independent of any earlier Dynamo entry in the test process.
script = (
"import torch\n"
"from torch.distributions import Distribution\n"
@@ -1860,16 +1869,17 @@ class TestColorJitter(BaseTester):
)
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.
+ def test_fixed_order_dispatch_on_every_platform(self, device, dtype, monkeypatch):
+ # The torch.where dispatcher needs no Dynamo, so a fixed order runs it where Dynamo is unavailable
+ # (torch 2.5.1 on Python 3.13) too: one code path on every platform.
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)
+ without_dynamo = ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))
+ assert without_dynamo._cond_fn is not None
+ assert torch.equal(without_dynamo(image, params=params), expected)
@pytest.mark.parametrize(
("step", "factors"),
@@ -1897,8 +1907,8 @@ class TestColorJitter(BaseTester):
],
)
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
+ # A fixed order on an RGB input uses tensor selection, a sampled order uses Python guards. 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)
@@ -2341,8 +2351,8 @@ class TestColorJitter(BaseTester):
ids=["brightness", "contrast", "saturation", "hue"],
)
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.
+ # .compile() must replace what apply_transform executes (#4038): the fixed-order dispatcher for RGB,
+ # or the four step helpers for a sampled order.
compiled_graphs = []
def backend(graph_module, _example_inputs):
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index f027a32ea..8d21407c9 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -1358,7 +1358,7 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
# Issue #4807: unpickling passes each uncompiled callable to ``torch.compile`` again, with the arguments of
# the last ``compile()`` call; a second ``compile()`` keeps the first, uncompiled callables for pickling, and a
- # fixed ColorJitter order also compiles (and so must restore) the torch.cond dispatcher.
+ # fixed ColorJitter order also compiles (and so must restore) the fixed-order dispatcher.
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
@pytest.mark.parametrize(
"name", ["RandomGaussianIllumination", "RandomGaussianBlur", "ColorJitter", "ColorJitterFixedOrder"]