🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Feat/mi add mask (#3581)
Gaël Cousin26fc95c8a0a3
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.pyindex 015a856a9..0be788d59 100644--- a/kornia/losses/mutual_information.py+++ b/kornia/losses/mutual_information.py@@ -88,6 +88,13 @@ 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])+ else:+ return mask.view(-1)++def _normalize_signal(data: torch.Tensor, num_bins: int, eps: float = 1e-8) -> torch.Tensor:min_val, _ = data.min(dim=-1)max_val, _ = data.max(dim=-1)@@ -128,6 +135,7 @@ class EntropyBasedLossBase(torch.nn.Module):def __init__(self,reference_signal: torch.Tensor,+ mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,@@ -137,6 +145,9 @@ class EntropyBasedLossBase(torch.nn.Module):Args:reference_signal (torch.Tensor): reference signal to whichother signals will be compared by the forward method+ mask (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+ in reference_signal.kernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): number of signal value bins in kernel@@ -148,8 +159,12 @@ class EntropyBasedLossBase(torch.nn.Module):ValueError: If kernel_function is not a valid MIKernel member."""super().__init__()+ mask = self.fix_mask(mask, reference_signal)self.eps = torch.finfo(reference_signal.dtype).eps- self.register_buffer("signal", _normalize_signal(reference_signal, num_bins, self.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("mask", mask)self.num_bins = num_binsif kernel_function not in MIKernel:raise ValueError(@@ -159,7 +174,36 @@ class EntropyBasedLossBase(torch.nn.Module):self.window_radius = window_radiusself.bin_centers = torch.arange(self.num_bins, device=self.signal.device)- def _compute_joint_histogram(self, other_signal: torch.Tensor, eps: float) -> torch.Tensor:+ @staticmethod+ def fix_mask(mask: torch.Tensor, masked_guy: torch.Tensor) -> torch.Tensor:+ """Convert mask to correct full mask if it is None.++ Args:+ mask (torch.Tensor | None): input mask+ masked_guy (torch.Tensor): the tensor to be masked by mask++ Returns:+ torch.Tensor: normalized mask+ """+ 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)++ # TODO: optimize method below, maybe with ihdex coordinates conversion+ def trace_in_ref_mask(self, other_signal, other_mask):+ if other_mask.all():+ return other_signal[..., self.mask]++ intermediate = torch.zeros(self.initial_shape).to(other_signal)+ intermediate[..., other_mask] = other_signal+ return intermediate[..., self.mask]++ def _compute_joint_histogram(+ self, other_signal: torch.Tensor, eps: float, other_mask: torch.Tensor | None = None+ ) -> torch.Tensor:"""Compute the joint histogram between the reference signal and another signal.Uses kernel density estimation to estimate the joint probability distribution@@ -170,20 +214,29 @@ class EntropyBasedLossBase(torch.nn.Module):other_signal (torch.Tensor): Signal to compare with the reference signal.Must have the same shape as the reference signal.eps (float): Epsilon value for numerical stability in computations.+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: Joint histogram tensor with shape [..., num_bins, num_bins]- representing the estimated joint probability distribution.+ representing the estimated joint probability distribution of the passed signals in the intersection+ of rois.Raises:ValueError: If other_signal has incompatible shape with reference signal."""- if other_signal.shape != self.signal.shape:- raise ValueError(f"The two signals have incompatible shapes: {other_signal.shape} and {self.signal.shape}.")+ if other_signal.shape != self.initial_shape:+ raise ValueError(+ f"The two signals have incompatible shapes: {other_signal.shape} and {self.initial_shape}."+ )+ # normalize in restriction to mask and recast in self.signal coords+ other_mask = self.fix_mask(other_mask, other_signal)+ 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]- diff_1 = self.bin_centers.unsqueeze(-1) - self.signal.unsqueeze(-2)- diff_2 = self.bin_centers.unsqueeze(-1) - other_signal.unsqueeze(-2)+ diff_1 = self.bin_centers.unsqueeze(-1) - self.signal[..., common_mask].unsqueeze(-2)+ diff_2 = self.bin_centers.unsqueeze(-1) - other_signal[..., common_mask].unsqueeze(-2)vals_1 = self.kernel_function(diff_1)vals_2 = self.kernel_function(diff_2)@@ -192,7 +245,9 @@ class EntropyBasedLossBase(torch.nn.Module):return joint_histogram- def entropies(self, other_signal: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ def entropies(+ self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""Compute entropy measures between the reference signal and another signal.Calculates joint entropy and marginal entropies based on the joint histogram of the two signals.@@ -200,6 +255,7 @@ class EntropyBasedLossBase(torch.nn.Module):Args:other_signal (torch.Tensor): Signal to compare with the reference signal.Must have the same shape as the reference_signal passed at instantiation.+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:tuple[torch.Tensor, torch.Tensor, torch.Tensor]: A tuple containing:@@ -213,12 +269,12 @@ class EntropyBasedLossBase(torch.nn.Module):Subclasses should implement specific loss functions based on these entropymeasures (e.g., mutual information)."""- joint_histogram = self._compute_joint_histogram(other_signal, self.eps)+ joint_histogram = self._compute_joint_histogram(other_signal, self.eps, other_mask)return _joint_histogram_to_entropies(joint_histogram, eps=self.eps)class MILossFromRef(EntropyBasedLossBase):- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None) -> torch.Tensor:"""Compute differentiable mutual information for self.signal and other_signal.mi = (H(X) + H(Y) - H(X,Y))@@ -228,18 +284,19 @@ class MILossFromRef(EntropyBasedLossBase):Args:other_signal: Batch of flat tensors shape (B,N) where B isthe tuple of batch dimensions for self.signal, possibly empty.+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- H_x, H_y, H_xy = self.entropies(other_signal)+ H_x, H_y, H_xy = self.entropies(other_signal, other_mask)mi = H_x + H_y - H_xyreturn -miclass NMILossFromRef(EntropyBasedLossBase):- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None) -> torch.Tensor:"""Compute differentiable normalized mutual information for self.signal and other_signal.nmi = (H(X) + H(Y)) / H(X,Y)@@ -249,11 +306,12 @@ class NMILossFromRef(EntropyBasedLossBase):Args:other_signal: Batch of flat tensors shape (B,N) where B isthe tuple of batch dimensions for self.signal, possibly empty.+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- H_x, H_y, H_xy = self.entropies(other_signal)+ H_x, H_y, H_xy = self.entropies(other_signal, other_mask)nmi = (H_x + H_y) / H_xyreturn -nmi@@ -271,6 +329,7 @@ class MILossFromRef2D(MILossFromRef):def __init__(self,reference_signal: torch.Tensor,+ mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1,@@ -282,6 +341,7 @@ class MILossFromRef2D(MILossFromRef):other signals will be compared by the forward method.batch of 2D images, shape (B,H,W) where B are the batchdimensions.+ mask (torch.Tensor | None): common mask of roi for all the samples in reference_signal, by default Nonekernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): number of signal value bins in kernel@@ -289,13 +349,19 @@ class MILossFromRef2D(MILossFromRef):window_radius (float): radius of the kernel's supportinterval, by default 1.0"""- super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)+ super().__init__(+ self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ )@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:return tensor.reshape(tensor.shape[:-2] + (-1,))- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(+ self,+ other_signal: torch.Tensor,+ other_mask: torch.Tensor | None = None,+ ) -> torch.Tensor:"""Compute differentiable mutual information for reference_signal and other_signal (both supposed 2D).mi = (H(X) + H(Y) - H(X,Y))@@ -305,11 +371,12 @@ class MILossFromRef2D(MILossFromRef):Args:other_signal: Batch of flat tensors same shape (B,H,W) asreference_signal passed for instantiation+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal))+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))class MILossFromRef3D(MILossFromRef):@@ -324,6 +391,7 @@ class MILossFromRef3D(MILossFromRef):def __init__(self,reference_signal: torch.Tensor,+ mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1,@@ -335,6 +403,7 @@ class MILossFromRef3D(MILossFromRef):other signals will be compared by the forward method.batch of 3D images, shape (B,D,H,W) where B are thebatch dimensions.+ mask (torch.Tensor | None): common mask of roi for all the samples in reference_signal, by default Nonekernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): number of signal value bins in kernel@@ -342,13 +411,19 @@ class MILossFromRef3D(MILossFromRef):window_radius (float): radius of the kernel's supportinterval, by default 1.0"""- super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)+ super().__init__(+ self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ )@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:return tensor.reshape(tensor.shape[:-3] + (-1,))- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(+ self,+ other_signal: torch.Tensor,+ other_mask: torch.Tensor | None = None,+ ) -> torch.Tensor:"""Compute differentiable mutual information for reference_signal and other_signal (both supposed 3D).mi = (H(X) + H(Y) - H(X,Y))@@ -358,11 +433,12 @@ class MILossFromRef3D(MILossFromRef):Args:other_signal: Batch of flat tensors same shape (B,D,H,W) asreference_signal passed for instantiation+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal))+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))class NMILossFromRef2D(NMILossFromRef):@@ -377,6 +453,7 @@ class NMILossFromRef2D(NMILossFromRef):def __init__(self,reference_signal: torch.Tensor,+ mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1,@@ -388,6 +465,7 @@ class NMILossFromRef2D(NMILossFromRef):other signals will be compared by the forward method.batch of 2D images, shape (B,H,W) where B are the batchdimensions.+ mask (torch.Tensor | None): common mask of roi for all the samples in reference_signal, by default Nonekernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): number of signal value bins in kernel@@ -395,13 +473,19 @@ class NMILossFromRef2D(NMILossFromRef):window_radius (float): radius of the kernel's supportinterval, by default 1.0"""- super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)+ super().__init__(+ self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ )@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:return tensor.reshape(tensor.shape[:-2] + (-1,))- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(+ self,+ other_signal: torch.Tensor,+ other_mask: torch.Tensor | None = None,+ ) -> torch.Tensor:"""Compute differentiable mutual information for reference_signal and other_signal (both supposed 2D).nmi = (H(X) + H(Y)) / H(X,Y)@@ -411,11 +495,12 @@ class NMILossFromRef2D(NMILossFromRef):Args:other_signal: Batch of tensors same shape (B,H,W) asreference_signal passed for instantiation+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal))+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))class NMILossFromRef3D(NMILossFromRef):@@ -430,6 +515,7 @@ class NMILossFromRef3D(NMILossFromRef):def __init__(self,reference_signal: torch.Tensor,+ mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1,@@ -441,6 +527,7 @@ class NMILossFromRef3D(NMILossFromRef):other signals will be compared by the forward method.batch of 3D images, shape (B,D,H,W) where B are thebatch dimensions.+ mask (torch.Tensor | None): common mask of roi for all the samples in reference_signal, by default Nonekernel_function (MIKernel): Used kernel function for kerneldensity estimate, by default MIKernel.xunum_bins (int): number of signal value bins in kernel@@ -448,13 +535,19 @@ class NMILossFromRef3D(NMILossFromRef):window_radius (float): radius of the kernel's supportinterval, by default 1.0"""- super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)+ super().__init__(+ self.arrange_shape(reference_signal), _flatten_mask(mask), kernel_function, num_bins, window_radius+ )@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:return tensor.reshape(tensor.shape[:-3] + (-1,))- def forward(self, other_signal: torch.Tensor) -> torch.Tensor:+ def forward(+ self,+ other_signal: torch.Tensor,+ other_mask: torch.Tensor | None = None,+ ) -> torch.Tensor:"""Compute differentiable mutual information for reference_signal and other_signal (both supposed 3D).nmi = (H(X) + H(Y)) / H(X,Y)@@ -464,16 +557,19 @@ class NMILossFromRef3D(NMILossFromRef):Args:other_signal: Batch of tensors, same shape (B,D,H,W) asreference_signal passed for instantiation+ other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to NoneReturns:torch.Tensor: tensor of losses, shape B as above"""- return super().forward(self.arrange_shape(other_signal))+ return super().forward(self.arrange_shape(other_signal), _flatten_mask(other_mask))def mutual_information_loss(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,@@ -489,6 +585,9 @@ 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.+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.@@ -500,21 +599,27 @@ def mutual_information_loss(of input and target)"""module = MILossFromRef(- reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius+ reference_signal=target,+ mask=target_mask,+ kernel_function=kernel_function,+ num_bins=num_bins,+ window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)def mutual_information_loss_2d(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,) -> torch.Tensor:"""Compute differentiable mutual information for 2d tensors.- nmi = (H(X) + H(Y)) / H(X,Y)+ mi = (H(X) + H(Y) - H(X,Y))To have a loss function, the opposite is returned.Can also handle two batches of 2d tensors, then a batch of loss values is returned.@@ -522,6 +627,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.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.@@ -533,21 +640,27 @@ def mutual_information_loss_2d(of input and target)"""module = MILossFromRef2D(- reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius+ reference_signal=target,+ mask=target_mask,+ kernel_function=kernel_function,+ num_bins=num_bins,+ window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)def mutual_information_loss_3d(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,) -> torch.Tensor:"""Compute differentiable mutual information for 3d tensors.- nmi = (H(X) + H(Y)) / H(X,Y)+ mi = (H(X) + H(Y) - H(X,Y))To have a loss function, the opposite is returned.Can also handle two batches of 3d tensors, then a batch of loss values is returned.@@ -555,6 +668,9 @@ 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.+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.@@ -566,14 +682,20 @@ def mutual_information_loss_3d(of input and target)"""module = MILossFromRef3D(- reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius+ reference_signal=target,+ mask=target_mask,+ kernel_function=kernel_function,+ num_bins=num_bins,+ window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)def normalized_mutual_information_loss(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,@@ -589,6 +711,9 @@ 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.+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.@@ -602,22 +727,25 @@ def normalized_mutual_information_loss(module = NMILossFromRef(reference_signal=target,kernel_function=kernel_function,+ mask=target_mask,num_bins=num_bins,window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)def normalized_mutual_information_loss_2d(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,) -> torch.Tensor:"""Compute differentiable normalized mutual information for 2d tensors.- mi = (H(X) + H(Y) - H(X,Y))+ nmi = (H(X) + H(Y)) / H(X,Y)To have a loss function, the opposite is returned.Can also handle two batches of 2d tensors, then a batch of loss values is returned.@@ -625,6 +753,9 @@ 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.+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.@@ -636,21 +767,27 @@ def normalized_mutual_information_loss_2d(of input and target)"""module = NMILossFromRef2D(- reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius+ reference_signal=target,+ mask=target_mask,+ kernel_function=kernel_function,+ num_bins=num_bins,+ window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)def normalized_mutual_information_loss_3d(input: torch.Tensor,target: torch.Tensor,+ input_mask: torch.Tensor | None = None,+ target_mask: torch.Tensor | None = None,kernel_function: MIKernel = MIKernel.xu,num_bins: int = 64,window_radius: float = 1.0,) -> torch.Tensor:"""Compute differentiable normalized mutual information for 3d tensors.- mi = (H(X) + H(Y) - H(X,Y))+ nmi = (H(X) + H(Y)) / H(X,Y)To have a loss function, the opposite is returned.Can also handle two batches of 3d tensors, then a batch of loss values is returned.@@ -658,6 +795,9 @@ 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.+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.@@ -669,6 +809,10 @@ def normalized_mutual_information_loss_3d(of input and target)"""module = NMILossFromRef3D(- reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius+ reference_signal=target,+ mask=target_mask,+ kernel_function=kernel_function,+ num_bins=num_bins,+ window_radius=window_radius,)- return module.forward(input)+ return module.forward(input, other_mask=input_mask)diff --git a/pixi.toml b/pixi.tomlindex 79652d2fd..4bb331c89 100644--- a/pixi.toml+++ b/pixi.toml@@ -63,7 +63,7 @@ clean = { cmd = "find . -type f -name '*.pyc' -delete && find . -type d -name '_# ------------------------------------------------------------------------------[feature.cuda.tasks]-install = { cmd = "uv sync --extra dev --extra x && uv pip install --reinstall torch torchvision --index pytorch-cu121", description = "Install dev dependencies (CUDA PyTorch)" }+install = { cmd = "uv sync --extra dev && uv pip install --reinstall torch torchvision --index pytorch-cu121", description = "Install dev dependencies (CUDA PyTorch)" }install-docs = { cmd = "uv sync --extra dev --extra docs --extra x && uv pip install --reinstall torch torchvision --index pytorch-cu121", description = "Install dev + docs (CUDA PyTorch)" }# CUDA test taskstest-cuda = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DEVICE = "cuda" }, description = "Run tests on CUDA" }diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.pyindex 9fc8d7f89..10826f90c 100644--- a/tests/losses/test_mutual_information.py+++ b/tests/losses/test_mutual_information.py@@ -22,7 +22,9 @@ from kornia.losses.mutual_information import (MILossFromRef,NMILossFromRef,mutual_information_loss,+ mutual_information_loss_2d,normalized_mutual_information_loss,+ normalized_mutual_information_loss_2d,)from testing.base import BaseTester@@ -49,8 +51,7 @@ class TestMutualInformationLoss(BaseTester):for radius in [1 / 2, 1, 2, 3]:# relative MI, expect 1assert torch.allclose(- self.relative_mi(img_1, img_2, window_radius=radius),- torch.ones(1, device=device, dtype=dtype),+ self.relative_mi(img_1, img_2, window_radius=radius), torch.ones(1, dtype=dtype, device=device)), "Wrong MI behaviour, correlated case."# relative MI, expect 0# NOTE: mutual_information_loss is a finite-sample, histogram-based estimator applied to random data.@@ -58,32 +59,32 @@ class TestMutualInformationLoss(BaseTester):# radii introduce noticeable variance, so we use a slightly looser atol here for test robustness.assert torch.allclose(self.relative_mi(img_1, img_3, window_radius=radius),- torch.zeros(1, device=device, dtype=dtype),+ torch.zeros(1, dtype=dtype, device=device),atol=0.2,), "Wrong MI behaviour, uncorrelated case."assert torch.allclose(self.relative_mi(img_2, img_3, window_radius=radius),- torch.zeros(1, device=device, dtype=dtype),+ torch.zeros(1, dtype=dtype, device=device),atol=0.2,), "Wrong MI behaviour, uncorrelated case."# NMI, expect -2assert torch.allclose(normalized_mutual_information_loss(img_1, img_2, window_radius=radius, num_bins=num_bins),- -2 * torch.ones(1, device=device, dtype=dtype),+ -2 * torch.ones(1, dtype=dtype, device=device),atol=0.2 * radius + 0.15,), "Wrong NMI behaviour, correlated case."# NMI, expect -1assert torch.allclose(normalized_mutual_information_loss(img_1, img_3, window_radius=radius, num_bins=num_bins),- -torch.ones(1, device=device, dtype=dtype),+ -torch.ones(1, dtype=dtype, device=device),atol=0.1,), "Wrong NMI behaviour, uncorrelated case."assert torch.allclose(normalized_mutual_information_loss(img_2, img_3, window_radius=radius, num_bins=num_bins),- -torch.ones(1, device=device, dtype=dtype),+ -torch.ones(1, dtype=dtype, device=device),atol=0.1,), "Wrong NMI behaviour, uncorrelated case."@@ -177,8 +178,12 @@ class TestMutualInformationLoss(BaseTester):normalized_loss_iterative = torch.stack(normalized_losses)# Compare- assert loss_batch.shape == dims[:-1], "The shape of the batched losses for mi is wrong."- assert normalized_loss_batch.shape == dims[:-1], "The shape of the batched losses for nmi is wrong."+ assert loss_batch.shape == dims[:-1], (+ f"The shape of the batched losses for mi is wrong: {loss_batch.shape} vs {dims[:-1]}."+ )+ assert normalized_loss_batch.shape == dims[:-1], (+ f"The shape of the batched losses for nmi is wrong: {normalized_loss_batch.shape} vs {dims[:-1]}."+ )assert torch.allclose(loss_batch.flatten(), loss_iterative, atol=1e-4), (f"Batch mismatch for mi! Batch: {loss_batch}, Iterative: {loss_iterative}"@@ -203,6 +208,33 @@ class TestMutualInformationLoss(BaseTester):self.assert_close(op(*args), op_module(pred))+ def test_masking(self, device, dtype):+ """test masking works on a 2d signal."""+ pred = torch.rand(2, 3, 200, 200, device=device, dtype=dtype)+ target = torch.rand(2, 3, 200, 200, device=device, dtype=dtype)+ target_mask = torch.zeros(pred.shape[-2:], dtype=torch.bool, device=device)+ pred_mask = target_mask.clone()+ target_mask[:100] = True+ pred_mask[:, :100] = True+ # we tweak the values of target and pred for the normalization to be the same with or without the mask+ target[..., 0, 0] = 0+ target[..., 0, 1] = 1+ pred[..., 0, 0] = 0+ pred[..., 0, 1] = 1+ restricted_pred = pred[..., :100, :100]+ restricted_target = target[..., :100, :100]++ masked_kwargs = {"input": pred, "target": target, "input_mask": pred_mask, "target_mask": target_mask}+ restricted_kwargs = {+ "input": restricted_pred,+ "target": restricted_target,+ }+ self.assert_close(mutual_information_loss_2d(**masked_kwargs), mutual_information_loss_2d(**restricted_kwargs))+ self.assert_close(+ normalized_mutual_information_loss_2d(**masked_kwargs),+ normalized_mutual_information_loss_2d(**restricted_kwargs),+ )+def test_dynamo(self, device, dtype, torch_optimizer):pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)