🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(augmentation): a single clamp for the unit-range input clamp when no gradient is recorded (#6267)
Dmytro Mishkin72d7e6f08358
diff --git a/changelog.d/6267.fixed.md b/changelog.d/6267.fixed.mdnew file mode 100644index 000000000..004f055e8--- /dev/null+++ b/changelog.d/6267.fixed.md@@ -0,0 +1,7 @@+The `[0, 1]` input clamp that range-dependent 2D intensity augmentations gained in #5980 is cheaper. A call that+records no reverse-mode gradient and carries no forward-mode tangent now costs a single `clamp`. A call that needs+either derivative costs a comparison with the clamped copy and a selection, instead of two bound comparisons, their+conjunction and a selection. Values and gradients are unchanged, apart from the sign of a zero: on MPS and under+`torch.compile` a `-0.0` pixel can now come back as `+0.0`, as `clamp` returns it there. On an i7-14700K CPU+(4 threads, batch 8, 256×256, float32), `RandomBrightness` and `RandomContrast` take about 300 µs per call instead of+830 µs, against about 240 µs in 0.8.3, which had no input clamp. On an RTX 4090 they are 1.2–1.4× faster.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex db5296110..5bcb86b6b 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -28,11 +28,24 @@ from kornia.geometry.keypoints import Keypointsdef _clamp_unit_range(input: Tensor) -> Tensor:"""Clamp ``input`` into ``[0, 1]`` with an identity gradient on the closed range.- ``torch.clamp``'s derivative at a bound is ``1`` on torch 2.5.1 and 2.9.1 and ``0`` on 2.14, and valid images+ ``torch.clamp``'s derivative at a bound is ``1`` on torch 2.5.1 and 2.9.1 and ``0`` on 2.14.0, and valid imagesoften hold exact ``0`` and ``1`` pixels. The values inside ``[0, 1]`` are therefore taken from ``input`` itself,so they keep their gradient on every torch version; values outside get the bound and a zero gradient.++ The values always equal ``input.clamp(0, 1)``, ``NaN`` included, so a call that records no gradient and+ carries no forward-mode tangent is that single clamp. Otherwise, select ``input`` where the clamp left it+ unchanged: one comparison against the clamped copy instead of two bound comparisons and their conjunction.+ Forward-mode tangents must keep the identity derivative even inside ``torch.no_grad()``. The sign of a zero is+ not part of the contract: ``clamp`` returns ``+0.0`` for ``-0.0`` on MPS and under Inductor (CPU and CUDA),+ while eager CPU and CUDA keep ``-0.0``."""- return torch.where((input >= 0.0) & (input <= 1.0), input, input.clamp(0.0, 1.0))+ clamped = input.clamp(0.0, 1.0)+ if (+ not (torch.is_grad_enabled() and input.requires_grad)+ and torch.autograd.forward_ad.unpack_dual(input).tangent is None+ ):+ return clamped+ return torch.where(clamped == input, input, clamped)class _PicklableCompileMixin:diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 73498dfdf..7170a409f 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -24,6 +24,7 @@ import pytestimport torchimport kornia.augmentation as K+from kornia.augmentation._2d.intensity.base import _clamp_unit_rangefrom kornia.augmentation.random_generator import RectangleEraseGeneratorfrom kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.enhance import (@@ -1459,6 +1460,37 @@ class TestIntensityColourConventions(BaseTester):class TestIntensityInputClamping(BaseTester):+ @pytest.mark.parametrize("forward_mode", ["jvp", "dual"])+ @pytest.mark.parametrize("grad_enabled", [False, True])+ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_input_clamp_preserves_forward_tangents(self, device, dtype, forward_mode, grad_enabled, requires_grad):+ image = torch.tensor([-0.5, -0.0, 0.0, 0.25, 1.0, 1.5], device=device, dtype=dtype)+ image.requires_grad_(requires_grad)+ tangent = torch.tensor([2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device=device, dtype=dtype)+ expected = torch.tensor([0.0, 3.0, 4.0, 5.0, 6.0, 0.0], device=device, dtype=dtype)+ # no_grad disables reverse-mode recording, but forward AD must still pass the tangent at both bounds.+ with torch.set_grad_enabled(grad_enabled):+ if forward_mode == "jvp":+ values, actual = torch.func.jvp(_clamp_unit_range, (image,), (tangent,))+ else:+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(image, tangent)+ values, actual = torch.autograd.forward_ad.unpack_dual(_clamp_unit_range(dual))+ self.assert_close(values, image.clamp(0.0, 1.0))+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("grad_enabled", [False, True])+ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_input_clamp_matches_clamp_on_zeros_nan_and_inf(self, device, dtype, grad_enabled, requires_grad):+ image = torch.tensor([-0.0, 0.0, float("nan"), -float("inf"), float("inf")], device=device, dtype=dtype)+ image.requires_grad_(requires_grad)+ with torch.set_grad_enabled(grad_enabled):+ actual = _clamp_unit_range(image)+ assert torch.equal(torch.isnan(actual), torch.isnan(image))+ finite = ~torch.isnan(image)+ # The sign of a zero is not pinned: clamp gives +0.0 for -0.0 on MPS and under Inductor, -0.0 in eager CPU/CUDA.+ self.assert_close(actual[finite], image.clamp(0.0, 1.0)[finite])+@pytest.mark.parametrize("name", ["ColorJiggle", "RandomGamma", "RandomPosterize"])def test_bicubic_overshoot_is_clamped_before_intensity(self, device, dtype, name):torch.manual_seed(0)@@ -1508,6 +1540,30 @@ class TestIntensityInputClamping(BaseTester):out.sum().backward()self.assert_close(image.grad, torch.ones_like(image))+ # Without a recorded gradient the input clamp is a single torch.clamp; with one it selects the input where the+ # clamp left it unchanged. Both must return the same values, and the recorded gradient is 1 inside [0, 1]+ # and 0 outside.+ @pytest.mark.parametrize(+ "factory",+ [lambda: K.RandomBrightness(brightness=(1.0, 1.0), p=1.0), lambda: K.ColorJiggle(0.0, 0.0, 0.0, 0.0, p=1.0)],+ ids=["RandomBrightness", "ColorJiggle"],+ )+ def test_unit_range_input_clamp_matches_with_and_without_a_gradient(self, device, dtype, factory):+ values = torch.tensor([-0.5, -0.0, 0.0, 0.25, 0.75, 1.0, 1.5, 2.0], device=device, dtype=dtype)+ image = values.reshape(1, 1, 2, 4).expand(1, 3, 2, 4).contiguous()+ expected = image.clamp(0.0, 1.0)+ with torch.no_grad():+ assert torch.equal(factory()(image), expected)+ assert torch.equal(factory()(image), expected)+ leaf = image.clone().requires_grad_()+ out = factory()(leaf)+ assert torch.equal(out.detach(), expected)+ out.sum().backward()+ interior = (image > 0.0) & (image < 1.0)+ outside = (image < 0.0) | (image > 1.0)+ assert torch.equal(leaf.grad[interior], torch.ones_like(leaf.grad[interior]))+ assert torch.equal(leaf.grad[outside], torch.zeros_like(leaf.grad[outside]))+@pytest.mark.parametrize("gamma", [0.5, 1.5])def test_gamma_gradient_outside_range_is_zero(self, device, dtype, gamma):image = torch.tensor([-0.5, 0.25, 0.5, 1.5], device=device, dtype=dtype).reshape(1, 1, 1, 4)