🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): validate mutual information inputs (#5591)
Puttala Jeevan Kumar9d8a9bda1cb9
diff --git a/changelog.d/5591.breaking.md b/changelog.d/5591.breaking.mdnew file mode 100644index 000000000..f07da8553--- /dev/null+++ b/changelog.d/5591.breaking.md@@ -0,0 +1,17 @@+The mutual information losses (`mutual_information_loss`, `normalized_mutual_information_loss`, their `_2d` and `_3d`+variants and the `MILossFromRef` / `NMILossFromRef` modules) now validate their arguments (#5548). Inputs that used to+return a value now raise kornia's `BaseError`: an integer mask (an `int64` 0/1 mask indexed positions 0 and 1 and gave+MI 0); a mask that is not shaped like one sample, `(N,)`, `(H, W)` or `(D, H, W)` (a `(W, H)` mask on `(H, W)` images+was read in row-major order, a flat `(H·W,)` mask on the `_2d` form was accepted, and a one-element or 0-d `True` mask+on the flat form meant no mask); masks whose intersection is empty (disjoint masks gave MI 0 and an NMI loss of -1); a+`num_bins` that is not an `int` of at least 2 (`1` gave 0, and floats such as `2.5` or `16.0` and NumPy integers ran);+and a negative `window_radius`. The functions raise `ShapeError` when `input` and `target` differ in shape, and the+`_2d` / `_3d` modules raise `BaseError` when the compared image differs from the reference: a `(W, H)` target against+an `(H, W)` input used to be flattened first and return a value. Errors that used to come from torch or Python now+come from kornia too: float masks, empty masks, batched masks, `window_radius=0` (`ZeroDivisionError`) and a size+mismatch in the `_2d` / `_3d` modules raise `BaseError`, so code that caught the `ValueError` of a batched flat mask+or of that size mismatch must catch `BaseError`. A `kernel_function` that is not an `MIKernel` member raises the+documented `ValueError` on every Python version instead of `TypeError` or `AttributeError`. Non-contiguous masks are+accepted, `uint8` masks keep working without torch's deprecation warning, and `MIKernel.rectangular` keeps the input+dtype: float64, float16 and bfloat16 inputs returned a float32 loss computed in float32. Calls with boolean masks and+the `xu` or `truncated_gaussian` kernels return the same values as before, bit for bit.diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.pyindex 9a3d6a531..6a456e490 100644--- a/kornia/losses/mutual_information.py+++ b/kornia/losses/mutual_information.py@@ -21,6 +21,7 @@ from functools import partialimport torch+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPEfrom kornia.core.utils import is_exporting@@ -60,7 +61,7 @@ def rectangular_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tentorch.Tensor: transformed signal"""x = torch.abs(x)- return torch.where(x <= window_radius, 1.0, 0.0)+ return (x <= window_radius).to(x.dtype)def truncated_gaussian_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tensor:@@ -97,14 +98,23 @@ class MIKernel(Enum):truncated_gaussian = member(truncated_gaussian_kernel)-def _flatten_mask(mask: torch.Tensor | None) -> torch.Tensor:- if mask is None:- return torch.tensor([True])- return mask.view(-1)+def _validate_mask(mask: torch.Tensor | None, shape: torch.Size) -> None:+ if mask is not None:+ KORNIA_CHECK_IS_TENSOR(mask, "mask must be a boolean tensor or None.")+ KORNIA_CHECK(mask.dtype in (torch.bool, torch.uint8), "mask must have boolean dtype (torch.bool or uint8).")+ KORNIA_CHECK(+ mask.shape == shape,+ f"mask must have one-sample shape {shape}, common to the batch. Got {mask.shape}.",+ )+++def _flatten_mask(mask: torch.Tensor | None, shape: torch.Size) -> torch.Tensor | None:+ _validate_mask(mask, shape)+ return None if mask is None else mask.reshape(-1)def _mask_is_full(mask: torch.Tensor | None) -> bool:- """Whether ``mask`` selects everything: ``None`` or a single ``True`` broadcast over the signal.+ """Whether ``mask`` selects everything: ``None`` or ``True`` for a one-element signal.A one-element mask is decided structurally under graph capture (a single ``False`` would maskthe whole signal, which is never meaningful), so exported graphs carry no data-dependent gather.@@ -171,7 +181,7 @@ class EntropyBasedLossBase(torch.nn.Module):reference_signal (torch.Tensor): reference signal to whichother signals will be compared by the forward methodmask (torch.Tensor | None): mask of roi in reference_signal, by default None- singleton shape, equal to reference_signal.shape[:-1]. It is a common mask for all the samples+ boolean with shape (N,), equal to reference_signal.shape[-1:]. It is common to all the samplesin reference_signal.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -184,18 +194,25 @@ class EntropyBasedLossBase(torch.nn.Module):ValueError: If kernel_function is not a valid MIKernel member."""super().__init__()+ KORNIA_CHECK(+ isinstance(num_bins, int) and not isinstance(num_bins, bool) and num_bins >= 2,+ "num_bins must be an integer >= 2.",+ )+ KORNIA_CHECK(window_radius > 0, "window_radius must be > 0.")+ if not isinstance(kernel_function, MIKernel):+ raise ValueError(f"kernel_function must be a MIKernel member, the available options are {list(MIKernel)}.")+ _validate_mask(mask, reference_signal.shape[-1:])self._ref_mask_is_full = _mask_is_full(mask)mask = self.fix_mask(mask, reference_signal)eps = torch.finfo(reference_signal.dtype).epsself.initial_shape = reference_signal.shapesignal = reference_signal[..., mask]+ # Without a mask the gather keeps every sample: checking its size would guard on a data-dependent size+ # and break ``fullgraph`` capture.+ KORNIA_CHECK(self._ref_mask_is_full or signal.shape[-1] > 0, "mask must select at least one sample.")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:- raise ValueError(- f"The passed_kernel_function is not an accepted MIKernel, the available options are {list(MIKernel)}."- )self.kernel_function = partial(kernel_function.value, window_radius=window_radius)self.window_radius = window_radius# A non-persistent buffer follows ``Module.to(device)`` and keeps the ``state_dict`` keys as they are.@@ -217,12 +234,10 @@ class EntropyBasedLossBase(torch.nn.Module):Returns:torch.Tensor: normalized mask"""+ _validate_mask(mask, masked_guy.shape[-1:])if mask is None:- mask = torch.tensor(1, dtype=torch.bool)- if mask.ndim > 1:- raise ValueError("the mask has to be a common mask for all elements of the batch, not a batch of masks")- mask = mask.broadcast_to(masked_guy.shape[-1])- return mask.to(masked_guy.device)+ return torch.ones(masked_guy.shape[-1], dtype=torch.bool, device=masked_guy.device)+ return mask.to(masked_guy.device, torch.bool)# TODO: optimize method below, maybe with ihdex coordinates conversiondef trace_in_ref_mask(self, other_signal, other_mask):@@ -277,6 +292,7 @@ class EntropyBasedLossBase(torch.nn.Module):raise ValueError(f"The two signals have incompatible shapes: {other_signal.shape} and {self.initial_shape}.")+ _validate_mask(other_mask, other_signal.shape[-1:])if self._ref_mask_is_full and _mask_is_full(other_mask):# No roi on either side: skip the boolean-mask gathers, whose output sizes depend on the# mask values and therefore cannot be captured by ``torch.export``/ONNX.@@ -285,11 +301,12 @@ class EntropyBasedLossBase(torch.nn.Module):else:# normalize in restriction to mask and recast in self.signal coordsother_mask = self.fix_mask(other_mask, other_signal)+ common_mask = other_mask[self.mask]+ ref_signal = self.signal[..., common_mask]+ KORNIA_CHECK(ref_signal.shape[-1] > 0, "mask intersection must select at least one sample.")other_signal = other_signal[..., other_mask]other_signal = _normalize_signal(other_signal, num_bins=self.num_bins, eps=eps)other_signal = self.trace_in_ref_mask(other_signal, other_mask)- common_mask = other_mask[self.mask]- ref_signal = self.signal[..., common_mask]other_signal = other_signal[..., common_mask]diff_1 = self.bin_centers.unsqueeze(-1) - ref_signal.unsqueeze(-2)@@ -420,8 +437,13 @@ class MILossFromRef2D(MILossFromRef):interval, by default 1.0"""super().__init__(- self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ self.arrange_shape(reference_signal),+ _flatten_mask(mask, reference_signal.shape[-2:]),+ kernel_function,+ num_bins,+ window_radius,)+ self._reference_shape = reference_signal.shape@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:@@ -456,7 +478,11 @@ class MILossFromRef2D(MILossFromRef):Returns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))+ KORNIA_CHECK(+ other_signal.shape == self._reference_shape,+ f"input and reference must have the same shape. Got {other_signal.shape} and {self._reference_shape}.",+ )+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask, other_signal.shape[-2:]))class MILossFromRef3D(MILossFromRef):@@ -492,8 +518,13 @@ class MILossFromRef3D(MILossFromRef):interval, by default 1.0"""super().__init__(- self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ self.arrange_shape(reference_signal),+ _flatten_mask(mask, reference_signal.shape[-3:]),+ kernel_function,+ num_bins,+ window_radius,)+ self._reference_shape = reference_signal.shape@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:@@ -528,7 +559,11 @@ class MILossFromRef3D(MILossFromRef):Returns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))+ KORNIA_CHECK(+ other_signal.shape == self._reference_shape,+ f"input and reference must have the same shape. Got {other_signal.shape} and {self._reference_shape}.",+ )+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask, other_signal.shape[-3:]))class NMILossFromRef2D(NMILossFromRef):@@ -564,8 +599,13 @@ class NMILossFromRef2D(NMILossFromRef):interval, by default 1.0"""super().__init__(- self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ self.arrange_shape(reference_signal),+ _flatten_mask(mask, reference_signal.shape[-2:]),+ kernel_function,+ num_bins,+ window_radius,)+ self._reference_shape = reference_signal.shape@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:@@ -599,7 +639,11 @@ class NMILossFromRef2D(NMILossFromRef):Returns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))+ KORNIA_CHECK(+ other_signal.shape == self._reference_shape,+ f"input and reference must have the same shape. Got {other_signal.shape} and {self._reference_shape}.",+ )+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask, other_signal.shape[-2:]))class NMILossFromRef3D(NMILossFromRef):@@ -635,8 +679,13 @@ class NMILossFromRef3D(NMILossFromRef):interval, by default 1.0"""super().__init__(- self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ self.arrange_shape(reference_signal),+ _flatten_mask(mask, reference_signal.shape[-3:]),+ kernel_function,+ num_bins,+ window_radius,)+ self._reference_shape = reference_signal.shape@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:@@ -670,7 +719,11 @@ class NMILossFromRef3D(NMILossFromRef):Returns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))+ KORNIA_CHECK(+ other_signal.shape == self._reference_shape,+ f"input and reference must have the same shape. Got {other_signal.shape} and {self._reference_shape}.",+ )+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask, other_signal.shape[-3:]))def mutual_information_loss(@@ -693,8 +746,8 @@ def mutual_information_loss(is any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of flat tensors, same shape asinput.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (N,), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (N,), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -706,6 +759,7 @@ def mutual_information_loss(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = MILossFromRef(reference_signal=target,mask=target_mask,@@ -735,8 +789,8 @@ def mutual_information_loss_2d(input (torch.Tensor): Batch of 2d tensors shape (B,H,W) where Bis any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of 2d tensors, same shape as input.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (H, W), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (H, W), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): The number of bins used for KDE, defaults to 64.@@ -747,6 +801,7 @@ def mutual_information_loss_2d(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = MILossFromRef2D(reference_signal=target,mask=target_mask,@@ -776,8 +831,8 @@ def mutual_information_loss_3d(input (torch.Tensor): Batch of 3d tensors shape (B,D,H,W) whereB is any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of 3d tensors, same shape as input.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (D, H, W), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (D, H, W), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -789,6 +844,7 @@ def mutual_information_loss_3d(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = MILossFromRef3D(reference_signal=target,mask=target_mask,@@ -819,8 +875,8 @@ def normalized_mutual_information_loss(is any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of flat tensors, same shape asinput.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (N,), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (N,), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -832,6 +888,7 @@ def normalized_mutual_information_loss(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = NMILossFromRef(reference_signal=target,kernel_function=kernel_function,@@ -861,8 +918,8 @@ def normalized_mutual_information_loss_2d(input (torch.Tensor): Batch of 2d tensors shape (B,H,W) where Bis any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of 2d tensors, same shape as input.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (H, W), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (H, W), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -874,6 +931,7 @@ def normalized_mutual_information_loss_2d(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = NMILossFromRef2D(reference_signal=target,mask=target_mask,@@ -903,8 +961,8 @@ def normalized_mutual_information_loss_3d(input (torch.Tensor): Batch of 3d tensors shape (B,D,H,W) whereB is any batch dimensions tuple, possibly empty.target (torch.Tensor): Batch of 3d tensors, same shape as input.- input_mask (torch.Tensor): mask of roi in input, defaults to None.- target_mask (torch.Tensor): mask of roi in target, defaults to None.+ input_mask (torch.Tensor): boolean roi mask of shape (D, H, W), common to the batch. Defaults to None.+ target_mask (torch.Tensor): boolean roi mask of shape (D, H, W), common to the batch. Defaults to None.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xu@@ -916,6 +974,7 @@ def normalized_mutual_information_loss_3d(torch.Tensor: tensor of losses, shape B (common batch dims tupleof input and target)"""+ KORNIA_CHECK_SAME_SHAPE(input, target)module = NMILossFromRef3D(reference_signal=target,mask=target_mask,diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.pyindex 4f066014c..72d5035af 100644--- a/tests/losses/test_mutual_information.py+++ b/tests/losses/test_mutual_information.py@@ -14,21 +14,32 @@# See the License for the specific language governing permissions and# limitations under the License.#+import warnings+import pytestimport torch+from kornia.core._compat import torch_version_lt+from kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.losses.mutual_information import (MIKernel,MILossFromRef,+ MILossFromRef2D,+ MILossFromRef3D,NMILossFromRef,+ NMILossFromRef2D,+ NMILossFromRef3D,_normalize_signal,mutual_information_loss,mutual_information_loss_2d,+ mutual_information_loss_3d,normalized_mutual_information_loss,normalized_mutual_information_loss_2d,+ normalized_mutual_information_loss_3d,+ rectangular_kernel,)-from testing.base import BaseTester+from testing.base import BaseTester, dynamo_is_availableclass TestMutualInformationLoss(BaseTester):@@ -159,7 +170,8 @@ class TestMutualInformationLoss(BaseTester):grad_pred, grad_target = torch.autograd.grad(loss_fn(pred_, target_, kernel_function=kernel).sum(), (pred_, target_))- assert grad_pred.isfinite().all() and grad_target.isfinite().all()+ assert grad_pred.isfinite().all()+ assert grad_target.isfinite().all()self.assert_close(grad_pred[1], torch.zeros_like(grad_pred[1]), rtol=0, atol=0)assert grad_pred[0].abs().sum() > 0scale = torch.ones((), device=device, dtype=dtype, requires_grad=True)@@ -354,3 +366,189 @@ class TestMutualInformationLoss(BaseTester):# 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"++ @pytest.mark.parametrize("loss_fn", [mutual_information_loss, normalized_mutual_information_loss])+ @pytest.mark.parametrize("kernel", [MIKernel.xu, MIKernel.truncated_gaussian])+ def test_masked_gradcheck(self, device, loss_fn, kernel):+ generator = torch.Generator().manual_seed(5548)+ signal = torch.rand((2, 8), generator=generator, dtype=torch.float64).to(device).requires_grad_()+ target = torch.rand((2, 8), generator=generator, dtype=torch.float64).to(device).requires_grad_()+ mask = torch.tensor([True, False, True, True, False, True, True, True], device=device)+ self.gradcheck(lambda x, y: loss_fn(x, y, mask, mask, kernel, 4), (signal, target))+++ "loss_fn,module,shape",+ [+ (mutual_information_loss, MILossFromRef, (12,)),+ (normalized_mutual_information_loss, NMILossFromRef, (12,)),+ (mutual_information_loss_2d, MILossFromRef2D, (3, 4)),+ (normalized_mutual_information_loss_2d, NMILossFromRef2D, (3, 4)),+ (mutual_information_loss_3d, MILossFromRef3D, (2, 3, 4)),+ (normalized_mutual_information_loss_3d, NMILossFromRef3D, (2, 3, 4)),+ ],+)+class TestMutualInformationValidation(BaseTester):+ @pytest.mark.parametrize("mask_dtype", [torch.int64, torch.int8, torch.float32])+ def test_mask_dtype(self, device, dtype, loss_fn, module, shape, mask_dtype):+ signal = torch.arange(1, 1 + torch.Size(shape).numel(), device=device, dtype=dtype).reshape(shape)+ mask = (signal > 2).to(mask_dtype)+ with pytest.raises(BaseError, match=r"mask.*boolean"):+ loss_fn(signal, signal, input_mask=mask)+ with pytest.raises(BaseError, match=r"mask.*boolean"):+ loss_fn(signal, signal, target_mask=mask)+ with pytest.raises(BaseError, match=r"mask.*boolean"):+ module(signal, mask)+ with pytest.raises(BaseError, match=r"mask.*boolean"):+ module(signal)(signal, mask)++ def test_uint8_mask_reads_as_boolean(self, device, dtype, loss_fn, module, shape):+ # A uint8 0/1 mask selected the same samples as a boolean one before the dtype check (#5548): keep it,+ # without torch's deprecation warning for uint8 indices.+ signal = torch.linspace(0, 1, 2 * torch.Size(shape).numel(), device=device, dtype=dtype).reshape(2, *shape)+ target = signal.flip(-1) ** 2+ mask = torch.arange(torch.Size(shape).numel(), device=device).reshape(shape) % 3 != 1+ expected = loss_fn(signal, target, mask, mask)+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ actual = loss_fn(signal, target, mask.to(torch.uint8), mask.to(torch.uint8))+ from_ref = module(target, mask.to(torch.uint8))(signal, mask.to(torch.uint8))+ assert torch.equal(actual, expected)+ assert torch.equal(from_ref, expected)++ @pytest.mark.parametrize("kind", ["transposed", "batched", "singleton", "scalar"])+ def test_mask_shape(self, device, dtype, loss_fn, module, shape, kind):+ signal = torch.ones((2, *shape), device=device, dtype=dtype)+ mask = torch.ones(shape, device=device, dtype=torch.bool)+ if kind == "transposed":+ mask = mask.unsqueeze(0) if len(shape) == 1 else mask.transpose(-1, -2).contiguous()+ elif kind == "batched":+ mask = mask.expand(2, *shape)+ elif kind == "singleton":+ mask = mask.new_ones((1,) * len(shape))+ else:+ mask = mask.new_ones(())+ with pytest.raises(BaseError, match=r"mask.*one-sample shape"):+ loss_fn(signal, signal, input_mask=mask)+ with pytest.raises(BaseError, match=r"mask.*one-sample shape"):+ loss_fn(signal, signal, target_mask=mask)+ with pytest.raises(BaseError, match=r"mask.*one-sample shape"):+ module(signal, mask)+ with pytest.raises(BaseError, match=r"mask.*one-sample shape"):+ module(signal)(signal, mask)++ def test_signal_shape_before_flattening(self, device, dtype, loss_fn, module, shape):+ signal = torch.ones((2, *shape), device=device, dtype=dtype)+ other = signal.transpose(-1, -2).contiguous()+ with pytest.raises(ShapeError, match="same shape"):+ loss_fn(signal, other)+ # The generic module retains its documented ValueError for incompatible signal shapes.+ with pytest.raises((BaseError, ValueError), match="shape"):+ module(signal)(other)++ @pytest.mark.parametrize("kind", ["input_empty", "target_empty", "disjoint"])+ def test_empty_mask_intersection(self, device, dtype, loss_fn, module, shape, kind):+ signal = torch.arange(torch.Size(shape).numel(), device=device, dtype=dtype).reshape(shape)+ input_mask = signal < 2+ target_mask = ~input_mask+ if kind == "input_empty":+ input_mask = torch.zeros_like(input_mask)+ target_mask = None+ elif kind == "target_empty":+ target_mask = torch.zeros_like(target_mask)+ input_mask = None+ with pytest.raises(BaseError, match=r"mask.*at least one sample"):+ loss_fn(signal, signal, input_mask, target_mask)+ with pytest.raises(BaseError, match=r"mask.*at least one sample"):+ module(signal, target_mask)(signal, input_mask)++ @pytest.mark.parametrize("num_bins", [0, 1, -1, 2.5, 2.0, True])+ def test_num_bins(self, device, dtype, loss_fn, module, shape, num_bins):+ signal = torch.ones(shape, device=device, dtype=dtype)+ with pytest.raises(BaseError, match="num_bins must be an integer >= 2"):+ loss_fn(signal, signal, num_bins=num_bins)+ with pytest.raises(BaseError, match="num_bins must be an integer >= 2"):+ module(signal, num_bins=num_bins)++ @pytest.mark.parametrize("window_radius", [0.0, -1.0])+ def test_window_radius(self, device, dtype, loss_fn, module, shape, window_radius):+ signal = torch.ones(shape, device=device, dtype=dtype)+ with pytest.raises(BaseError, match="window_radius must be > 0"):+ loss_fn(signal, signal, window_radius=window_radius)+ with pytest.raises(BaseError, match="window_radius must be > 0"):+ module(signal, window_radius=window_radius)++ @pytest.mark.parametrize("kernel", ["xu", MIKernel.xu.value, None, 0])+ def test_kernel_member(self, device, dtype, loss_fn, module, shape, kernel):+ signal = torch.ones(shape, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="kernel_function must be a MIKernel member"):+ loss_fn(signal, signal, kernel_function=kernel)+ with pytest.raises(ValueError, match="kernel_function must be a MIKernel member"):+ module(signal, kernel_function=kernel)++ @pytest.mark.parametrize("kernel", list(MIKernel))+ def test_valid_masks_and_boundaries(self, device, dtype, loss_fn, module, shape, kernel):+ generator = torch.Generator().manual_seed(5548)+ signal = torch.rand((2, *shape), generator=generator).to(device, dtype)+ target = torch.rand((2, *shape), generator=generator).to(device, dtype)+ # A non-contiguous mask with exactly one sample's shape remains valid; an image mask is laid out so that it+ # cannot be viewed flat.+ mask = torch.ones(shape, device=device, dtype=torch.bool)+ mask.view(-1)[1::3] = False+ mask = torch.stack([mask, mask], -1)[..., 0] if len(shape) == 1 else mask.mT.contiguous().mT+ assert not mask.is_contiguous()+ kwargs = {"kernel_function": kernel, "num_bins": 2, "window_radius": 0.5}+ actual = loss_fn(signal, target, mask, mask, **kwargs)+ flat_loss = (+ normalized_mutual_information_loss+ if module in (NMILossFromRef, NMILossFromRef2D, NMILossFromRef3D)+ else mutual_information_loss+ )+ expected = flat_loss(+ signal.reshape(2, -1)[:, mask.reshape(-1)], target.reshape(2, -1)[:, mask.reshape(-1)], **kwargs+ )+ self.assert_close(actual, expected)+ self.assert_close(actual, module(target, mask, **kwargs)(signal, mask))+ assert actual.dtype == dtype+ assert actual.device == device+ assert actual.isfinite().all()+ full_mask = torch.ones(shape, device=device, dtype=torch.bool)+ no_mask = loss_fn(signal, target, **kwargs)+ self.assert_close(no_mask, loss_fn(signal, target, full_mask, full_mask, **kwargs))+ self.assert_close(no_mask, module(target, **kwargs)(signal))+ assert no_mask.dtype == dtype+ assert no_mask.device == device+++class TestRectangularKernel(BaseTester):+ def test_dtype_and_values(self, device, dtype):+ signal = torch.tensor([-2, -1, 0, 1, 2], device=device, dtype=dtype)+ actual = rectangular_kernel(signal)+ assert actual.dtype == dtype+ assert actual.device == device+ self.assert_close(actual, signal.new_tensor([0, 1, 1, 1, 0]))++[email protected](not dynamo_is_available() or torch_version_lt(2, 9, 0), reason="Dynamo traces the gathers from 2.9")+ "loss_fn,shape",+ [+ (mutual_information_loss, (12,)),+ (normalized_mutual_information_loss, (12,)),+ (mutual_information_loss_2d, (3, 4)),+ (normalized_mutual_information_loss_2d, (3, 4)),+ (mutual_information_loss_3d, (2, 3, 4)),+ (normalized_mutual_information_loss_3d, (2, 3, 4)),+ ],+)+class TestMutualInformationEagerBackendTraces(BaseTester):+ # The names keep "compile" and "dynamo" out, so the ordinary jobs run these.+ def test_eager_backend_traces_without_a_mask(self, device, dtype, loss_fn, shape):+ # Without a mask the losses trace in one graph: the empty-mask check must not guard on the size of the+ # unmasked gather.+ signal = torch.linspace(0, 1, 2 * torch.Size(shape).numel(), device=device, dtype=dtype).reshape(2, *shape)+ target = signal.flip(-1) ** 2+ torch._dynamo.reset()+ with torch._dynamo.config.patch(capture_dynamic_output_shape_ops=True):+ compiled = torch.compile(loss_fn, backend="eager", fullgraph=True)+ self.assert_close(compiled(signal, target), loss_fn(signal, target))