Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): check exact input/target shape in MS_SSIMLoss (#6158)

Charan Rathoreb8092dbb73e5
diff --git a/changelog.d/6158.fixed.md b/changelog.d/6158.fixed.md
new file mode 100644
index 000000000..f9ff89070
--- /dev/null
+++ b/changelog.d/6158.fixed.md
@@ -0,0 +1 @@
+`MS_SSIMLoss` now requires `img1` and `img2` to be 4-D `(B, C, H, W)` tensors with the same channels, height and width and equal batch sizes, or a batch size of 1 that is compared with every image of the other batch as before, and raises `ValueError` otherwise (a `ShapeError` for a shape mismatch), also with Kornia checks disabled (#6157). It used to compare only the number of dimensions: a height or width of 1 was broadcast and returned a wrong loss, and so did some 3-D `(C, H, W)` pairs. Inputs of different ranks already raised `ValueError`; every other mismatch or input that is not 4-D ended in a torch `RuntimeError` or `IndexError` and now raises `ValueError`.
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index 5fe57d0b7..2546fea7e 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -23,6 +23,8 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core.exceptions import ShapeError
+
# Based on:
# https://github.com/psyrocloud/MS-SSIM_L1_LOSS
@@ -64,6 +66,8 @@ class MS_SSIMLoss(nn.Module):
- The defaults follow [3]: ``alpha=0.025``, as in [2], and ``compensation=200``, which neither [1] nor [2]
applies; [1] sets :math:`\alpha = 0.84`. The default ``reduction='mean'`` averages the :math:`(B, H, W)`
map, whose channels are already averaged.
+ - The two images must have the same :math:`(C, H, W)` shape. Their batch sizes must match, or one of them
+ must be 1, and that image is then compared with every image of the other batch.
Reference:
[1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11
@@ -207,8 +211,20 @@ class MS_SSIMLoss(nn.Module):
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)}.")
+ if not len(img1.shape) == 4:
+ raise ValueError(f"Invalid img1 shape, we expect BxCxHxW. Got: {img1.shape}")
+
+ if not len(img2.shape) == 4:
+ raise ValueError(f"Invalid img2 shape, we expect BxCxHxW. Got: {img2.shape}")
+
+ # A batch of one broadcasts over the other image's batch and gives the loss against the repeated image; a
+ # height, width or channel count of one would broadcast to a wrong loss.
+ same_batch = img1.shape[0] == img2.shape[0] or img1.shape[0] == 1 or img2.shape[0] == 1
+ if img1.shape[1:] != img2.shape[1:] or not same_batch:
+ raise ShapeError(
+ "Input and target must have the same shape, except for a batch size of 1. "
+ f"Got: {img1.shape} and {img2.shape}."
+ )
mask_dtype = self._g_masks.dtype
if img1.is_complex() or img2.is_complex():
diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.py
index 3ba6aa86d..ab3c51241 100644
--- a/tests/losses/test_ssim.py
+++ b/tests/losses/test_ssim.py
@@ -15,10 +15,13 @@
# limitations under the License.
#
+import re
+
import pytest
import torch
import kornia
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.core.exceptions import BaseError
from testing.base import BaseTester
@@ -80,6 +83,49 @@ _MS_SSIM_TOL = {torch.float16: 1e-2, torch.bfloat16: 5e-2}
class TestMS_SSIMLoss(BaseTester):
+ @pytest.mark.parametrize("shape", [(3, 16, 16), (1, 1, 3, 16, 16), (16, 16)])
+ def test_non_4d_inputs_raise(self, shape, device, dtype):
+ # MS-SSIM is defined for BxCxHxW only; equal-shaped inputs of another rank must not
+ # fall through to conv2d (a 3-D pair takes its unbatched path) and its confusing errors.
+ img = torch.rand(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="BxCxHxW"):
+ kornia.losses.MS_SSIMLoss()(img, img)
+
+ @pytest.mark.parametrize("target_shape", [(3, 3, 16, 16), (2, 1, 16, 16), (2, 3, 1, 16), (2, 3, 16, 1)])
+ def test_shape_mismatch_raises(self, target_shape, device, dtype):
+ # GH#6157 a height or width of 1 used to broadcast silently to a wrong loss; mismatched shapes must raise.
+ img1 = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ img2 = torch.rand(target_shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match=re.escape(f"batch size of 1. Got: {img1.shape} and {img2.shape}.")):
+ kornia.losses.MS_SSIMLoss()(img1, img2)
+
+ @pytest.mark.parametrize("reduction", ["mean", "sum", "none"])
+ def test_batch_of_one_broadcasts(self, reduction, device, dtype):
+ # GH#6157 a batch of one is compared with every image of the other batch, in either argument.
+ img = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ single = torch.rand(1, 3, 16, 16, device=device, dtype=dtype)
+ criterion = kornia.losses.MS_SSIMLoss(reduction=reduction).to(device, dtype)
+ repeated = single.expand_as(img)
+ self.assert_close(criterion(img, single), criterion(img, repeated), rtol=0, atol=0)
+ self.assert_close(criterion(single, img), criterion(repeated, img), rtol=0, atol=0)
+
+ def test_shape_mismatch_raises_when_checks_disabled(self, device, dtype):
+ # GH#6157 the shape guard must hold even with Kornia checks disabled
+ # globally; the loss must never broadcast mismatched inputs silently.
+ img1 = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ img2 = torch.rand(3, 3, 16, 16, device=device, dtype=dtype)
+ were_checks_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(
+ ValueError,
+ match=r"batch size of 1\. Got: torch\.Size\(\[2, 3, 16, 16\]\) and torch\.Size\(\[3, 3, 16, 16\]\)",
+ ):
+ kornia.losses.MS_SSIMLoss()(img1, img2)
+ finally:
+ if were_checks_enabled:
+ enable_checks()
+
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
def test_high_pixel_values_use_float32_moments(self, device, dtype):
# The float64 reference is computed on the CPU, so the device leg needs no float64 support.
@@ -165,9 +211,13 @@ class TestMS_SSIMLoss(BaseTester):
criterion(torch.rand(1), 2)
assert "Output type is not a torch.Tensor. Got" in str(errinfo)
- with pytest.raises(ValueError) as errinfo:
+ with pytest.raises(ValueError, match="BxCxHxW"):
criterion(torch.rand(1), torch.rand(1, 2))
- assert "Input shapes should be same. Got" in str(errinfo)
+
+ with pytest.raises(
+ ValueError, match=r"batch size of 1\. Got: torch\.Size\(\[3, 1, 8, 8\]\) and torch\.Size\(\[2, 1, 8, 8\]\)"
+ ):
+ criterion(torch.rand(3, 1, 8, 8), torch.rand(2, 1, 8, 8))
@pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
@pytest.mark.parametrize("batch_shape", [(2, 1, 2, 3), (1, 3, 10, 16)])