Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Adds `MS-SSIMLoss` reconstruction loss function (#1551)

Hasib Zunairb131fc081718
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index 472ed595a..d18fcd331 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -38,6 +38,7 @@ Module
.. autoclass:: TverskyLoss
.. autoclass:: FocalLoss
.. autoclass:: SSIMLoss
+.. autoclass:: MS_SSIMLoss
.. autoclass:: InverseDepthSmoothnessLoss
.. autoclass:: TotalVariation
.. autoclass:: PSNRLoss
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 6fe6ef28f..6bab3521e 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -3,6 +3,7 @@ from .dice import DiceLoss, dice_loss
from .divergence import js_div_loss_2d, kl_div_loss_2d
from .focal import BinaryFocalLossWithLogits, FocalLoss, binary_focal_loss_with_logits, focal_loss
from .hausdorff import HausdorffERLoss, HausdorffERLoss3D
+from .ms_ssim import MS_SSIMLoss
from .psnr import PSNRLoss, psnr_loss
from .ssim import SSIMLoss, ssim_loss
from .total_variation import TotalVariation, total_variation
@@ -28,5 +29,6 @@ __all__ = [
"total_variation",
"TotalVariation",
"tversky_loss",
- "TverskyLoss"
+ "TverskyLoss",
+ "MS_SSIMLoss",
]
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
new file mode 100644
index 000000000..f41de5cb0
--- /dev/null
+++ b/kornia/losses/ms_ssim.py
@@ -0,0 +1,165 @@
+from typing import List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+# Based on:
+# https://github.com/psyrocloud/MS-SSIM_L1_LOSS
+
+
+class MS_SSIMLoss(nn.Module):
+ r"""Creates a criterion that computes MSSIM + L1 loss.
+
+ According to [1], we compute the MS_SSIM + L1 loss as follows:
+
+ .. math::
+ \text{loss}(x, y) = \alpha \cdot \mathcal{L_{MSSIM}}(x,y)+(1 - \alpha) \cdot G_\alpha \cdot \mathcal{L_1}(x,y)
+
+ Where:
+ - :math:`\alpha` is the weight parameter.
+ - :math:`x` and :math:`y` are the reconstructed and true reference images.
+ - :math:`\mathcal{L_{MSSIM}}` is the MS-SSIM loss.
+ - :math:`G_\alpha` is the sigma values for computing multi-scale SSIM.
+ - :math:`\mathcal{L_1}` is the L1 loss.
+
+ Reference:
+ [1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11
+
+ Args:
+ sigmas: gaussian sigma values.
+ data_range: the range of the images.
+ K: k values.
+ alpha : specifies the alpha value
+ compensation: specifies the scaling coefficient.
+
+ Returns:
+ The computed loss.
+
+ Shape:
+ - Input1: :math:`(N, C, H, W)`.
+ - Input2: :math:`(N, C, H, W)`.
+ - Output: :math:`(N,)` or scalar.
+
+ Examples:
+ >>> input1 = torch.rand(1, 3, 5, 5)
+ >>> input2 = torch.rand(1, 3, 5, 5)
+ >>> criterion = kornia.losses.MS_SSIMLoss()
+ >>> loss = criterion(input1, input2)
+ """
+
+ def __init__(
+ self,
+ sigmas: List[float] = [0.5, 1.0, 2.0, 4.0, 8.0],
+ data_range: float = 1.0,
+ K: Tuple[float, float] = (0.01, 0.03),
+ alpha: float = 0.025,
+ compensation: float = 200.0,
+ ) -> None:
+ super().__init__()
+ self.DR: float = data_range
+ self.C1: float = (K[0] * data_range) ** 2
+ self.C2: float = (K[1] * data_range) ** 2
+ self.pad = int(2 * sigmas[-1])
+ self.alpha: float = alpha
+ self.compensation: float = compensation
+
+ # Set filter size
+ filter_size = int(4 * sigmas[-1] + 1)
+ g_masks = torch.zeros((3 * len(sigmas), 1, filter_size, filter_size))
+
+ # Compute mask at different scales
+ for idx, sigma in enumerate(sigmas):
+ g_masks[3 * idx + 0, 0, :, :] = self._fspecial_gauss_2d(filter_size, sigma)
+ g_masks[3 * idx + 1, 0, :, :] = self._fspecial_gauss_2d(filter_size, sigma)
+ g_masks[3 * idx + 2, 0, :, :] = self._fspecial_gauss_2d(filter_size, sigma)
+
+ self.register_buffer('_g_masks', g_masks)
+
+ def _fspecial_gauss_1d(
+ self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ ) -> torch.Tensor:
+ """Create 1-D gauss kernel.
+
+ Args:
+ size: the size of gauss kernel.
+ sigma: sigma of normal distribution.
+
+ Returns:
+ 1D kernel (size).
+ """
+ coords = torch.arange(size, device=device, dtype=dtype)
+ coords -= size // 2
+ g = torch.exp(-(coords ** 2) / (2 * sigma ** 2))
+ g /= g.sum()
+ return g.reshape(-1)
+
+ def _fspecial_gauss_2d(
+ self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ ) -> torch.Tensor:
+ """Create 2-D gauss kernel.
+
+ Args:
+ size: the size of gauss kernel.
+ sigma: sigma of normal distribution.
+
+ Returns:
+ 2D kernel (size x size).
+ """
+ gaussian_vec = self._fspecial_gauss_1d(size, sigma, device, dtype)
+ return torch.outer(gaussian_vec, gaussian_vec)
+
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
+ """Compute MS_SSIM loss.
+
+ Args:
+ img1: the predicted image with shape :math:`(B, C, H, W)`.
+ img2: the target image with a shape of :math:`(B, C, H, W)`.
+
+ Returns:
+ Estimated MS-SSIM_L1 loss.
+ """
+ if not isinstance(img1, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(img1)}")
+
+ if not isinstance(img2, torch.Tensor):
+ raise TypeError(f"Output type is not a torch.Tensor. Got {type(img2)}")
+
+ if not len(img1.shape) == len(img2.shape):
+ raise ValueError(f"Input shapes should be same. Got {type(img1)} and {type(img2)}.")
+
+ g_masks: torch.Tensor = torch.jit.annotate(torch.Tensor, self._g_masks)
+
+ CH: int = img1.shape[-3]
+ mux = F.conv2d(img1, g_masks, groups=CH, padding=self.pad)
+ muy = F.conv2d(img2, g_masks, groups=CH, padding=self.pad)
+ mux2 = mux * mux
+ muy2 = muy * muy
+ muxy = mux * muy
+
+ sigmax2 = F.conv2d(img1 * img1, g_masks, groups=CH, padding=self.pad) - mux2
+ sigmay2 = F.conv2d(img2 * img2, g_masks, groups=CH, padding=self.pad) - muy2
+ sigmaxy = F.conv2d(img1 * img2, g_masks, groups=CH, padding=self.pad) - muxy
+
+ lc = (2 * muxy + self.C1) / (mux2 + muy2 + self.C1)
+ cs = (2 * sigmaxy + self.C2) / (sigmax2 + sigmay2 + self.C2)
+ lM = lc[:, -1, :, :] * lc[:, -2, :, :] * lc[:, -3, :, :]
+ PIcs = cs.prod(dim=1)
+
+ # Compute MS-SSIM loss
+ loss_ms_ssim = 1 - lM * PIcs
+
+ # TODO: pass pointer to function e.g. to make more custom with mse, cosine, etc.
+ # Compute L1 loss
+ loss_l1 = F.l1_loss(img1, img2, reduction='none')
+
+ # Compute average l1 loss in 3 channels
+ gaussian_l1 = F.conv2d(loss_l1, g_masks[-CH:], groups=CH, padding=self.pad).mean(
+ 1
+ )
+
+ # Compute MS-SSIM + L1 loss
+ loss = self.alpha * loss_ms_ssim + (1 - self.alpha) * gaussian_l1 / self.DR
+ loss = self.compensation * loss
+
+ return loss.mean()
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index 28e9c9788..0f6093390 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -298,70 +298,6 @@ class TestDepthSmoothnessLoss:
assert gradcheck(kornia.losses.inverse_depth_smoothness_loss, (depth, image), raise_exception=True)
-class TestSSIMLoss:
- def test_ssim_equal_none(self, device, dtype):
- # input data
- img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
- img2 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
-
- ssim1 = kornia.losses.ssim_loss(img1, img1, window_size=5, reduction="none")
- ssim2 = kornia.losses.ssim_loss(img2, img2, window_size=5, reduction="none")
-
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)
- assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)
-
- @pytest.mark.parametrize("window_size", [5, 11])
- @pytest.mark.parametrize("reduction_type", ["mean", "sum"])
- @pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
- def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):
- if device.type == 'xla':
- pytest.skip("test highly unstable with tpu")
-
- # input data
- img = torch.rand(batch_shape, device=device, dtype=dtype)
-
- loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
-
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
-
- def test_jit(self, device, dtype):
- img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
-
- args = (img1, img2, 5, 1.0, 1e-6, 'mean')
-
- op = kornia.losses.ssim_loss
- op_script = torch.jit.script(op)
-
- assert_close(op(*args), op_script(*args))
-
- def test_module(self, device, dtype):
- img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
-
- args = (img1, img2, 5, 1.0, 1e-12, 'mean')
-
- op = kornia.losses.ssim_loss
- op_module = kornia.losses.SSIMLoss(*args[2:])
-
- assert_close(op(*args), op_module(*args[:2]))
-
- def test_gradcheck(self, device, dtype):
- # input data
- window_size = 3
- img1 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
- img2 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
-
- # evaluate function gradient
- img1 = utils.tensor_to_gradcheck_var(img1) # to var
- img2 = utils.tensor_to_gradcheck_var(img2) # to var
-
- # TODO: review method since it needs `nondet_tol` in cuda sometimes.
- assert gradcheck(kornia.losses.ssim_loss, (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8)
-
-
class TestDivergenceLoss:
@pytest.mark.parametrize(
'input,target,expected',
diff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.py
new file mode 100644
index 000000000..2e24cf6d7
--- /dev/null
+++ b/test/losses/test_ssim.py
@@ -0,0 +1,120 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+
+import kornia
+import kornia.testing as utils # test utils
+from kornia.testing import assert_close
+
+
+class TestSSIMLoss:
+ def test_ssim_equal_none(self, device, dtype):
+ # input data
+ img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+ img2 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+
+ ssim1 = kornia.losses.ssim_loss(img1, img1, window_size=5, reduction="none")
+ ssim2 = kornia.losses.ssim_loss(img2, img2, window_size=5, reduction="none")
+
+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
+ assert_close(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)
+ assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)
+
+ @pytest.mark.parametrize("window_size", [5, 11])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum"])
+ @pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
+ def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):
+ if device.type == 'xla':
+ pytest.skip("test highly unstable with tpu")
+
+ # input data
+ img = torch.rand(batch_shape, device=device, dtype=dtype)
+
+ loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
+
+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
+ assert_close(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
+
+ def test_jit(self, device, dtype):
+ img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+
+ args = (img1, img2, 5, 1.0, 1e-6, 'mean')
+
+ op = kornia.losses.ssim_loss
+ op_script = torch.jit.script(op)
+
+ assert_close(op(*args), op_script(*args))
+
+ def test_module(self, device, dtype):
+ img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+
+ args = (img1, img2, 5, 1.0, 1e-12, 'mean')
+
+ op = kornia.losses.ssim_loss
+ op_module = kornia.losses.SSIMLoss(*args[2:])
+
+ assert_close(op(*args), op_module(*args[:2]))
+
+ def test_gradcheck(self, device, dtype):
+ # input data
+ window_size = 3
+ img1 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
+ img2 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
+
+ # evaluate function gradient
+ img1 = utils.tensor_to_gradcheck_var(img1) # to var
+ img2 = utils.tensor_to_gradcheck_var(img2) # to var
+
+ # TODO: review method since it needs `nondet_tol` in cuda sometimes.
+ assert gradcheck(kornia.losses.ssim_loss, (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8)
+
+
+class TestMS_SSIMLoss:
+ def test_msssim_equal_none(self, device, dtype):
+ # input data
+ img1 = torch.rand(1, 3, 10, 16, device=device, dtype=dtype)
+ img2 = torch.rand(1, 3, 10, 16, device=device, dtype=dtype)
+
+ msssim = kornia.losses.MS_SSIMLoss().to(device, dtype)
+ msssim1 = msssim(img1, img1)
+ msssim2 = msssim(img2, img2)
+
+ assert_close(msssim1.item(), 0.0)
+ assert_close(msssim2.item(), 0.0)
+
+ # TODO: implement for single channel image
+ @pytest.mark.parametrize("batch_shape", [(2, 1, 2, 3), (1, 3, 10, 16)])
+ def test_msssim(self, device, dtype, batch_shape):
+ img = torch.rand(batch_shape, device=device, dtype=dtype)
+
+ msssiml1 = kornia.losses.MS_SSIMLoss().to(device, dtype)
+ loss = msssiml1(img, img)
+
+ assert_close(loss.item(), 0.0)
+
+ def test_gradcheck(self, device):
+ # input data
+ dtype = torch.float64
+ img1 = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ img2 = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+
+ # evaluate function gradient
+ img1 = utils.tensor_to_gradcheck_var(img1) # to var
+ img2 = utils.tensor_to_gradcheck_var(img2) # to var
+
+ loss = kornia.losses.MS_SSIMLoss().to(device, dtype)
+
+ assert gradcheck(loss, (img1, img2), raise_exception=True, nondet_tol=1e-8)
+
+ def test_jit(self, device, dtype):
+ img1 = torch.rand(1, 3, 10, 10, device=device, dtype=dtype)
+ img2 = torch.rand(1, 3, 10, 10, device=device, dtype=dtype)
+
+ args = (img1, img2)
+
+ op = kornia.losses.MS_SSIMLoss().to(device, dtype)
+ op_script = torch.jit.script(op)
+
+ assert_close(op(*args), op_script(*args))