Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add cuda tests for ssim loss and refactor

edgarribac0beda544934
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 4a19d2726..8df44c3c9 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -4,7 +4,12 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.filters import get_gaussian_kernel2d
+from kornia.filters import get_gaussian_kernel2d, filter2D
+
+
+def _compute_zero_padding(kernel_size: int) -> int:
+ """Computes zero padding."""
+ return (kernel_size - 1) // 2
class SSIM(nn.Module):
@@ -58,7 +63,7 @@ class SSIM(nn.Module):
def __init__(
self,
window_size: int,
- reduction: str = 'none',
+ reduction: str = "none",
max_val: float = 1.0) -> None:
super(SSIM, self).__init__()
self.window_size: int = window_size
@@ -67,76 +72,74 @@ class SSIM(nn.Module):
self.window: torch.Tensor = get_gaussian_kernel2d(
(window_size, window_size), (1.5, 1.5))
- self.padding: int = self.compute_zero_padding(window_size)
+ self.window = self.window.requires_grad_(False) # need to disable gradients
+
+ self.padding: int = _compute_zero_padding(window_size)
self.C1: float = (0.01 * self.max_val) ** 2
self.C2: float = (0.03 * self.max_val) ** 2
- @staticmethod
- def compute_zero_padding(kernel_size: int) -> int:
- """Computes zero padding."""
- return (kernel_size - 1) // 2
-
- def filter2D(
- self,
- input: torch.Tensor,
- kernel: torch.Tensor,
- channel: int) -> torch.Tensor:
- return F.conv2d(input, kernel, padding=self.padding, groups=channel)
-
def forward( # type: ignore
self,
img1: torch.Tensor,
img2: torch.Tensor) -> torch.Tensor:
+
if not torch.is_tensor(img1):
raise TypeError("Input img1 type is not a torch.Tensor. Got {}"
.format(type(img1)))
+
if not torch.is_tensor(img2):
raise TypeError("Input img2 type is not a torch.Tensor. Got {}"
.format(type(img2)))
+
if not len(img1.shape) == 4:
raise ValueError("Invalid img1 shape, we expect BxCxHxW. Got: {}"
.format(img1.shape))
+
if not len(img2.shape) == 4:
raise ValueError("Invalid img2 shape, we expect BxCxHxW. Got: {}"
.format(img2.shape))
+
if not img1.shape == img2.shape:
raise ValueError("img1 and img2 shapes must be the same. Got: {}"
.format(img1.shape, img2.shape))
+
if not img1.device == img2.device:
raise ValueError("img1 and img2 must be in the same device. Got: {}"
.format(img1.device, img2.device))
+
if not img1.dtype == img2.dtype:
raise ValueError("img1 and img2 must be in the same dtype. Got: {}"
.format(img1.dtype, img2.dtype))
+
# prepare kernel
b, c, h, w = img1.shape
tmp_kernel: torch.Tensor = self.window.to(img1.device).to(img1.dtype)
- kernel: torch.Tensor = tmp_kernel.repeat(c, 1, 1, 1)
+ tmp_kernel = torch.unsqueeze(tmp_kernel, dim=0)
# compute local mean per channel
- mu1: torch.Tensor = self.filter2D(img1, kernel, c)
- mu2: torch.Tensor = self.filter2D(img2, kernel, c)
+ mu1: torch.Tensor = filter2D(img1, tmp_kernel)
+ mu2: torch.Tensor = filter2D(img2, tmp_kernel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
# compute local sigma per channel
- sigma1_sq = self.filter2D(img1 * img1, kernel, c) - mu1_sq
- sigma2_sq = self.filter2D(img2 * img2, kernel, c) - mu2_sq
- sigma12 = self.filter2D(img1 * img2, kernel, c) - mu1_mu2
+ sigma1_sq = filter2D(img1 * img1, tmp_kernel) - mu1_sq
+ sigma2_sq = filter2D(img2 * img2, tmp_kernel) - mu2_sq
+ sigma12 = filter2D(img1 * img2, tmp_kernel) - mu1_mu2
- ssim_map = ((2 * mu1_mu2 + self.C1) * (2 * sigma12 + self.C2)) / \
+ ssim_map = ((2. * mu1_mu2 + self.C1) * (2. * sigma12 + self.C2)) / \
((mu1_sq + mu2_sq + self.C1) * (sigma1_sq + sigma2_sq + self.C2))
- loss = torch.clamp(torch.tensor(1.) - ssim_map, min=0, max=1) / 2.
+ loss = torch.clamp(-ssim_map + 1., min=0, max=1) / 2.
- if self.reduction == 'mean':
+ if self.reduction == "mean":
loss = torch.mean(loss)
- elif self.reduction == 'sum':
+ elif self.reduction == "sum":
loss = torch.sum(loss)
- elif self.reduction == 'none':
+ elif self.reduction == "none":
pass
return loss
@@ -150,7 +153,7 @@ def ssim(
img1: torch.Tensor,
img2: torch.Tensor,
window_size: int,
- reduction: str = 'none',
+ reduction: str = "none",
max_val: float = 1.0) -> torch.Tensor:
r"""Function that measures the Structural Similarity (SSIM) index between
each element in the input `x` and target `y`.
diff --git a/test/test_losses.py b/test/test_losses.py
index f03e1edd6..dda6b4db5 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -172,35 +172,39 @@ class TestDepthSmoothnessLoss:
)
[email protected]("window_size", [5, 11])
[email protected]("reduction_type", ["none", "mean", "sum"])
[email protected]("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
-def test_ssim(batch_shape, window_size, reduction_type):
- # input data
- img1 = torch.rand(batch_shape)
- img2 = torch.rand(batch_shape)
-
- ssim = kornia.losses.SSIM(window_size, reduction_type)
- ssim_loss_val = ssim(img1, img2)
-
- if reduction_type == "none":
- assert ssim_loss_val.shape == batch_shape
- else:
- assert ssim_loss_val.dim() == 0
-
- assert pytest.approx(ssim(img1, img1).sum().item(), 0.0)
- assert pytest.approx(ssim(img2, img2).sum().item(), 0.0)
-
- # functional
- assert_allclose(
- ssim_loss_val,
- kornia.losses.ssim(img1, img2, window_size, reduction_type),
- )
-
- # evaluate function gradient
- img1 = utils.tensor_to_gradcheck_var(img1) # to var
- img2 = utils.tensor_to_gradcheck_var(img2, requires_grad=False) # to var
- assert gradcheck(ssim, (img1, img2), raise_exception=True)
+class TestSSIMLoss:
+
+ def test_ssim_equal_none(self, device):
+ # input data
+ img1 = torch.rand(1, 1, 10, 16).to(device)
+ img2 = torch.rand(1, 1, 10, 16).to(device)
+
+ ssim1 = kornia.ssim(img1, img1, window_size=5, reduction="none")
+ ssim2 = kornia.ssim(img2, img2, window_size=5, reduction="none")
+
+ assert_allclose(ssim1, torch.zeros_like(img1))
+ assert_allclose(ssim2, torch.zeros_like(img2))
+
+ @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, batch_shape, window_size, reduction_type):
+ # input data
+ img = torch.rand(batch_shape).to(device)
+
+ ssim = kornia.losses.SSIM(window_size, reduction_type)
+ assert_allclose(ssim(img, img).item(), 0.0)
+
+ def test_gradcheck(self, device):
+ # input data
+ window_size = 5
+ img1 = torch.rand(1, 1, 10, 16).to(device)
+ img2 = torch.rand(1, 1, 10, 16).to(device)
+
+ # evaluate function gradient
+ img1 = utils.tensor_to_gradcheck_var(img1) # to var
+ img2 = utils.tensor_to_gradcheck_var(img2, requires_grad=False) # to var
+ assert gradcheck(kornia.ssim, (img1, img2, window_size), raise_exception=True)
class TestDivergenceLoss: