π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): compute MS-SSIM moments in float32 (#5377)
Karnajeet Gosavi1bfc0a620529
diff --git a/changelog.d/5377.fixed.md b/changelog.d/5377.fixed.mdnew file mode 100644index 000000000..5e741dcf7--- /dev/null+++ b/changelog.d/5377.fixed.md@@ -0,0 +1 @@+`MS_SSIMLoss` now filters float16 and bfloat16 images in float32 with autocast disabled and returns the loss in the input dtype, as `ssim` and `SSIMLoss` do (#5148). A float16 pair with local means above about 181, such as pixel-range data at `data_range=255.0`, used to give a NaN loss, and bfloat16 was 2.5 % low on such images (12.06 instead of 12.37). A float16 or bfloat16 module renormalises its rounded Gaussian masks, which no longer summed to one. Under `torch.autocast` a float32 input used to be filtered in the autocast dtype (12.04 instead of 12.37 under CPU bfloat16 autocast, NaN under float16) and is now filtered in float32. Images whose dtype differs from the module's, which used to raise torch's dtype-mismatch error, are now accepted: integer and bool images count as the mask dtype, and the loss is returned in the promoted dtype of the two images.diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.pyindex c41c3cebe..823418367 100644--- a/kornia/losses/ms_ssim.py+++ b/kornia/losses/ms_ssim.py@@ -71,8 +71,10 @@ class MS_SSIMLoss(nn.Module):- 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+ Integer and bool images count as the dtype of the Gaussian masks: float32, unless the module was moved to+ another floating dtype. The images are filtered in the promoted dtype of the two images and the masks, with+ float16 and bfloat16 raised to float32 and autocast disabled on CPU, CUDA and MPS. The loss is returned in the+ promoted dtype of the two images, so two integer images give a loss in the mask dtype. Pixel values are notrescaled: pass ``data_range=255.0`` for 8-bit images, which gives the loss of the images divided by 255 at thedefault ``data_range=1.0``.@@ -189,17 +191,51 @@ class MS_SSIMLoss(nn.Module):if not len(img1.shape) == len(img2.shape):raise ValueError(f"Input shapes should be same. Got {type(img1)} and {type(img2)}.")+ mask_dtype = self._g_masks.dtype+ if img1.is_complex() or img2.is_complex():+ output_dtype = torch.promote_types(img1.dtype, img2.dtype)+ compute_dtype = output_dtype+ g_masks = self._g_masks+ else:+ # The masks carry fractional weights, so integer and bool images count as the mask dtype.+ dtype1 = img1.dtype if img1.is_floating_point() else mask_dtype+ dtype2 = img2.dtype if img2.is_floating_point() else mask_dtype+ output_dtype = torch.promote_types(dtype1, dtype2)+ # Half-precision moments overflow (local means above about 181 in float16) and cancel, so they are+ # computed in float32.+ compute_dtype = torch.promote_types(output_dtype, mask_dtype)+ if compute_dtype in (torch.float16, torch.bfloat16):+ compute_dtype = torch.float32+ g_masks = self._g_masks.to(compute_dtype)+ if mask_dtype in (torch.float16, torch.bfloat16):+ # Rounded to half precision, the masks no longer sum to one (in bfloat16 only to within 2.4e-3),+ # which shifts every variance by about (1 - sum) * mu^2: renormalise the float32 copy.+ g_masks = g_masks / g_masks.sum(dim=(-2, -1), keepdim=True)++ img1 = img1.to(compute_dtype)+ img2 = img2.to(compute_dtype)+CH: int = img1.shape[-3]- S: int = self.num_scales# A grouped convolution gives each input channel a contiguous block of output channels, so the masks are# 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)+ g_masks = torch.jit.annotate(torch.Tensor, g_masks).repeat(CH, 1, 1, 1)++ if img1.device.type == "cpu":+ with torch.autocast(device_type="cpu", enabled=False):+ loss = self._compute_loss(img1, img2, g_masks)+ elif img1.device.type == "cuda":+ with torch.autocast(device_type="cuda", enabled=False):+ loss = self._compute_loss(img1, img2, g_masks)+ elif img1.device.type == "mps":+ with torch.autocast(device_type="mps", enabled=False):+ loss = self._compute_loss(img1, img2, g_masks)+ else:+ loss = self._compute_loss(img1, img2, g_masks)+ return loss.to(output_dtype)- # 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)+ def _compute_loss(self, img1: torch.Tensor, img2: torch.Tensor, g_masks: torch.Tensor) -> torch.Tensor:+ CH: int = img1.shape[-3]+ S: int = self.num_scalesmux = F.conv2d(img1, g_masks, groups=CH, padding=self.pad)muy = F.conv2d(img2, g_masks, groups=CH, padding=self.pad)diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.pyindex 9f55f6157..5ff2f6e92 100644--- a/tests/losses/test_ssim.py+++ b/tests/losses/test_ssim.py@@ -82,6 +82,68 @@ _MS_SSIM_TOL = {torch.float16: 1e-2, torch.bfloat16: 5e-2}class TestMS_SSIMLoss(BaseTester):+ @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.+ generator = torch.Generator().manual_seed(0)+ img1 = (180 + torch.rand(1, 3, 64, 64, generator=generator) * 75).round()+ img2 = (img1 + torch.randn(1, 3, 64, 64, generator=generator) * 20).clamp(0, 255).round()++ reference = kornia.losses.MS_SSIMLoss(data_range=255.0).double()(img1.double(), img2.double())+ criterion = kornia.losses.MS_SSIMLoss(data_range=255.0).to(device, dtype)+ loss = criterion(img1.to(device, dtype), img2.to(device, dtype))++ assert loss.dtype == dtype+ assert torch.isfinite(loss)+ # Allows one rounding to ``dtype``: half an ulp of 12.4 is below ``eps / 2`` relative. Masks used as rounded+ # to ``dtype`` (in bfloat16 the first sums to 0.9976) gave 12.25 in bfloat16 and 12.383 in float16.+ self.assert_close(loss.float().cpu(), reference.float(), atol=0.0, rtol=torch.finfo(dtype).eps / 2)++ def test_int16_images_are_not_rounded_through_float16(self, device):+ # Values 1 mod 4 in [2048, 4096) round down by one in float16 (ties to even), so a float16 detour doubles the+ # loss between ``img1`` and ``img1 + 1`` (0.0098 instead of 0.0049).+ generator = torch.Generator().manual_seed(0)+ img1 = (2049 + 4 * torch.randint(0, 500, (1, 3, 64, 64), generator=generator)).to(torch.int16)+ img2 = img1 + 1++ criterion = kornia.losses.MS_SSIMLoss(data_range=32767.0).to(device, torch.float16)+ reference = kornia.losses.MS_SSIMLoss(data_range=32767.0).double()+ loss = criterion(img1.to(device), img2.to(device))++ assert loss.dtype == torch.float16+ expected = reference(img1.double(), img2.double()).float()+ self.assert_close(loss.float().cpu(), expected, atol=0.0, rtol=1e-2)++ def test_mixed_dtypes_follow_the_promotion_rule(self, device):+ generator = torch.Generator().manual_seed(0)+ img1 = torch.randint(0, 256, (1, 3, 32, 32), generator=generator, dtype=torch.uint8).to(device)+ img2 = torch.rand(1, 3, 32, 32, generator=generator).mul(255).to(device)++ # An integer image counts as the mask dtype, float32, as in ``ssim``.+ criterion = kornia.losses.MS_SSIMLoss(data_range=255.0).to(device)+ loss = criterion(img1, img2.half())+ assert loss.dtype == torch.float32+ self.assert_close(loss, criterion(img1.float(), img2.half().float()), atol=0.0, rtol=0.0)+ assert criterion(img2.half(), img1).dtype == torch.float32++ # A float32 image in a float64 module is filtered in float64 and returned in float32.+ if device.type != "mps":+ loss = criterion.double()(img1.float(), img2)+ assert loss.dtype == torch.float32+ self.assert_close(loss, criterion(img1.double(), img2.double()).float(), atol=0.0, rtol=0.0)++ def test_autocast_keeps_msssim_convolutions_in_float32(self):+ generator = torch.Generator().manual_seed(0)+ img1 = (180 + torch.rand(1, 3, 64, 64, generator=generator) * 75).round()+ img2 = (img1 + torch.randn(1, 3, 64, 64, generator=generator) * 20).clamp(0, 255).round()+ criterion = kornia.losses.MS_SSIMLoss(data_range=255.0)++ expected = criterion(img1, img2)+ with torch.autocast(device_type="cpu", dtype=torch.bfloat16):+ actual = criterion(img1, img2)++ self.assert_close(actual, expected)+def test_msssim_equal_none(self, device, dtype):# input dataimg1 = torch.rand(1, 3, 10, 16, device=device, dtype=dtype)