π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): compute integer SSIM inputs in float32 (#5304)
AhmetHakanBezir5589336c4057
diff --git a/changelog.d/5304.breaking.md b/changelog.d/5304.breaking.mdnew file mode 100644index 000000000..e98682ee3--- /dev/null+++ b/changelog.d/5304.breaking.md@@ -0,0 +1,5 @@+`ssim`, `ssim3d`, `SSIM` and `SSIM3D` now compute integer images in float32 and return a float32 map, and+`ssim_loss`, `ssim3d_loss`, `SSIMLoss` and `SSIM3DLoss` inherit the fix (#5297). Previously the fractional Gaussian+weights truncated to zero, so the result did not depend on the images: the map came back in the integer dtype, all 1+for `max_val=255.0` and all 0 for the default `max_val=1.0`, and each loss returned the same constant for every pair.+Pixel values are not rescaled, and floating-point inputs are unchanged.diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex 11f9fd33d..ccab73279 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -69,6 +69,7 @@ def ssim(The ssim index map with shape :math:`(B, C, H, W)`.Note:+ Integer images are converted to float32 before computing the local moments.Half-precision inputs are evaluated in float32 for numerical stability.Filtering runs with autocast disabled; the result uses the promoted input dtype.@@ -96,6 +97,12 @@ def ssim(if not img1.shape == img2.shape:raise ValueError(f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")+ # Preserve fractional Gaussian weights and avoid integer moment overflow.+ if not img1.is_floating_point() and not img1.is_complex():+ img1 = img1.to(torch.float32)+ if not img2.is_floating_point() and not img2.is_complex():+ img2 = img2.to(torch.float32)+output_dtype = torch.promote_types(img1.dtype, img2.dtype)# Half-precision moments can overflow before the SSIM ratio is formed.if img1.dtype in (torch.float16, torch.bfloat16):diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex 9731be9c2..13a6f0d8d 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -79,6 +79,7 @@ def ssim3d(The ssim index map with shape :math:`(B, C, D, H, W)`.Note:+ Integer images are converted to float32 before computing the local moments.Half-precision inputs are evaluated in float32 for numerical stability.Filtering runs with autocast disabled; the result uses the promoted input dtype.@@ -97,6 +98,12 @@ def ssim3d(if not isinstance(max_val, float):raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")+ # Preserve fractional Gaussian weights and avoid integer moment overflow.+ if not img1.is_floating_point() and not img1.is_complex():+ img1 = img1.to(torch.float32)+ if not img2.is_floating_point() and not img2.is_complex():+ img2 = img2.to(torch.float32)+output_dtype = torch.promote_types(img1.dtype, img2.dtype)# Half-precision moments can overflow before the SSIM ratio is formed.if img1.dtype in (torch.float16, torch.bfloat16):diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.pyindex 462e8ee8d..f04ae2c4e 100644--- a/tests/metrics/test_ssim3d.py+++ b/tests/metrics/test_ssim3d.py@@ -24,6 +24,32 @@ from testing.base import BaseTesterclass TestSSIM3d(BaseTester):+ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int16])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_integer_images(self, device, image_dtype, padding):+ # Integer Gaussian weights must not truncate to zero (#5297).+ black = torch.zeros((1, 1, 5, 5, 5), device=device, dtype=image_dtype)+ white = torch.full_like(black, 255)+ actual = kornia.metrics.ssim3d(black, white, 3, max_val=255.0, padding=padding)+ assert actual.dtype == torch.float32+ self.assert_close(actual, torch.full_like(actual, 0.0001), atol=1e-6, rtol=1e-4)++ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int16, torch.int32, torch.int64])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_integer_images_match_the_float32_result(self, device, image_dtype, padding):+ # A textured pair exercises the variances and the covariance, which a pair of constant images cancels.+ # The 12-bit values of the wider types are not all exact in float16.+ max_val = 255.0 if image_dtype == torch.uint8 else 4095.0+ generator = torch.Generator().manual_seed(0)+ img1 = (torch.rand((1, 2, 8, 8, 8), generator=generator) * max_val).round()+ img2 = (img1 + torch.randn((1, 2, 8, 8, 8), generator=generator) * max_val / 6).clamp(0, max_val).round()+ img1, img2 = img1.to(device), img2.to(device)+ expected = kornia.metrics.ssim3d(img1, img2, 5, max_val=max_val, padding=padding)+ actual = kornia.metrics.ssim3d(img1.to(image_dtype), img2.to(image_dtype), 5, max_val=max_val, padding=padding)+ assert actual.dtype == torch.float32+ assert expected.mean() < 0.95+ self.assert_close(actual, expected, rtol=0, atol=0)+def test_dynamo_dynamic_range(self, device, dtype, torch_optimizer):img = torch.full((1, 1) + (8,) * 3, 128.0, device=device, dtype=dtype)optimized = torch_optimizer(kornia.metrics.ssim3d)diff --git a/tests/metrics/test_ssim_metric.py b/tests/metrics/test_ssim_metric.pyindex 4a832cc09..ef7b8dc35 100644--- a/tests/metrics/test_ssim_metric.py+++ b/tests/metrics/test_ssim_metric.py@@ -26,6 +26,32 @@ from testing.base import BaseTesterclass TestSsim(BaseTester):+ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int16])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_integer_images(self, device, image_dtype, padding):+ # Integer Gaussian weights must not truncate to zero (#5297).+ black = torch.zeros((1, 1, 5, 5), device=device, dtype=image_dtype)+ white = torch.full_like(black, 255)+ actual = ssim(black, white, 3, max_val=255.0, padding=padding)+ assert actual.dtype == torch.float32+ self.assert_close(actual, torch.full_like(actual, 0.0001), atol=1e-6, rtol=1e-4)++ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int16, torch.int32, torch.int64])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_integer_images_match_the_float32_result(self, device, image_dtype, padding):+ # A textured pair exercises the variances and the covariance, which a pair of constant images cancels.+ # The 12-bit values of the wider types are not all exact in float16.+ max_val = 255.0 if image_dtype == torch.uint8 else 4095.0+ generator = torch.Generator().manual_seed(0)+ img1 = (torch.rand((1, 2, 16, 16), generator=generator) * max_val).round()+ img2 = (img1 + torch.randn((1, 2, 16, 16), generator=generator) * max_val / 6).clamp(0, max_val).round()+ img1, img2 = img1.to(device), img2.to(device)+ expected = ssim(img1, img2, 5, max_val=max_val, padding=padding)+ actual = ssim(img1.to(image_dtype), img2.to(image_dtype), 5, max_val=max_val, padding=padding)+ assert actual.dtype == torch.float32+ assert expected.mean() < 0.95+ self.assert_close(actual, expected, rtol=0, atol=0)+def test_dynamo_dynamic_range(self, device, dtype, torch_optimizer):img = torch.full((1, 1) + (8,) * 2, 128.0, device=device, dtype=dtype)optimized = torch_optimizer(ssim)