π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): keep half-precision SSIM moments finite (#5148)
AhmetHakanBezir942a0588b691
diff --git a/changelog.d/5148.fixed.md b/changelog.d/5148.fixed.mdnew file mode 100644index 000000000..7222b4fad--- /dev/null+++ b/changelog.d/5148.fixed.md@@ -0,0 +1,8 @@+`ssim`, `ssim3d`, `SSIM` and `SSIM3D`, and the `ssim_loss`, `SSIMLoss`, `ssim3d_loss` and `SSIM3DLoss` losses built+on them, compute float16 and bfloat16 inputs in float32 and return the map in the input dtype. In float16 the products+of the local moments overflowed for pixel-range data, so with `max_val=255.0` the map and the loss came back NaN (a+constant image of value 24 or more compared with itself was NaN everywhere), and with `max_val` of 0.75 or less an+all-zero region gave NaN because `C1 * C2` underflowed to zero; bfloat16 maps were up to 0.08 off on random+32 x 32 images. The convolutions also run with autocast disabled now: under `torch.autocast` a float32 input used to+give a map in the autocast dtype (bfloat16 on CPU, up to 0.07 off, and NaN for pixel-range data under float16+autocast), and now gives a float32 map.diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex 5474a8cd7..11f9fd33d 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -68,6 +68,10 @@ def ssim(Returns:The ssim index map with shape :math:`(B, C, H, W)`.+ Note:+ Half-precision inputs are evaluated in float32 for numerical stability.+ Filtering runs with autocast disabled; the result uses the promoted input dtype.+Examples:>>> input1 = torch.rand(1, 4, 5, 5)>>> input2 = torch.rand(1, 4, 5, 5)@@ -92,6 +96,13 @@ 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}")+ 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):+ img1 = img1.float()+ if img2.dtype in (torch.float16, torch.bfloat16):+ img2 = img2.float()+# prepare kernelkernel: torch.Tensor = get_gaussian_kernel1d(window_size, 1.5, device=img1.device, dtype=img1.dtype)@@ -100,8 +111,9 @@ def ssim(C2: float = (0.03 * max_val) ** 2# compute local mean per channel- mu1: torch.Tensor = filter2d_separable(img1, kernel, kernel)- mu2: torch.Tensor = filter2d_separable(img2, kernel, kernel)+ with torch.autocast(device_type=img1.device.type, enabled=False):+ mu1: torch.Tensor = filter2d_separable(img1, kernel, kernel)+ mu2: torch.Tensor = filter2d_separable(img2, kernel, kernel)cropping_shape: List[int] = []if padding == "valid":@@ -116,9 +128,10 @@ def ssim(mu2_sq = mu2**2mu1_mu2 = mu1 * mu2- mu_img1_sq = filter2d_separable(img1**2, kernel, kernel)- mu_img2_sq = filter2d_separable(img2**2, kernel, kernel)- mu_img1_img2 = filter2d_separable(img1 * img2, kernel, kernel)+ with torch.autocast(device_type=img1.device.type, enabled=False):+ mu_img1_sq = filter2d_separable(img1**2, kernel, kernel)+ mu_img2_sq = filter2d_separable(img2**2, kernel, kernel)+ mu_img1_img2 = filter2d_separable(img1 * img2, kernel, kernel)if padding == "valid":mu_img1_sq = _crop(mu_img1_sq, cropping_shape)@@ -136,7 +149,7 @@ def ssim(num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)- return num / (den + eps)+ return (num / (den + eps)).to(output_dtype)class SSIM(nn.Module):diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex c757a5de8..9731be9c2 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -78,6 +78,10 @@ def ssim3d(Returns:The ssim index map with shape :math:`(B, C, D, H, W)`.+ Note:+ Half-precision inputs are evaluated in float32 for numerical stability.+ Filtering runs with autocast disabled; the result uses the promoted input dtype.+Examples:>>> input1 = torch.rand(1, 4, 5, 5, 5)>>> input2 = torch.rand(1, 4, 5, 5, 5)@@ -93,6 +97,13 @@ def ssim3d(if not isinstance(max_val, float):raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")+ 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):+ img1 = img1.float()+ if img2.dtype in (torch.float16, torch.bfloat16):+ img2 = img2.float()+# prepare kernelkernel: torch.Tensor = get_gaussian_kernel3d((window_size, window_size, window_size), (1.5, 1.5, 1.5))@@ -101,8 +112,9 @@ def ssim3d(C2: float = (0.03 * max_val) ** 2# compute local mean per channel- mu1: torch.Tensor = filter3d(img1, kernel)- mu2: torch.Tensor = filter3d(img2, kernel)+ with torch.autocast(device_type=img1.device.type, enabled=False):+ mu1: torch.Tensor = filter3d(img1, kernel)+ mu2: torch.Tensor = filter3d(img2, kernel)cropping_shape: List[int] = []if padding == "valid":@@ -117,9 +129,10 @@ def ssim3d(mu2_sq = mu2**2mu1_mu2 = mu1 * mu2- mu_img1_sq = filter3d(img1**2, kernel)- mu_img2_sq = filter3d(img2**2, kernel)- mu_img1_img2 = filter3d(img1 * img2, kernel)+ with torch.autocast(device_type=img1.device.type, enabled=False):+ mu_img1_sq = filter3d(img1**2, kernel)+ mu_img2_sq = filter3d(img2**2, kernel)+ mu_img1_img2 = filter3d(img1 * img2, kernel)if padding == "valid":mu_img1_sq = _crop(mu_img1_sq, cropping_shape)@@ -137,7 +150,7 @@ def ssim3d(num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)- return num / (den + eps)+ return (num / (den + eps)).to(output_dtype)class SSIM3D(nn.Module):diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex ae9721578..92c2bab5d 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -445,5 +445,4 @@ call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_weighcall builtins.AssertionError tests/losses/test_mutual_information.py::TestMutualInformationLoss::test_value_ranges[cpu-bfloat16]call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_3d[cpu-bfloat16-pred0-expected0]call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_4d[cpu-bfloat16-pred0-expected0]-call builtins.AssertionError tests/metrics/test_ssim3d.py::TestSSIM3d::test_unit[cpu-bfloat16]call builtins.AssertionError tests/models/test_rt_detr.py::test_regvgg_optimize_for_deployment[cpu-bfloat16]diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.pyindex eadf944fc..462e8ee8d 100644--- a/tests/metrics/test_ssim3d.py+++ b/tests/metrics/test_ssim3d.py@@ -24,6 +24,66 @@ from testing.base import BaseTesterclass TestSSIM3d(BaseTester):+ 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)+ actual = optimized(img, img, 3, max_val=255.0)+ assert actual.dtype == dtype+ self.assert_close(actual, torch.ones_like(actual))++ def test_mixed_input_dtypes(self, device, dtype):+ first = torch.full((1, 1) + (8,) * 3, 128.0, device=device, dtype=dtype)+ second = torch.full_like(first, 64.0, dtype=torch.float32)+ actual = kornia.metrics.ssim3d(first, second, 3, max_val=255.0)+ output_dtype = torch.promote_types(dtype, torch.float32)+ assert actual.dtype == output_dtype+ c1 = (0.01 * 255.0) ** 2+ expected = torch.full_like(actual, (2 * 128 * 64 + c1) / (128**2 + 64**2 + c1))+ self.assert_close(actual, expected)++ def test_pixel_range_gradients(self, device, dtype):+ if device.type == "mps":+ pytest.skip("Float64 reference is unsupported on MPS")+ img1 = torch.arange(5**3, device=device, dtype=dtype).reshape((1, 1) + (5,) * 3) % 17 * 15+ img2 = (img1.flip(-1) * 0.8).detach().requires_grad_()+ img1 = img1.detach().requires_grad_()+ ref1, ref2 = img1.detach().double().requires_grad_(), img2.detach().double().requires_grad_()+ actual = kornia.metrics.ssim3d(img1, img2, 3, max_val=255.0)+ reference = kornia.metrics.ssim3d(ref1, ref2, 3, max_val=255.0)+ self.assert_close(actual, reference.to(dtype))+ actual_grads = torch.autograd.grad(actual.sum(), (img1, img2))+ reference_grads = torch.autograd.grad(reference.sum(), (ref1, ref2))+ for actual_grad, reference_grad in zip(actual_grads, reference_grads):+ assert torch.isfinite(actual_grad).all()+ self.assert_close(actual_grad, reference_grad.to(dtype), rtol=2e-2, atol=1e-5)++ def test_autocast_dynamic_range(self, device, dtype):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Autocast regression covers CPU and CUDA backends")+ img1 = torch.arange(8**3, device=device, dtype=dtype).reshape((1, 1) + (8,) * 3) % 17 * 15+ img2 = img1.flip(-1) * 0.8+ expected = kornia.metrics.ssim3d(img1.double(), img2.double(), 3, max_val=255.0).to(dtype)+ autocast_dtype = torch.float16 if device.type == "cuda" else torch.bfloat16+ with torch.autocast(device_type=device.type, dtype=autocast_dtype):+ actual = kornia.metrics.ssim3d(img1, img2, 3, max_val=255.0)+ assert actual.dtype == dtype+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("values", [(128.0, 128.0, 255.0), (128.0, 64.0, 255.0), (0.0, 0.0, 0.5)])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_constant_image_dynamic_range(self, device, dtype, values, padding):+ first, second, max_val = values+ shape = (1, 2) + (8,) * 3+ img1 = torch.full(shape, first, device=device, dtype=dtype)+ img2 = torch.full(shape, second, device=device, dtype=dtype)+ actual = kornia.metrics.ssim3d(img1, img2, 3, max_val=max_val, padding=padding)+ # Constant images have zero local variance/covariance in the SSIM formula.+ c1, c2 = (0.01 * max_val) ** 2, (0.03 * max_val) ** 2+ expected_value = (2 * first * second + c1) * c2 / ((first**2 + second**2 + c1) * c2 + 1e-12)+ expected = torch.full_like(actual, expected_value)+ assert actual.dtype == dtype+ self.assert_close(actual, expected)+@pytest.mark.parametrize("shape,padding,window_size,max_value",[diff --git a/tests/metrics/test_ssim_metric.py b/tests/metrics/test_ssim_metric.pyindex 4f77a086d..4a832cc09 100644--- a/tests/metrics/test_ssim_metric.py+++ b/tests/metrics/test_ssim_metric.py@@ -26,6 +26,66 @@ from testing.base import BaseTesterclass TestSsim(BaseTester):+ 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)+ actual = optimized(img, img, 3, max_val=255.0)+ assert actual.dtype == dtype+ self.assert_close(actual, torch.ones_like(actual))++ def test_mixed_input_dtypes(self, device, dtype):+ first = torch.full((1, 1) + (8,) * 2, 128.0, device=device, dtype=dtype)+ second = torch.full_like(first, 64.0, dtype=torch.float32)+ actual = ssim(first, second, 3, max_val=255.0)+ output_dtype = torch.promote_types(dtype, torch.float32)+ assert actual.dtype == output_dtype+ c1 = (0.01 * 255.0) ** 2+ expected = torch.full_like(actual, (2 * 128 * 64 + c1) / (128**2 + 64**2 + c1))+ self.assert_close(actual, expected)++ def test_pixel_range_gradients(self, device, dtype):+ if device.type == "mps":+ pytest.skip("Float64 reference is unsupported on MPS")+ img1 = torch.arange(5**2, device=device, dtype=dtype).reshape((1, 1) + (5,) * 2) % 17 * 15+ img2 = (img1.flip(-1) * 0.8).detach().requires_grad_()+ img1 = img1.detach().requires_grad_()+ ref1, ref2 = img1.detach().double().requires_grad_(), img2.detach().double().requires_grad_()+ actual = ssim(img1, img2, 3, max_val=255.0)+ reference = ssim(ref1, ref2, 3, max_val=255.0)+ self.assert_close(actual, reference.to(dtype))+ actual_grads = torch.autograd.grad(actual.sum(), (img1, img2))+ reference_grads = torch.autograd.grad(reference.sum(), (ref1, ref2))+ for actual_grad, reference_grad in zip(actual_grads, reference_grads):+ assert torch.isfinite(actual_grad).all()+ self.assert_close(actual_grad, reference_grad.to(dtype), rtol=2e-2, atol=1e-5)++ def test_autocast_dynamic_range(self, device, dtype):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Autocast regression covers CPU and CUDA backends")+ img1 = torch.arange(8**2, device=device, dtype=dtype).reshape((1, 1) + (8,) * 2) % 17 * 15+ img2 = img1.flip(-1) * 0.8+ expected = ssim(img1.double(), img2.double(), 3, max_val=255.0).to(dtype)+ autocast_dtype = torch.float16 if device.type == "cuda" else torch.bfloat16+ with torch.autocast(device_type=device.type, dtype=autocast_dtype):+ actual = ssim(img1, img2, 3, max_val=255.0)+ assert actual.dtype == dtype+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("values", [(128.0, 128.0, 255.0), (128.0, 64.0, 255.0), (0.0, 0.0, 0.5)])+ @pytest.mark.parametrize("padding", ["same", "valid"])+ def test_constant_image_dynamic_range(self, device, dtype, values, padding):+ first, second, max_val = values+ shape = (1, 2) + (8,) * 2+ img1 = torch.full(shape, first, device=device, dtype=dtype)+ img2 = torch.full(shape, second, device=device, dtype=dtype)+ actual = ssim(img1, img2, 3, max_val=max_val, padding=padding)+ # Constant images have zero local variance/covariance in the SSIM formula.+ c1, c2 = (0.01 * max_val) ** 2, (0.03 * max_val) ** 2+ expected_value = (2 * first * second + c1) * c2 / ((first**2 + second**2 + c1) * c2 + 1e-12)+ expected = torch.full_like(actual, expected_value)+ assert actual.dtype == dtype+ self.assert_close(actual, expected)+def test_same_image_returns_ones(self, device, dtype):img = torch.rand(1, 3, 16, 16, device=device, dtype=dtype)out = ssim(img, img, window_size=5)