Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): skip ColorJitter's brightness step at the neutral factor 1 (#4893)

Ethan Stoner7380aed41d8f
diff --git a/changelog.d/4893.breaking.md b/changelog.d/4893.breaking.md
new file mode 100644
index 000000000..aa71cbbb8
--- /dev/null
+++ b/changelog.d/4893.breaking.md
@@ -0,0 +1,8 @@
+`ColorJitter` now skips its brightness step when every factor is the multiplier's neutral `1`, instead of `0`
+(#4785). Before, a batch whose brightness factors were all `0` came back unchanged while the same sample in a mixed
+batch came back black; now a factor of `0` gives a black image whatever the rest of the batch drew. Before, the
+factor `1` drawn by the default `brightness=0.0` still ran that step, which clamps into `[0, 1]`: an out-of-range
+input was clamped before any later step, and on torch releases whose `clamp` has a zero gradient at its bounds, such
+as 2.14, input pixels at exactly `0` or `1` got no gradient. Now the step is skipped; outputs for inputs in `[0, 1]`
+are unchanged, and the contrast and saturation steps still clamp when they run. With every step neutral,
+`ColorJitter` and `ColorJiggle` now return a copy of the input instead of the input tensor itself.
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 43fb14953..2ea6edad8 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -101,10 +101,13 @@ def _dispatch_color_steps(
Distribution.set_default_validate_args(validate_args)
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():
- input = steps[idx](input, factors[idx])
- return input
+ 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.
+ return output.clone() if output is input else output
def _brightness_step(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 0790130b6..5d1bcad7e 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -50,8 +50,7 @@ def _adjust_saturation(input: torch.Tensor, factor: torch.Tensor) -> torch.Tenso
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)
+_NEUTRAL = (1.0, 1.0, 1.0, 0.0)
_BRANCHES: _Steps = (_adjust_brightness, _adjust_contrast, _adjust_saturation, _adjust_hue)
@@ -93,17 +92,10 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):
- see :class:`ColorJiggle` for how the two classes relate. This class takes the brightness factor as
drawn, a multiplier whose identity is ``1``, and a scalar ``brightness`` above ``1`` draws from
``[0, 1 + brightness]``, as torchvision does.
- - 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
- are all ``0`` comes back unchanged instead of black, and ``ColorJitter(0, 0, 0, 0)`` clamps an
- out-of-range input. Tracked in
- `#4785 <https://github.com/kornia/kornia/issues/4785>`_.
+ - a step is skipped when every factor in the batch equals its neutral value -- ``1`` for brightness,
+ contrast and saturation, ``0`` for hue -- 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::
Because the brightness, contrast and saturation steps clamp, an all-negative input can come back as an
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 104ca955d..afea22752 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -573,27 +573,29 @@ class TestIntensityColourConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
self.assert_close(cls(0.0, 0.0, 0.0, 0.0, p=1.0)(image), image)
- # Issue #4785, ColorJitter: the brightness guard tests the factor against 0, not the multiplier's neutral 1,
- # so the factor 1 drawn by the default ``brightness=0.0`` still runs the clamping step. Run first, it
- # clamps an all-negative input to zero; a contrast or saturation factor above 1 applied before it lifts
- # part of the image first. A fix that skips a factor of 1 flips the brightness-first leg; removing the guard
- # altogether leaves it green, because the clamp is then #4430's. A fixed order without index 0 skips the
- # step and its clamp.
+ # Issue #4785, ColorJitter: the brightness guard tests the factor against the multiplier's neutral 1, so the
+ # factor 1 drawn by the default ``brightness=0.0`` skips the step and its clamp. Whether the brightness index
+ # comes before or after a contrast or saturation step, the output is that step's alone, and an all-negative
+ # input is no longer clamped to zero before the step can lift part of it. A fixed order without index 0
+ # skips the step as well.
# Snippet used to generate expected:
# torch.manual_seed(1234); neg = torch.rand(1, 3, 8, 8) - 1.0
# print(K.ColorJitter(p=1.0, order=order, contrast=(1.9, 1.9))(neg).aminmax())
@pytest.mark.parametrize(("step", "kwargs"), [(1, {"contrast": (1.9, 1.9)}), (2, {"saturation": (1.9, 1.9)})])
- def test_wart_color_jitter_default_brightness_step_clamps_4785(self, device, dtype, step, kwargs):
+ def test_convention_color_jitter_default_brightness_step_is_skipped_4785(self, device, dtype, step, kwargs):
torch.manual_seed(_FIXTURE_SEED)
negative = (torch.rand(1, 3, 8, 8) - 1.0).to(device=device, dtype=dtype)
+ step_only = K.ColorJitter(p=1.0, order=(step,), **kwargs)(negative)
+ assert float(step_only.min()) >= 0.0
+ assert float(step_only.max()) > 0.25
brightness_first = K.ColorJitter(p=1.0, order=(0, step), **kwargs)(negative)
- assert float(brightness_first.abs().max()) == 0.0
+ self.assert_close(brightness_first, step_only, atol=0, rtol=0)
step_first = K.ColorJitter(p=1.0, order=(step, 0), **kwargs)(negative)
- assert float(step_first.min()) >= 0.0
- assert float(step_first.max()) > 0.25
- # Leaving index 0 out of a fixed order skips the brightness step and its clamp.
+ self.assert_close(step_first, step_only, atol=0, rtol=0)
+ # With every factor neutral nothing clamps, whether or not a fixed order includes index 0.
above = torch.full((1, 3, 2, 2), 2.0, device=device, dtype=dtype)
self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(above), above)
+ self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0)(above), above)
# A fixed constructor `order` ignores a forward `order=` tensor; without one, a forward `order=` replaces
# ColorJiggle's drawn order, so leaving the hue step out lets a one-channel image through. ColorJitter's
@@ -623,13 +625,15 @@ class TestIntensityColourConventions(BaseTester):
with pytest.raises(BaseError, match="Not a color or gray tensor"):
saturation(four_channel)
- # Issue #4785: ColorJitter's brightness step multiplies (identity 1) but is guarded as if 0 were
- # neutral, so a batch whose factors are all 0 comes back unchanged while the same sample in a mixed
- # batch comes back black. The fix makes the all-zero batch black and flips the first assertion.
- def test_wart_color_jitter_zero_brightness_factor_is_skipped_4785(self, device, dtype):
+ # Issue #4785: ColorJitter's brightness step multiplies (identity 1), so a factor of 0 gives a black image
+ # whatever the other samples drew: a batch whose factors are all 0 comes back black, like the same sample in
+ # a mixed batch, and a fixed order that includes the step does the same.
+ def test_convention_color_jitter_zero_brightness_factor_is_black_4785(self, device, dtype):
image = torch.full((2, 3, 2, 2), 0.5, device=device, dtype=dtype)
aug = K.ColorJitter(brightness=(0.0, 0.0), p=1.0)
- assert torch.equal(aug(image), image)
+ assert float(aug(image).abs().max()) == 0.0
+ fixed = K.ColorJitter(brightness=(0.0, 0.0), p=1.0, order=(0,))
+ assert float(fixed(image).abs().max()) == 0.0
params = aug.forward_parameters(image.shape)
params["brightness_factor"] = torch.tensor([0.0, 1.0])
mixed = aug(image, params=params)
@@ -1537,3 +1541,16 @@ class TestIntensityColourConventions(BaseTester):
clamped = generator((20000, 3, height, width))
realised = float((clamped["heights"] > clamped["widths"]).float().mean())
assert realised == expected, (height, width, realised)
+
+ # With every step neutral both classes return a copy, on the Python guards (a sampled order) and on the
+ # torch.cond path (a fixed order) alike, so writing into the output leaves the input unchanged, as with p=0.
+ @pytest.mark.parametrize("cls", [K.ColorJiggle, K.ColorJitter])
+ @pytest.mark.parametrize("order", [None, (0, 1, 2, 3)])
+ def test_convention_color_neutral_steps_return_a_copy(self, device, dtype, cls, order):
+ image = torch.full((2, 3, 2, 2), 0.5, device=device, dtype=dtype)
+ original = image.clone()
+ output = cls(0.0, 0.0, 0.0, 0.0, p=1.0, order=order)(image)
+ self.assert_close(output, original)
+ assert output.untyped_storage().data_ptr() != image.untyped_storage().data_ptr()
+ output.fill_(-1.0)
+ self.assert_close(image, original)