π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): keep adjust_gamma gradients finite at black pixels (#6255)
alp56ce34c3b47e
diff --git a/changelog.d/6255.fixed.md b/changelog.d/6255.fixed.mdnew file mode 100644index 000000000..3b9443ba2--- /dev/null+++ b/changelog.d/6255.fixed.md@@ -0,0 +1 @@+`adjust_gamma`, `AdjustGamma` and `RandomGamma` now return a zero gradient at black pixels (input `0`) for a gamma between 0 and 1, where `x ** gamma` has an infinite derivative. The gradient there was NaN on torch 2.14 and `inf` on earlier releases, so every image with a black pixel gave a non-finite input gradient. Output values are unchanged.diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex fd74a01d6..836b86026 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -400,7 +400,8 @@ def adjust_gamma(r"""Perform gamma correction on an image.Convention:- Applies gain * input ** gamma elementwise, then clamps to [0, 1].+ Applies gain * input ** gamma elementwise, then clamps to [0, 1]. For ``0 < gamma < 1`` the derivative of+ ``input ** gamma`` at a black pixel (``input == 0``) is infinite; the gradient there is 0 instead... image:: _static/img/adjust_contrast.png@@ -467,7 +468,15 @@ def adjust_gamma(if input.dtype == torch.float32:gamma = struct.unpack("f", struct.pack("f", gamma))[0]gain = struct.unpack("f", struct.pack("f", gain))[0]- return (input.pow(gamma) * gain).clamp(0.0, 1.0)+ if torch.is_grad_enabled() and input.requires_grad and 0.0 < gamma < 1.0:+ # As in the tensor path below.+ black = input == 0+ power = torch.where(+ black, torch.zeros_like(input), torch.where(black, torch.ones_like(input), input).pow(gamma)+ )+ else:+ power = input.pow(gamma)+ return (power * gain).clamp(0.0, 1.0)if isinstance(gamma, float):gamma = torch.tensor([gamma], device=input.device, dtype=input.dtype)@@ -490,8 +499,18 @@ def adjust_gamma(gamma = _make_factor_broadcastable(gamma, input)gain = _make_factor_broadcastable(gain, input)- # Apply the gamma correction- x_adjust: torch.Tensor = gain * torch.pow(input, gamma)+ # Apply the gamma correction. For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0, which the clamp+ # below turns into NaN (inf before torch 2.14). Black pixels then take the power of a safe base, keep their value+ # 0 ** gamma = 0 and get a zero gradient; gamma = 0 keeps 0 ** 0 = 1. The values are the same either way, so the+ # masking only runs when autograd records a gradient for the input.+ if torch.is_grad_enabled() and input.requires_grad:+ black = (input == 0) & (gamma > 0) & (gamma < 1)+ power = torch.where(+ black, torch.zeros_like(input), torch.pow(torch.where(black, torch.ones_like(input), input), gamma)+ )+ else:+ power = torch.pow(input, gamma)+ x_adjust: torch.Tensor = gain * power# Truncate between pixel valuesout: torch.Tensor = torch.clamp(x_adjust, 0.0, 1.0)diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex f8c84f145..5c408e5bf 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -3097,6 +3097,15 @@ class TestRandomGamma(BaseTester):self.assert_close(f(input), expected, low_tolerance=True)+ def test_black_pixel_gradient_is_finite(self, device, dtype):+ # gamma < 1 has an infinite derivative at black pixels; they get a zero gradient instead of NaN.+ image = torch.tensor([[[[0.0, 0.25, 0.5]]]], device=device, dtype=dtype).repeat(2, 3, 1, 1).requires_grad_()+ out = RandomGamma(gamma=(0.5, 0.5), p=1.0)(image)+ out.sum().backward()+ expected_grad = torch.tensor([0.0, 1.0, 0.5**0.5], device=device, dtype=dtype).expand_as(image)+ self.assert_close(out, image.detach().sqrt())+ self.assert_close(image.grad, expected_grad)+@pytest.mark.slowdef test_gradcheck(self, device):input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 994a372b7..aeae2104e 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -360,6 +360,24 @@ class TestAdjustGamma(BaseTester):gain = torch.tensor([0.7, 0.9], device=device, dtype=torch.float64, requires_grad=True)self.gradcheck(kornia.enhance.adjust_gamma, (image, gamma, gain))+ @pytest.mark.parametrize("gamma", [0.0, 0.25, 0.5, 0.9, 2.0])+ @pytest.mark.parametrize("scalar", [True, False])+ def test_black_pixel_gradient(self, device, dtype, gamma, scalar):+ # For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0; the gradient there is 0, as for the other+ # exponents. x = 1 is left out: the derivative of the output clamp at its bound differs across torch releases.+ image = torch.tensor([0.0, 0.25, 0.5], device=device, dtype=dtype).reshape(1, 1, 3).requires_grad_()+ param = gamma if scalar else torch.tensor([gamma], device=device, dtype=dtype)+ out = kornia.enhance.adjust_gamma(image, param)+ (grad,) = torch.autograd.grad(out.sum(), image)+ # in the image dtype, as adjust_gamma rounds the exponent+ exponent = torch.tensor(gamma, device=device, dtype=dtype)+ expected = image.detach().pow(exponent)+ expected_grad = exponent * image.detach().pow(exponent - 1)+ expected_grad[..., 0] = 0.0+ self.assert_close(out, expected)+ assert torch.isfinite(grad).all()+ self.assert_close(grad, expected_grad)+@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_scalar_export(self, device, dtype):image = torch.full((1, 2, 2), 0.4, device=device, dtype=dtype)