Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(metrics): reflect the border of ssim3d like ssim and build its window in the input dtype (#5560)

εŒΊζ’“ηcb3571d57e39
diff --git a/changelog.d/5560.breaking.md b/changelog.d/5560.breaking.md
new file mode 100644
index 000000000..db10d4323
--- /dev/null
+++ b/changelog.d/5560.breaking.md
@@ -0,0 +1,8 @@
+`ssim3d`, `SSIM3D`, `ssim3d_loss` and `SSIM3DLoss` now reflect the volume at its faces for `padding='same'`, as
+`ssim` does for images (#5534). Previously they replicated the border, so a stack of identical slices did not
+reproduce the 2-D map near the faces, by up to 0.61 on random data. `'same'` results change within `window_size // 2`
+voxels of every face; the border does not reach `'valid'` results. A volume whose depth, height or width is
+`window_size // 2` or less used to return a `'same'` map and now raises torch's padding error, as `ssim` does for such
+images. Complex volumes, for which `ssim3d` returned a complex map, now raise the error that `ssim` raises for complex
+images, because the window is built in the input dtype: a `NotImplementedError`, or a plain `RuntimeError` on torch
+2.5.1.
diff --git a/changelog.d/5560.fixed.md b/changelog.d/5560.fixed.md
new file mode 100644
index 000000000..55aaafd30
--- /dev/null
+++ b/changelog.d/5560.fixed.md
@@ -0,0 +1,5 @@
+`ssim3d` now builds its Gaussian window in the device and dtype of the inputs, as `ssim` does, and filters mixed
+inputs in their common dtype (#5534). Float64 results are accurate to float64 roundoff instead of carrying the
+rounding of a float32 window, which moved them by under 1e-6 on uniform random volumes and by more on low-contrast
+ones, 8.3e-5 for values in [0.9, 1.0]. Float32 and half results on the CPU are unchanged; on a GPU the window is now
+computed on the device, which moves float32 results by float32 roundoff (1.1e-6 on MPS).
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index 73615713d..a9ff215da 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -79,6 +79,9 @@ def ssim3d(
The ssim index map with shape :math:`(B, C, D, H, W)`.
Note:
+ The volume is reflected at its faces for ``padding='same'``, as :func:`kornia.metrics.ssim` does for
+ images, so every spatial size must be larger than ``window_size // 2``. The Gaussian window is built in
+ the device and dtype of the inputs.
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.
@@ -117,9 +120,14 @@ def ssim3d(
img1 = img1.float()
if img2.dtype in (torch.float16, torch.bfloat16):
img2 = img2.float()
+ # Mixed inputs are filtered in their common dtype, which is also the dtype of the window.
+ compute_dtype = torch.promote_types(img1.dtype, img2.dtype)
+ img1, img2 = img1.to(compute_dtype), img2.to(compute_dtype)
# prepare kernel
- kernel: torch.Tensor = get_gaussian_kernel3d((window_size, window_size, window_size), (1.5, 1.5, 1.5))
+ kernel: torch.Tensor = get_gaussian_kernel3d(
+ (window_size, window_size, window_size), (1.5, 1.5, 1.5), device=img1.device, dtype=compute_dtype
+ )
# compute coefficients
C1: float = (0.01 * max_val) ** 2
@@ -127,8 +135,8 @@ def ssim3d(
# compute local mean per channel
with torch.autocast(device_type=img1.device.type, enabled=False):
- mu1: torch.Tensor = filter3d(img1, kernel)
- mu2: torch.Tensor = filter3d(img2, kernel)
+ mu1: torch.Tensor = filter3d(img1, kernel, border_type="reflect")
+ mu2: torch.Tensor = filter3d(img2, kernel, border_type="reflect")
cropping_shape: List[int] = []
if padding == "valid":
@@ -144,9 +152,9 @@ def ssim3d(
mu1_mu2 = mu1 * mu2
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)
+ mu_img1_sq = filter3d(img1**2, kernel, border_type="reflect")
+ mu_img2_sq = filter3d(img2**2, kernel, border_type="reflect")
+ mu_img1_img2 = filter3d(img1 * img2, kernel, border_type="reflect")
if padding == "valid":
mu_img1_sq = _crop(mu_img1_sq, cropping_shape)
diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.py
index 74190e99e..1231816a1 100644
--- a/tests/losses/test_ssim.py
+++ b/tests/losses/test_ssim.py
@@ -416,7 +416,8 @@ class TestSSIM3DLoss(BaseTester):
@pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
- @pytest.mark.parametrize("shape", [(1, 1, 2, 16, 16), (2, 4, 2, 15, 20)])
+ # The reflect padding of 'same' needs every spatial size to be larger than window_size // 2.
+ @pytest.mark.parametrize("shape", [(1, 1, 6, 16, 16), (2, 4, 6, 15, 20)])
def test_ssim(self, device, dtype, shape, window_size, reduction_type):
if device.type == "xla":
pytest.skip("test highly unstable with tpu")
@@ -496,7 +497,7 @@ class TestSSIM3DLoss(BaseTester):
# TODO: review method since it needs `nondet_tol` in cuda sometimes.
self.gradcheck(kornia.losses.ssim3d_loss, (img, img, 3), nondet_tol=1e-8)
- @pytest.mark.parametrize("shape", [(1, 2, 3, 5, 5), (2, 4, 2, 5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 2, 3, 5, 5), (2, 4, 3, 5, 5)])
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.py
index e317837d3..ae85f97a2 100644
--- a/tests/metrics/test_ssim3d.py
+++ b/tests/metrics/test_ssim3d.py
@@ -202,6 +202,16 @@ class TestSSIM3d(BaseTester):
kornia.metrics.ssim3d(img, img_b, 3)
assert "img1 and img2 shapes must be the same. Got:" in str(errinfo)
+ def test_exception_complex_volumes(self, device):
+ # The window is built in the input dtype, so a complex volume raises as in ssim, in every pairing; ssim3d used
+ # to return a complex map (#5534). torch raises NotImplementedError, a RuntimeError subclass, and a plain
+ # RuntimeError on 2.5.1.
+ real = torch.rand(1, 1, 6, 8, 8, device=device)
+ complex_ = real.to(torch.complex64)
+ for img1, img2 in ((real, complex_), (complex_, real), (complex_, complex_)):
+ with pytest.raises(RuntimeError, match="not implemented for 'ComplexFloat'"):
+ kornia.metrics.ssim3d(img1, img2, 3)
+
def test_unit(self, device, dtype):
img_a = torch.tensor(
[
@@ -225,9 +235,9 @@ class TestSSIM3d(BaseTester):
[
[
[
- [[0.0093, 0.0080, 0.0075], [0.0075, 0.0068, 0.0063], [0.0067, 0.0060, 0.0056]],
- [[0.0077, 0.0070, 0.0065], [0.0077, 0.0069, 0.0064], [0.0075, 0.0066, 0.0062]],
- [[0.0075, 0.0069, 0.0064], [0.0078, 0.0070, 0.0065], [0.0077, 0.0067, 0.0064]],
+ [[0.0070, 0.0065, 0.0066], [0.0073, 0.0068, 0.0065], [0.0074, 0.0073, 0.0070]],
+ [[0.0076, 0.0076, 0.0071], [0.0074, 0.0069, 0.0066], [0.0076, 0.0072, 0.0068]],
+ [[0.0072, 0.0068, 0.0067], [0.0075, 0.0069, 0.0066], [0.0085, 0.0085, 0.0075]],
]
]
],
@@ -237,6 +247,33 @@ class TestSSIM3d(BaseTester):
self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ def test_same_padding_matches_ssim_on_identical_slices(self, device, dtype):
+ """'same' padding reflects the volume at its faces as ssim does, so a stack of identical slices reproduces
+ the 2-D map on every slice; in float64 the window is float64 too, so they agree to roundoff (#5534)."""
+ generator = torch.Generator().manual_seed(0)
+ img1 = torch.rand(1, 2, 9, 11, generator=generator).to(device=device, dtype=dtype)
+ img2 = torch.rand(1, 2, 9, 11, generator=generator).to(device=device, dtype=dtype)
+ vol1 = img1[:, :, None].repeat(1, 1, 7, 1, 1)
+ vol2 = img2[:, :, None].repeat(1, 1, 7, 1, 1)
+
+ expected = kornia.metrics.ssim(img1, img2, 5)[:, :, None].repeat(1, 1, 7, 1, 1)
+ actual = kornia.metrics.ssim3d(vol1, vol2, 5, padding="same")
+
+ tolerance = {"rtol": 1e-12, "atol": 1e-12} if dtype == torch.float64 else {}
+ self.assert_close(actual, expected, **tolerance)
+
+ def test_mixed_float32_float64_pair_is_computed_in_float64(self, device, dtype):
+ # A float32/float64 pair is filtered in float64, the result dtype, with a float64 window, whichever argument
+ # is the float32 one, so it equals the all-float64 result to roundoff (#5534).
+ if dtype != torch.float64:
+ pytest.skip("the pair needs a float64 argument")
+ generator = torch.Generator().manual_seed(0)
+ img1 = torch.rand(1, 2, 6, 7, 9, generator=generator).to(device)
+ img2 = torch.rand(1, 2, 6, 7, 9, generator=generator, dtype=torch.float64).to(device)
+ expected = kornia.metrics.ssim3d(img1.double(), img2, 5)
+ self.assert_close(kornia.metrics.ssim3d(img1, img2, 5), expected, rtol=1e-12, atol=1e-12)
+ self.assert_close(kornia.metrics.ssim3d(img2, img1, 5), expected, rtol=1e-12, atol=1e-12)
+
@pytest.mark.parametrize(
"shape,padding,window_size,max_value",
[