Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): compute integer images in the mask dtype in MS_SSIMLoss (#5353)

εŒΊζ’“ηc68bfb6e2e85
diff --git a/changelog.d/5353.fixed.md b/changelog.d/5353.fixed.md
new file mode 100644
index 000000000..af02afa33
--- /dev/null
+++ b/changelog.d/5353.fixed.md
@@ -0,0 +1,4 @@
+`MS_SSIMLoss` now computes integer and bool images in the dtype of its Gaussian masks, float32 for a default module
+and float64 for a module moved with `.double()`, and returns the loss in that dtype (#5351). Previously such an image
+reached `F.conv2d` with a dtype that did not match the masks and raised torch's error, `expected scalar type Byte but
+found Float` for uint8. Floating images are unchanged and pixel values are not rescaled.
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index 7fa7ad37f..c41c3cebe 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -70,6 +70,12 @@ class MS_SSIMLoss(nn.Module):
- Input2: :math:`(N, C, H, W)`.
- Output: :math:`(N, H, W)` or scalar if reduction is set to ``'mean'`` or ``'sum'``.
+ Note:
+ Integer and bool images are converted to the dtype of the Gaussian masks before filtering, float32 unless the
+ module was moved to another floating dtype, so the loss is returned in that dtype. Pixel values are not
+ rescaled: pass ``data_range=255.0`` for 8-bit images, which gives the loss of the images divided by 255 at the
+ default ``data_range=1.0``.
+
Examples:
>>> input1 = torch.rand(1, 3, 5, 5)
>>> input2 = torch.rand(1, 3, 5, 5)
@@ -189,6 +195,12 @@ class MS_SSIMLoss(nn.Module):
# repeated channel-major: output ``c * S + s`` is channel ``c`` filtered at scale ``s``.
g_masks: torch.Tensor = torch.jit.annotate(torch.Tensor, self._g_masks).repeat(CH, 1, 1, 1)
+ # The masks carry fractional weights, so integer and bool images are filtered in the mask dtype.
+ if not img1.is_floating_point() and not img1.is_complex():
+ img1 = img1.to(g_masks.dtype)
+ if not img2.is_floating_point() and not img2.is_complex():
+ img2 = img2.to(g_masks.dtype)
+
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
diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.py
index 00bb44ec0..9f55f6157 100644
--- a/tests/losses/test_ssim.py
+++ b/tests/losses/test_ssim.py
@@ -268,6 +268,55 @@ class TestMS_SSIMLoss(BaseTester):
assert out.shape == (1, 16, 20)
self.assert_close(out, loss(img1.flip(-1), img2.flip(-1)).flip(-1))
+ @pytest.mark.parametrize(
+ "input_dtype, data_range", [(torch.uint8, 255.0), (torch.int16, 255.0), (torch.int64, 255.0), (torch.bool, 1.0)]
+ )
+ def test_integer_images_are_computed_in_the_mask_dtype_5351(self, device, dtype, input_dtype, data_range):
+ # An integer or bool image is converted to the dtype of the Gaussian masks before filtering, so it gives the
+ # loss of the same values held in that dtype, for two integer images and for one integer and one float image.
+ g = torch.Generator().manual_seed(0)
+ values1 = torch.randint(0, 256, (1, 3, 12, 16), generator=g)
+ values2 = (values1 + torch.randn(1, 3, 12, 16, generator=g) * 40).round().clamp(0, 255).long()
+ if input_dtype is torch.bool:
+ values1, values2 = values1 > 127, values2 > 127
+ img1 = values1.to(device, input_dtype)
+ img2 = values2.to(device, input_dtype)
+ criterion = kornia.losses.MS_SSIMLoss(data_range=data_range).to(device, dtype)
+
+ expected = criterion(img1.to(dtype), img2.to(dtype))
+ assert expected.dtype == dtype
+ assert expected.item() > 0
+
+ loss = criterion(img1, img2)
+ assert loss.dtype == dtype
+ self.assert_close(loss, expected)
+ self.assert_close(criterion(img1, img2.to(dtype)), expected)
+ self.assert_close(criterion(img1.to(dtype), img2), expected)
+
+ def test_integer_images_follow_the_module_dtype_5351(self, device, dtype):
+ # The masks follow the module dtype, so a float64 module computes uint8 images in float64.
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ img1 = torch.randint(0, 256, (1, 1, 12, 16), device=device, dtype=torch.uint8)
+ img2 = torch.randint(0, 256, (1, 1, 12, 16), device=device, dtype=torch.uint8)
+ criterion = kornia.losses.MS_SSIMLoss(data_range=255.0).to(device, torch.float64)
+
+ loss = criterion(img1, img2)
+ assert loss.dtype == torch.float64
+ self.assert_close(loss, criterion(img1.double(), img2.double()))
+
+ def test_complex_images_are_not_cast_5351(self, device, dtype):
+ # Only integer and bool images are converted: casting a complex image to the real mask dtype would drop its
+ # imaginary part, so it still raises.
+ g = torch.Generator().manual_seed(0)
+ img1 = torch.rand(1, 1, 12, 16, generator=g).to(device, dtype)
+ img2 = torch.rand(1, 1, 12, 16, generator=g).to(device, dtype)
+ criterion = kornia.losses.MS_SSIMLoss().to(device, dtype)
+ with pytest.raises(RuntimeError):
+ criterion(img1.to(torch.complex64), img2)
+ with pytest.raises(RuntimeError):
+ criterion(img1, img2.to(torch.complex64))
+
def test_gradcheck(self, device, dtype):
# input data
dtype = torch.float64