Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Keep half precision PSNR finite for representable results (#5780)

AhmetHakanBezir8994f12bde17
diff --git a/changelog.d/5780.fixed.md b/changelog.d/5780.fixed.md
new file mode 100644
index 000000000..884cc6e52
--- /dev/null
+++ b/changelog.d/5780.fixed.md
@@ -0,0 +1 @@
+`psnr`, `psnr_loss` and `PSNRLoss` compute float16 and bfloat16 images in float32, including a tensor data range. The result uses the promoted image dtype, also promoted with a tensor `max_val` dtype; a float32 tensor data range gives a float32 result for half-precision images. In float16, `max_val**2 / mse` overflowed, so every PSNR above 48.16 dB (8-bit quantization of a float image alone gives about 59 dB) came back as `inf` and `psnr_loss` gradients were NaN.
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index 8bb1dfe69..8a6793695 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -21,9 +21,10 @@ import torch
from torch import nn
from kornia import metrics
+from kornia.metrics.psnr import _PSNRMaxVal
-def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
+def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: _PSNRMaxVal) -> torch.Tensor:
r"""Compute the PSNR loss.
The loss is computed as follows:
@@ -39,10 +40,10 @@ def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torc
Args:
image: the input image with shape :math:`(*)`.
target : the labels image with shape :math:`(*)`.
- max_val: the data range of the images, :math:`\text{MAX}_I`.
+ max_val: the data range of the images, :math:`\text{MAX}_I`, as a float, integer or tensor.
Return:
- the computed loss as a scalar.
+ the computed loss as a scalar for a scalar range, or with the shape of a tensor range.
Examples:
>>> ones = torch.ones(1)
@@ -67,12 +68,12 @@ class PSNRLoss(nn.Module):
inputs give ``-inf``.
Args:
- max_val: the data range of the images, :math:`\text{MAX}_I`.
+ max_val: the data range of the images, :math:`\text{MAX}_I`, as a float, integer or tensor.
Shape:
- Image: arbitrary dimensional tensor :math:`(*)`.
- Target: arbitrary dimensional tensor :math:`(*)` same shape as image.
- - Output: a scalar.
+ - Output: a scalar for a scalar range, or with the shape of a tensor range.
Examples:
>>> ones = torch.ones(1)
@@ -82,9 +83,9 @@ class PSNRLoss(nn.Module):
"""
- def __init__(self, max_val: float) -> None:
+ def __init__(self, max_val: _PSNRMaxVal) -> None:
super().__init__()
- self.max_val: float = max_val
+ self.max_val: _PSNRMaxVal = max_val
def forward(self, image: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Compute the negative PSNR loss between two tensors.
@@ -94,7 +95,7 @@ class PSNRLoss(nn.Module):
target: Reference tensor with the same shape as ``image``.
Returns:
- Scalar tensor containing the PSNR-based loss computed with
+ Tensor containing the PSNR-based loss computed with
``self.max_val``. Lower values correspond to higher peak signal to
noise ratio.
"""
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index 93ec659f3..2e3c8b9f3 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -18,8 +18,11 @@
import torch
from torch.nn.functional import mse_loss as mse
+# Unlike Python's numeric tower, TorchScript unions need int explicitly to keep integer ranges accepted.
+_PSNRMaxVal = float | int | torch.Tensor
-def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
+
+def psnr(image: torch.Tensor, target: torch.Tensor, max_val: _PSNRMaxVal) -> torch.Tensor:
r"""Create a function that calculates the PSNR between 2 images.
PSNR is the Peak Signal to Noise Ratio. For one m x n image, the PSNR is:
@@ -38,7 +41,7 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
(e.g for floating point images :math:`\text{MAX}_I=1`).
Convention:
- - One MSE is pooled over every element, batch and channels included, and the result is a single value: for a
+ - One MSE is pooled over every element, batch and channels included. A scalar range gives one PSNR: for a
batch it is the PSNR of the pooled MSE, not the mean of per-image PSNRs, so compute per-image values one
image at a time. :ref:`Losses and metrics <losses-metrics-conventions>` maps both onto scikit-image and
torchmetrics.
@@ -47,14 +50,17 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
- ``image`` and ``target`` must have the same shape, without broadcasting; the value is symmetric in them.
Identical inputs give an MSE of 0 and ``inf``, while a batch with one identical pair stays finite.
- Integer and bool images are converted to float32 before computing the MSE; pixel values are not rescaled.
+ - Float16 and bfloat16 inputs are evaluated in float32; the result retains their promoted input dtype,
+ also promoted with ``max_val.dtype`` when the data range is a tensor. A float32 tensor data range therefore
+ gives a float32 result for half-precision images.
Args:
image: the input image with arbitrary shape :math:`(*)`.
target: the labels image with arbitrary shape :math:`(*)`.
- max_val: the data range of the images, :math:`\text{MAX}_I`.
+ max_val: the data range of the images, :math:`\text{MAX}_I`, as a float, integer or tensor.
Return:
- the PSNR as a scalar.
+ the PSNR as a scalar for a scalar range, or with the shape of a tensor range.
.. note::
Integer and bool images are converted to float32, as in :func:`~kornia.metrics.ssim`, and the two images are
@@ -86,10 +92,26 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
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)
+ compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ image, target = image.to(compute_dtype), target.to(compute_dtype)
+ result_dtype = dtype
+ if dtype in (torch.float16, torch.bfloat16) and isinstance(max_val, torch.Tensor):
+ result_dtype = torch.promote_types(dtype, max_val.dtype)
+ # Keep the tensor data range's square and division out of half precision too, without narrowing float64.
+ max_val = max_val.to(torch.promote_types(compute_dtype, max_val.dtype))
# The legacy (TorchScript) ONNX exporter writes ``log10`` as a division by a ``(1,)`` constant, which turns a 0-d
# result into a one-element vector. Reshaping to the shape of the ratio keeps the eager shape there (``()`` for a
# scalar ``max_val``, the shape of a tensor one) and is a no-op view eagerly.
- ratio = max_val**2 / mse(image, target, reduction="mean")
- return (10.0 * torch.log10(ratio)).reshape(ratio.shape)
+ mse_value = mse(image, target, reduction="mean")
+ # TorchScript needs the union refined before selecting a pow overload.
+ if isinstance(max_val, torch.Tensor):
+ ratio = torch.pow(max_val, 2) / mse_value
+ elif isinstance(max_val, int):
+ ratio = max_val**2 / mse_value
+ else:
+ ratio = max_val**2 / mse_value
+ result = 10.0 * torch.log10(ratio)
+ if dtype in (torch.float16, torch.bfloat16):
+ result = result.to(result_dtype)
+ return result.reshape(ratio.shape)
diff --git a/tests/losses/test_psnr.py b/tests/losses/test_psnr.py
index d55f15895..275b09198 100644
--- a/tests/losses/test_psnr.py
+++ b/tests/losses/test_psnr.py
@@ -77,6 +77,35 @@ class TestPSNRLoss(BaseTester):
self.assert_close(op(*args), op_module(pred, target))
+ @pytest.mark.parametrize("scalar_range", [True, False])
+ def test_scripted_tensor_range(self, device, scalar_range):
+ image = torch.tensor([32.0], device=device)
+ target = torch.zeros_like(image)
+ values = 512.0 if scalar_range else [512.0, 1024.0]
+ max_val = torch.tensor(values, device=device, requires_grad=True)
+ expected = 20 * torch.log10(max_val.detach() / 32)
+ metric = torch.jit.script(kornia.metrics.psnr)
+ loss = torch.jit.script(kornia.losses.psnr_loss)
+ module = torch.jit.script(kornia.losses.PSNRLoss(max_val))
+ actuals = [(metric(image, target, max_val), 1), (loss(image, target, max_val), -1), (module(image, target), -1)]
+ for actual, sign in actuals:
+ assert actual.shape == max_val.shape
+ self.assert_close(actual, sign * expected)
+ (range_grad,) = torch.autograd.grad(actual.sum(), max_val)
+ self.assert_close(range_grad, sign * 20 / (math.log(10) * max_val.detach()))
+
+ @pytest.mark.parametrize("max_val", [512, 512.0])
+ def test_scripted_numeric_range(self, device, max_val):
+ image = torch.tensor([32.0], device=device)
+ target = torch.zeros_like(image)
+ expected = kornia.metrics.psnr(image, target, max_val)
+ metric = torch.jit.script(kornia.metrics.psnr)
+ loss = torch.jit.script(kornia.losses.psnr_loss)
+ module = torch.jit.script(kornia.losses.PSNRLoss(max_val))
+ self.assert_close(metric(image, target, max_val), expected)
+ self.assert_close(loss(image, target, max_val), -expected)
+ self.assert_close(module(image, target), -expected)
+
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)
diff --git a/tests/metrics/test_psnr_metric.py b/tests/metrics/test_psnr_metric.py
index 2bceeec7e..da40da159 100644
--- a/tests/metrics/test_psnr_metric.py
+++ b/tests/metrics/test_psnr_metric.py
@@ -177,3 +177,65 @@ class TestConventionsPsnr(BaseTester):
assert actual.dtype == torch.float32
self.assert_close(actual, expected, rtol=0.0, atol=0.0)
assert torch.isfinite(kornia.metrics.psnr(a.to(dtype), b.to(dtype), 255.0))
+
+
+class TestPSNRHalfPrecision(BaseTester):
+ @pytest.mark.parametrize("image_dtype", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("range_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+ @pytest.mark.parametrize("scalar_range", [True, False])
+ def test_tensor_range_value_dtype_and_gradients(self, device, image_dtype, range_dtype, scalar_range):
+ """Square tensor data ranges in the compute dtype without losing their output dtype or gradients."""
+ if device.type == "mps" and range_dtype == torch.float64:
+ pytest.skip("MPS has no float64")
+ image = torch.tensor([32.0], device=device, dtype=image_dtype, requires_grad=True)
+ values = 512.0 if scalar_range else [512.0, 1024.0]
+ max_val = torch.tensor(values, device=device, dtype=range_dtype, requires_grad=True)
+ expected_dtype = torch.promote_types(image_dtype, range_dtype)
+ reference_range = max_val.detach().cpu().double()
+ reference = (20 * torch.log10(reference_range / 32)).to(device=device, dtype=expected_dtype)
+
+ actual = kornia.metrics.psnr(image, torch.zeros_like(image), max_val)
+ assert actual.shape == max_val.shape
+ assert actual.dtype == expected_dtype
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, reference)
+ actual.sum().backward()
+ expected_range_grad = (20 / (math.log(10) * reference_range)).to(device=device, dtype=range_dtype)
+ self.assert_close(max_val.grad, expected_range_grad)
+ self.assert_close(image.grad, image.new_tensor([-20 * max_val.numel() / (math.log(10) * 32)]))
+
+ @pytest.mark.parametrize("residual,max_val", [(1e-4, 1.0), (1.0 / 512, 1.0), (300.0, 512.0)])
+ def test_representable_psnr(self, device, dtype, residual, max_val):
+ """Finite half-precision PSNR and its loss wrappers match the scalar reference."""
+ image = torch.tensor([residual], device=device, dtype=dtype)
+ target = torch.zeros_like(image)
+ delta = image.detach().cpu().double().item()
+ expected = image.new_tensor(20 * math.log10(max_val / abs(delta)))
+ actual = kornia.metrics.psnr(image, target, max_val)
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual)
+ self.assert_close(actual, expected)
+ self.assert_close(kornia.losses.psnr_loss(image, target, max_val), -expected)
+ self.assert_close(kornia.losses.PSNRLoss(max_val)(image, target), -expected)
+
+ @pytest.mark.parametrize("residual,max_val", [(1.0 / 512, 1.0), (300.0, 512.0)])
+ def test_representable_gradient(self, device, dtype, residual, max_val):
+ """Image and target gradients match the analytic derivative for represented residuals."""
+ image = torch.tensor([residual], device=device, dtype=dtype, requires_grad=True)
+ target = torch.zeros_like(image, requires_grad=True)
+ result = kornia.metrics.psnr(image, target, max_val)
+ grad_image, grad_target = torch.autograd.grad(result, (image, target))
+ expected = image.new_tensor([-20 / (math.log(10) * image.detach().cpu().double().item())])
+ assert torch.isfinite(grad_image).all()
+ assert torch.isfinite(grad_target).all()
+ self.assert_close(grad_image, expected)
+ self.assert_close(grad_target, -expected)
+
+ def test_tensor_max_val_keeps_its_result_dtype(self, device, dtype):
+ """A float32 tensor range retains its contribution to the result dtype."""
+ # A float32 tensor max_val gave a float32 PSNR for every image dtype before half precision moved to float32.
+ image = torch.tensor([1.0 / 512], device=device, dtype=dtype)
+ max_val = torch.tensor([1.0, 255.0], device=device)
+ actual = kornia.metrics.psnr(image, torch.zeros_like(image), max_val)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, max_val.new_tensor([20 * math.log10(512), 20 * math.log10(255 * 512)]))