π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): compute psnr for integer and bool images in float32 (#5552)
εΊζ’η357d9ec7ba2e
diff --git a/changelog.d/5552.breaking.md b/changelog.d/5552.breaking.mdnew file mode 100644index 000000000..465779d15--- /dev/null+++ b/changelog.d/5552.breaking.md@@ -0,0 +1,7 @@+`psnr`, `psnr_loss` and `PSNRLoss` now compute integer and bool images in float32, as `ssim` does, and compare the+two images in their promoted dtype (#5536). Two integer or bool images give the value of their float32 copies as a+float32 tensor. Previously they raised torch's dtype error, except on MPS with torch 2.5.1, where `uint8`, `int16`,+`int32` and `bool` pairs returned wrong values and `int64` aborted the process. An integer image paired with a+float16 or bfloat16 image now gives a float32 result; previously the result was in the half dtype. Two images of+different dtypes no longer abort the process on MPS. Pixel values are not rescaled, and two floating-point images of+one dtype are unchanged.diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.pyindex 9eaf88e13..cb3cd6169 100644--- a/kornia/metrics/psnr.py+++ b/kornia/metrics/psnr.py@@ -46,6 +46,11 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.TenReturn:the computed loss as a scalar.+ .. note::+ Integer and bool images are converted to float32, as in :func:`~kornia.metrics.ssim`, and the two images are+ compared in their promoted dtype. An integer image paired with a float16 or bfloat16 image therefore gives a+ float32 result. Pixel values are not rescaled.+Examples:>>> ones = torch.ones(1)>>> psnr(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)@@ -64,4 +69,13 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tenif image.shape != target.shape:raise TypeError(f"Expected tensors of equal shapes, but got {image.shape} and {target.shape}")+ # mse has no integer kernel; compute integer images in float32 as ssim does.+ if not image.is_floating_point() and not image.is_complex():+ image = image.to(torch.float32)+ if not target.is_floating_point() and not target.is_complex():+ target = target.to(torch.float32)+ # Give mse_loss one dtype: on two dtypes it aborts the process on MPS, and its backward raises on torch 2.5.1.+ dtype = torch.promote_types(image.dtype, target.dtype)+ image, target = image.to(dtype), target.to(dtype)+return 10.0 * torch.log10(max_val**2 / mse(image, target, reduction="mean"))diff --git a/tests/losses/test_psnr.py b/tests/losses/test_psnr.pyindex 7342a7997..b5458db8a 100644--- a/tests/losses/test_psnr.py+++ b/tests/losses/test_psnr.py@@ -75,6 +75,15 @@ class TestPSNRLoss(BaseTester):self.assert_close(op(*args), op_module(pred, target))+ def test_integer_images(self, device):+ # psnr_loss and PSNRLoss inherit the float32 computation of integer images from psnr (#5536).+ generator = torch.Generator().manual_seed(0)+ pred = (torch.rand(2, 3, 3, 2, generator=generator) * 255).to(torch.uint8).to(device)+ target = (torch.rand(2, 3, 3, 2, generator=generator) * 255).to(torch.uint8).to(device)+ expected = kornia.losses.psnr_loss(pred.float(), target.float(), 255.0)+ self.assert_close(kornia.losses.psnr_loss(pred, target, 255.0), expected, rtol=0, atol=0)+ self.assert_close(kornia.losses.PSNRLoss(255.0)(pred, target), expected, rtol=0, atol=0)+def test_gradcheck(self, device, dtype):dtype = torch.float64pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)diff --git a/tests/metrics/test_psnr_metric.py b/tests/metrics/test_psnr_metric.pyindex db00fde3b..e35b5be51 100644--- a/tests/metrics/test_psnr_metric.py+++ b/tests/metrics/test_psnr_metric.py@@ -30,6 +30,73 @@ class TestPsnr(BaseTester):actual = kornia.metrics.psnr(sample, 1.2 * sample, 2.0)self.assert_close(actual, expected)+ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int64, torch.bool])+ def test_integer_images_match_the_float32_result(self, device, image_dtype):+ # Integer images are computed in float32, as ssim computes them (#5536).+ generator = torch.Generator().manual_seed(0)+ image = (torch.rand(2, 3, 9, 13, generator=generator) * 255).to(device)+ target = (torch.rand(2, 3, 9, 13, generator=generator) * 255).to(device)+ if image_dtype == torch.bool:+ # threshold: a plain cast to bool makes both images all True, and identical images give inf+ image, target, max_val = image > 127, target > 127, 1.0+ else:+ image, target, max_val = image.to(image_dtype), target.to(image_dtype), 255.0+ expected = kornia.metrics.psnr(image.float(), target.float(), max_val)+ actual = kornia.metrics.psnr(image, target, max_val)+ assert actual.dtype == torch.float32+ assert torch.isfinite(expected)+ self.assert_close(actual, expected, rtol=0, atol=0)++ @pytest.mark.parametrize("partner_dtype", [torch.float16, torch.bfloat16, torch.float64])+ def test_integer_image_with_a_floating_partner(self, device, partner_dtype):+ # The integer image counts as float32 and the pair is computed in the promoted dtype, as in ssim, so a half+ # partner gives float32, not the half dtype. Given two dtypes, mse_loss aborts the process on MPS and its+ # backward raises on torch 2.5.1 (#5536).+ if device.type == "mps" and partner_dtype == torch.float64:+ pytest.skip("MPS has no float64")+ generator = torch.Generator().manual_seed(0)+ image = (torch.rand(2, 3, 9, 13, generator=generator) * 255).to(torch.uint8).to(device)+ partner = (torch.rand(2, 3, 9, 13, generator=generator) * 255).round().to(device, partner_dtype)+ compute_dtype = torch.promote_types(torch.float32, partner_dtype)+ expected = kornia.metrics.psnr(image.to(compute_dtype), partner.to(compute_dtype), 255.0)+ for actual in (kornia.metrics.psnr(image, partner, 255.0), kornia.metrics.psnr(partner, image, 255.0)):+ assert actual.dtype == compute_dtype+ self.assert_close(actual, expected, rtol=0, atol=0)+ partner.requires_grad_()+ kornia.metrics.psnr(image, partner, 255.0).backward()+ assert partner.grad is not None+ assert partner.grad.dtype == partner_dtype++ @pytest.mark.parametrize(+ "dtypes",+ [+ (torch.float16, torch.float32),+ (torch.bfloat16, torch.float32),+ (torch.float16, torch.bfloat16),+ (torch.float32, torch.float64),+ ],+ ids=["f16-f32", "bf16-f32", "f16-bf16", "f32-f64"],+ )+ def test_two_floating_dtypes(self, device, dtypes):+ # Two floating images of different dtypes are compared in their promoted dtype, in either order, and each+ # gradient keeps its image's dtype. Given two dtypes, mse_loss aborts the process on MPS and its backward+ # raises on torch 2.5.1 (#5536).+ if device.type == "mps" and torch.float64 in dtypes:+ pytest.skip("MPS has no float64")+ generator = torch.Generator().manual_seed(0)+ image = torch.rand(2, 3, 9, 13, generator=generator).to(device, dtypes[0])+ target = torch.rand(2, 3, 9, 13, generator=generator).to(device, dtypes[1])+ compute_dtype = torch.promote_types(*dtypes)+ expected = kornia.metrics.psnr(image.to(compute_dtype), target.to(compute_dtype), 1.0)+ for actual in (kornia.metrics.psnr(image, target, 1.0), kornia.metrics.psnr(target, image, 1.0)):+ assert actual.dtype == compute_dtype+ self.assert_close(actual, expected, rtol=0, atol=0)+ image.requires_grad_()+ target.requires_grad_()+ kornia.metrics.psnr(image, target, 1.0).backward()+ assert image.grad.dtype == dtypes[0]+ assert target.grad.dtype == dtypes[1]+def test_exception_shape_mismatch(self, device, dtype):a = torch.ones(4, device=device, dtype=dtype)b = torch.ones(8, device=device, dtype=dtype)