Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion monai/losses/image_dissimilarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,11 @@ def parzen_windowing_b_spline(self, img: torch.Tensor, order: int) -> tuple[torc
compute_img = (
img.float() if not torch.is_floating_point(img) or img.dtype in (torch.float16, torch.bfloat16) else img
)
_max, _min = torch.max(compute_img), torch.min(compute_img)
# Bin each image from its own intensity range (as in ITK's Mattes MI): a batch-wide min/max would make one
# sample's loss depend on the other images in the batch.
reduce_dims = tuple(range(1, compute_img.ndim))
_max = torch.amax(compute_img, dim=reduce_dims, keepdim=True)
_min = torch.amin(compute_img, dim=reduce_dims, keepdim=True)
padding = 2
interior_bins = self.num_bins - 2 * padding
value_range = _max - _min
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,23 @@ def test_b_spline_nonzero_ranges_are_finite(self, case_name, dtype, maximum):
self.assertIsNotNone(pred.grad)
self.assertTrue(torch.isfinite(pred.grad).all())

def test_b_spline_batch_samples_are_independent(self):
"""Verify each sample is binned from its own intensity range, not the batch's.

A per-sample loss must not change when other images with a different intensity range share the batch.
"""
generator = torch.Generator().manual_seed(0)
pred_a = torch.rand(1, 1, 32, 32, generator=generator, dtype=torch.float64)
target_a = 0.8 * pred_a + 0.2 * torch.rand(1, 1, 32, 32, generator=generator, dtype=torch.float64)
pred_b = 10 * torch.rand(1, 1, 32, 32, generator=generator, dtype=torch.float64)
target_b = 0.8 * pred_b + 2 * torch.rand(1, 1, 32, 32, generator=generator, dtype=torch.float64)
loss = GlobalMutualInformationLoss(kernel_type="b-spline", reduction="none")

alone = torch.cat([loss(pred_a, target_a).flatten(), loss(pred_b, target_b).flatten()])
batched = loss(torch.cat([pred_a, pred_b]), torch.cat([target_a, target_b])).flatten()

np.testing.assert_allclose(batched.numpy(), alone.numpy(), rtol=1e-6)


class TestGlobalMutualInformationLossBuffers(unittest.TestCase):
def test_gaussian_kernel_registers_buffers(self):
Expand Down
Loading