π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): avoid float16 epsilon underflow in Luv conversions (#5342)
NiteeshGowda728ffe7ac6c54a
diff --git a/changelog.d/5342.fixed.md b/changelog.d/5342.fixed.mdnew file mode 100644index 000000000..b504a35eb--- /dev/null+++ b/changelog.d/5342.fixed.md@@ -0,0 +1 @@+Fix `rgb_to_luv` and `luv_to_rgb` returning NaNs for float16 black pixels and their gradients.diff --git a/kornia/color/luv.py b/kornia/color/luv.pyindex 2845e1e08..d5399ea70 100644--- a/kornia/color/luv.py+++ b/kornia/color/luv.py@@ -41,7 +41,9 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:Args:image: RGB Image to be converted to Luv with shape :math:`(*, 3, H, W)`.- eps: for numerically stability when dividing.+ eps: for numerically stability when dividing. For float16 input a positive ``eps`` below+ :math:`2^{-14}`, the smallest normal float16 value, is raised to it: smaller values underflow to+ zero or overflow the backward pass.Returns:Luv version of the image with shape :math:`(*, 3, H, W)`.@@ -57,6 +59,10 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> 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}")+ # float16 cannot represent the default eps, and a too-small eps can overflow its backward.+ if image.dtype == torch.float16 and eps > 0.0:+ eps = max(eps, 6.103515625e-05)+# Convert from sRGB to Linear RGBlin_rgb = rgb_to_linear_rgb(image)@@ -92,7 +98,9 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:Args:image: Luv image to be converted to RGB with shape :math:`(*, 3, H, W)`.- eps: for numerically stability when dividing.+ eps: for numerically stability when dividing. For float16 input a positive ``eps`` below+ :math:`2^{-14}`, the smallest normal float16 value, is raised to it: smaller values underflow to+ zero or overflow the backward pass.Returns:Luv version of the image with shape :math:`(*, 3, H, W)`.@@ -108,6 +116,10 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> 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}")+ # float16 cannot represent the default eps, and a too-small eps can overflow its backward.+ if image.dtype == torch.float16 and eps > 0.0:+ eps = max(eps, 6.103515625e-05)+L: torch.Tensor = image[..., 0, :, :]u: torch.Tensor = image[..., 1, :, :]v: torch.Tensor = image[..., 2, :, :]diff --git a/tests/color/test_luv.py b/tests/color/test_luv.pyindex 38e9eb723..4160ede40 100644--- a/tests/color/test_luv.py+++ b/tests/color/test_luv.py@@ -253,3 +253,44 @@ class TestLuvToRgb(BaseTester):ops = kornia.color.LuvToRgb().to(device, dtype)fcn = kornia.color.luv_to_rgbself.assert_close(ops(img), fcn(img))++[email protected]("function", [kornia.color.rgb_to_luv, kornia.color.luv_to_rgb])+def test_luv_converters_float16_black_are_finite(function):+ x = torch.zeros(3, 1, 1, dtype=torch.float16, requires_grad=True)++ output = function(x)+ output.sum().backward()++ assert torch.isfinite(output).all()+ assert torch.isfinite(x.grad).all()+++ "half_dtype, scale, luv_atol, rgb_atol",+ [+ # A subnormal float16 eps overflows the backward of rgb_to_luv (1e-5) and luv_to_rgb (1e-8).+ (torch.float16, 1e-5, 5e-2, 2e-5),+ (torch.float16, 1e-8, 5e-2, 2e-5),+ # A float16 eps floor much larger than the smallest normal moves these values.+ (torch.float16, 1e-3, 5e-2, 2e-5),+ # bfloat16 represents the default eps and must keep it.+ (torch.bfloat16, 1e-4, 2e-3, 2e-5),+ ],+)+def test_luv_converters_half_dark_pixels_match_float32(half_dtype, scale, luv_atol, rgb_atol):+ colors = torch.tensor([[1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.5, 0.2]])+ rgb = (scale * colors).T.reshape(3, 1, -1).to(half_dtype).requires_grad_(True)+ luv = kornia.color.rgb_to_luv(rgb)+ luv.sum().backward()++ luv_input = kornia.color.rgb_to_luv(scale * colors.T.reshape(3, 1, -1)).to(half_dtype).requires_grad_(True)+ rgb_output = kornia.color.luv_to_rgb(luv_input)+ rgb_output.sum().backward()++ for tensor in (luv, rgb.grad, rgb_output, luv_input.grad):+ assert torch.isfinite(tensor).all()+ torch.testing.assert_close(luv.float(), kornia.color.rgb_to_luv(rgb.detach().float()), rtol=0.0, atol=luv_atol)+ torch.testing.assert_close(+ rgb_output.float(), kornia.color.luv_to_rgb(luv_input.detach().float()), rtol=0.0, atol=rgb_atol+ )