Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): let the MI FromRef modules follow .to(device) and .to(dtype) (#5559)

εŒΊζ’“η7daff100f1a3
diff --git a/changelog.d/5559.fixed.md b/changelog.d/5559.fixed.md
new file mode 100644
index 000000000..7ee4138d1
--- /dev/null
+++ b/changelog.d/5559.fixed.md
@@ -0,0 +1,4 @@
+`MILossFromRef`, `NMILossFromRef` and their `2D`/`3D` variants now follow `Module.to(device)` and `Module.to(dtype)`
+(#5547): `bin_centers` is a non-persistent buffer, so a moved module no longer raises a device-mismatch error, and
+`eps` is read from the cached signal's dtype, so a module moved to float64 no longer keeps float32's epsilon. The
+`state_dict` keys are unchanged.
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index d75fb11e9..a3d59a616 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -182,10 +182,10 @@ class EntropyBasedLossBase(torch.nn.Module):
super().__init__()
self._ref_mask_is_full = _mask_is_full(mask)
mask = self.fix_mask(mask, reference_signal)
- self.eps = torch.finfo(reference_signal.dtype).eps
+ eps = torch.finfo(reference_signal.dtype).eps
self.initial_shape = reference_signal.shape
signal = reference_signal[..., mask]
- self.register_buffer("signal", _normalize_signal(signal, num_bins, self.eps))
+ self.register_buffer("signal", _normalize_signal(signal, num_bins, eps))
self.register_buffer("mask", mask)
self.num_bins = num_bins
if kernel_function not in MIKernel:
@@ -194,7 +194,13 @@ class EntropyBasedLossBase(torch.nn.Module):
)
self.kernel_function = partial(kernel_function.value, window_radius=window_radius)
self.window_radius = window_radius
- self.bin_centers = torch.arange(self.num_bins, device=self.signal.device)
+ # A non-persistent buffer follows ``Module.to(device)`` and keeps the ``state_dict`` keys as they are.
+ self.register_buffer("bin_centers", torch.arange(self.num_bins, device=self.signal.device), persistent=False)
+
+ @property
+ def eps(self) -> float:
+ """Machine epsilon of the cached reference signal, so that it follows ``Module.to(dtype)``."""
+ return torch.finfo(self.signal.dtype).eps
@staticmethod
def fix_mask(mask: torch.Tensor, masked_guy: torch.Tensor) -> torch.Tensor:
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index b2ab4fa59..c7934d408 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -247,3 +247,34 @@ class TestMutualInformationLoss(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(*args), op_optimized(*args), low_tolerance=True)
+
+ @pytest.mark.parametrize("module", [MILossFromRef, NMILossFromRef])
+ def test_to_dtype_matches_module_built_in_that_dtype(self, device, module):
+ """``.to(dtype)`` makes the module use that dtype's epsilon, like one built in that dtype (#5547)."""
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ generator = torch.Generator().manual_seed(0)
+ target = torch.rand(2, 12, 20, generator=generator).to(device)
+ pred = torch.rand(2, 12, 20, generator=generator).to(device)
+
+ moved = module(target).to(torch.float64)
+ built = module(target.double())
+
+ assert moved.eps == torch.finfo(torch.float64).eps
+ self.assert_close(moved(pred.double()), built(pred.double()))
+
+ @pytest.mark.parametrize("module", [MILossFromRef, NMILossFromRef])
+ def test_to_device_moves_bin_centers(self, device, module):
+ """``.to(device)`` moves ``bin_centers`` with the buffers and the ``state_dict`` keys stay the same (#5547)."""
+ target = torch.rand(2, 3, 3, 2)
+ pred = torch.rand(2, 3, 3, 2, device=device)
+
+ mod = module(target).to(device)
+
+ assert list(mod.state_dict().keys()) == ["signal", "mask"]
+ assert mod.bin_centers.device == mod.signal.device
+ self.assert_close(mod(pred), module(target.to(device))(pred))
+
+ # The meta device stands in for an accelerator on a CPU-only runner.
+ meta = module(target).to("meta")
+ assert meta.bin_centers.device.type == meta.signal.device.type == "meta"