micro_sam.v2.loss.directed_distance_based

  1import torch
  2import torch.nn as nn
  3import torch.nn.functional as F
  4
  5from torch_em.loss import DiceLoss
  6
  7from ..transforms.labels import FOREGROUND_IGNORE_VALUE
  8
  9
 10def _masked_mse(prediction: torch.Tensor, target: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
 11    """Mean squared error over the masked elements only, normalized per sample.
 12
 13    Deliberately differs from torch_em's DistanceLoss, which averages over the whole patch and
 14    so scales the distance gradient by the foreground fraction.
 15    """
 16    error = (prediction - target).square() * mask
 17    dims = tuple(range(1, error.ndim))
 18    return (error.sum(dims) / mask.sum(dims).clamp_min(1.0)).mean()
 19
 20
 21class DirectedDistanceLoss(nn.Module):
 22    """Loss for directed distance based instance segmentation.
 23
 24    The inputs contain foreground, three directed distances, and an optional fifth boundary channel.
 25    The boundary loss combines Dice and binary cross entropy (BCE) with ``boundary_dice_weight``.
 26
 27    Args:
 28        mask_distances_in_bg: The flag to exclude background voxels from the distance loss.
 29        foreground_loss: The loss for foreground predictions and targets.
 30        with_boundaries: The flag for a fifth boundary channel in the inputs and targets.
 31        boundary_dice_weight: The Dice weight in the boundary loss. One selects Dice only.
 32            Zero selects BCE only. Values between zero and one mix the two losses.
 33    """
 34    def __init__(
 35        self,
 36        mask_distances_in_bg: bool = True,
 37        foreground_loss: nn.Module = DiceLoss(),
 38        with_boundaries: bool = False,
 39        boundary_dice_weight: float = 1.0,
 40    ) -> None:
 41        super().__init__()
 42
 43        if not 0.0 <= boundary_dice_weight <= 1.0:
 44            raise ValueError(f"boundary_dice_weight must be between zero and one, got {boundary_dice_weight}.")
 45
 46        self.foreground_loss = foreground_loss
 47        self.mask_distances_in_bg = mask_distances_in_bg
 48        self.with_boundaries = with_boundaries
 49        self.boundary_dice_weight = boundary_dice_weight
 50        self.boundary_loss = DiceLoss() if with_boundaries else None
 51
 52        self.init_kwargs = {
 53            "mask_distances_in_bg": mask_distances_in_bg,
 54            "with_boundaries": with_boundaries,
 55            "boundary_dice_weight": boundary_dice_weight,
 56        }
 57
 58    @property
 59    def n_channels(self) -> int:
 60        """Return the number of prediction and target channels."""
 61        return 4 + int(self.with_boundaries)
 62
 63    def forward(self, input_: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
 64        assert input_.shape == target.shape, (input_.shape, target.shape)
 65        assert input_.shape[1] == self.n_channels, (input_.shape, self.n_channels)
 66
 67        # IMPORTANT: preserve the channels!
 68        # Otherwise the Dice Loss will do all kinds of shennanigans.
 69        # Because it always interprets the first axis as channel,
 70        # and treats it differently (sums over it independently).
 71        # This will lead to a very large dice loss that dominates over everything else.
 72        fg_input, fg_target = input_[:, 0:1], target[:, 0:1]
 73
 74        # Voxels without ground truth carry FOREGROUND_IGNORE_VALUE (-1) in the foreground channel. Zeroing both
 75        # tensors there is a Dice loss mask, and the zeroed fg_target also drops them from the distance masks below.
 76        valid = (fg_target != FOREGROUND_IGNORE_VALUE).to(fg_target.dtype)
 77        fg_target = fg_target * valid
 78        fg_loss = self.foreground_loss(fg_input * valid, fg_target)
 79
 80        # Check whether the input is 2d or not.
 81        # For 2d inputs, we avoid computing gradients for masked (pseudo) z-distances.
 82        is_3d = (target.shape[2] != 1)
 83
 84        if self.mask_distances_in_bg:
 85            # The all-zero mask zeroes out the z-term (and its gradient) for 2d inputs.
 86            z_mask = fg_target if is_3d else torch.zeros_like(fg_target)
 87            yx_mask = fg_target
 88        else:
 89            z_mask = yx_mask = torch.ones_like(fg_target)
 90
 91        zdist_loss = _masked_mse(input_[:, 1:2], target[:, 1:2], z_mask)
 92        ydist_loss = _masked_mse(input_[:, 2:3], target[:, 2:3], yx_mask)
 93        xdist_loss = _masked_mse(input_[:, 3:4], target[:, 3:4], yx_mask)
 94
 95        overall_loss = fg_loss + zdist_loss + ydist_loss + xdist_loss
 96        if self.with_boundaries:
 97            boundary_input, boundary_target = input_[:, 4:5], target[:, 4:5]
 98            dice_loss = self.boundary_loss(boundary_input * valid, boundary_target * valid)
 99            if self.boundary_dice_weight == 1.0:
100                boundary_loss = dice_loss
101            else:
102                # CUDA autocast prohibits BCE on probabilities.
103                with torch.autocast(device_type=boundary_input.device.type, enabled=False):
104                    # Clamp rounded sigmoid outputs to keep them away from zero and one.
105                    probability = boundary_input.float().clamp(1e-6, 1.0 - 1e-6)
106                    error = F.binary_cross_entropy(probability, boundary_target.float(), reduction="none")
107                    # Normalize over valid voxels per sample, as for the distance terms.
108                    boundary_valid = valid.float()
109                    dims = tuple(range(1, error.ndim))
110                    bce_loss = ((error * boundary_valid).sum(dims) / boundary_valid.sum(dims).clamp_min(1.0)).mean()
111                boundary_loss = self.boundary_dice_weight * dice_loss + (1.0 - self.boundary_dice_weight) * bce_loss
112            overall_loss = overall_loss + boundary_loss
113        return overall_loss
class DirectedDistanceLoss(torch.nn.modules.module.Module):
 22class DirectedDistanceLoss(nn.Module):
 23    """Loss for directed distance based instance segmentation.
 24
 25    The inputs contain foreground, three directed distances, and an optional fifth boundary channel.
 26    The boundary loss combines Dice and binary cross entropy (BCE) with ``boundary_dice_weight``.
 27
 28    Args:
 29        mask_distances_in_bg: The flag to exclude background voxels from the distance loss.
 30        foreground_loss: The loss for foreground predictions and targets.
 31        with_boundaries: The flag for a fifth boundary channel in the inputs and targets.
 32        boundary_dice_weight: The Dice weight in the boundary loss. One selects Dice only.
 33            Zero selects BCE only. Values between zero and one mix the two losses.
 34    """
 35    def __init__(
 36        self,
 37        mask_distances_in_bg: bool = True,
 38        foreground_loss: nn.Module = DiceLoss(),
 39        with_boundaries: bool = False,
 40        boundary_dice_weight: float = 1.0,
 41    ) -> None:
 42        super().__init__()
 43
 44        if not 0.0 <= boundary_dice_weight <= 1.0:
 45            raise ValueError(f"boundary_dice_weight must be between zero and one, got {boundary_dice_weight}.")
 46
 47        self.foreground_loss = foreground_loss
 48        self.mask_distances_in_bg = mask_distances_in_bg
 49        self.with_boundaries = with_boundaries
 50        self.boundary_dice_weight = boundary_dice_weight
 51        self.boundary_loss = DiceLoss() if with_boundaries else None
 52
 53        self.init_kwargs = {
 54            "mask_distances_in_bg": mask_distances_in_bg,
 55            "with_boundaries": with_boundaries,
 56            "boundary_dice_weight": boundary_dice_weight,
 57        }
 58
 59    @property
 60    def n_channels(self) -> int:
 61        """Return the number of prediction and target channels."""
 62        return 4 + int(self.with_boundaries)
 63
 64    def forward(self, input_: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
 65        assert input_.shape == target.shape, (input_.shape, target.shape)
 66        assert input_.shape[1] == self.n_channels, (input_.shape, self.n_channels)
 67
 68        # IMPORTANT: preserve the channels!
 69        # Otherwise the Dice Loss will do all kinds of shennanigans.
 70        # Because it always interprets the first axis as channel,
 71        # and treats it differently (sums over it independently).
 72        # This will lead to a very large dice loss that dominates over everything else.
 73        fg_input, fg_target = input_[:, 0:1], target[:, 0:1]
 74
 75        # Voxels without ground truth carry FOREGROUND_IGNORE_VALUE (-1) in the foreground channel. Zeroing both
 76        # tensors there is a Dice loss mask, and the zeroed fg_target also drops them from the distance masks below.
 77        valid = (fg_target != FOREGROUND_IGNORE_VALUE).to(fg_target.dtype)
 78        fg_target = fg_target * valid
 79        fg_loss = self.foreground_loss(fg_input * valid, fg_target)
 80
 81        # Check whether the input is 2d or not.
 82        # For 2d inputs, we avoid computing gradients for masked (pseudo) z-distances.
 83        is_3d = (target.shape[2] != 1)
 84
 85        if self.mask_distances_in_bg:
 86            # The all-zero mask zeroes out the z-term (and its gradient) for 2d inputs.
 87            z_mask = fg_target if is_3d else torch.zeros_like(fg_target)
 88            yx_mask = fg_target
 89        else:
 90            z_mask = yx_mask = torch.ones_like(fg_target)
 91
 92        zdist_loss = _masked_mse(input_[:, 1:2], target[:, 1:2], z_mask)
 93        ydist_loss = _masked_mse(input_[:, 2:3], target[:, 2:3], yx_mask)
 94        xdist_loss = _masked_mse(input_[:, 3:4], target[:, 3:4], yx_mask)
 95
 96        overall_loss = fg_loss + zdist_loss + ydist_loss + xdist_loss
 97        if self.with_boundaries:
 98            boundary_input, boundary_target = input_[:, 4:5], target[:, 4:5]
 99            dice_loss = self.boundary_loss(boundary_input * valid, boundary_target * valid)
100            if self.boundary_dice_weight == 1.0:
101                boundary_loss = dice_loss
102            else:
103                # CUDA autocast prohibits BCE on probabilities.
104                with torch.autocast(device_type=boundary_input.device.type, enabled=False):
105                    # Clamp rounded sigmoid outputs to keep them away from zero and one.
106                    probability = boundary_input.float().clamp(1e-6, 1.0 - 1e-6)
107                    error = F.binary_cross_entropy(probability, boundary_target.float(), reduction="none")
108                    # Normalize over valid voxels per sample, as for the distance terms.
109                    boundary_valid = valid.float()
110                    dims = tuple(range(1, error.ndim))
111                    bce_loss = ((error * boundary_valid).sum(dims) / boundary_valid.sum(dims).clamp_min(1.0)).mean()
112                boundary_loss = self.boundary_dice_weight * dice_loss + (1.0 - self.boundary_dice_weight) * bce_loss
113            overall_loss = overall_loss + boundary_loss
114        return overall_loss

Loss for directed distance based instance segmentation.

The inputs contain foreground, three directed distances, and an optional fifth boundary channel. The boundary loss combines Dice and binary cross entropy (BCE) with boundary_dice_weight.

Arguments:
  • mask_distances_in_bg: The flag to exclude background voxels from the distance loss.
  • foreground_loss: The loss for foreground predictions and targets.
  • with_boundaries: The flag for a fifth boundary channel in the inputs and targets.
  • boundary_dice_weight: The Dice weight in the boundary loss. One selects Dice only. Zero selects BCE only. Values between zero and one mix the two losses.
DirectedDistanceLoss( mask_distances_in_bg: bool = True, foreground_loss: torch.nn.modules.module.Module = DiceLoss(), with_boundaries: bool = False, boundary_dice_weight: float = 1.0)
35    def __init__(
36        self,
37        mask_distances_in_bg: bool = True,
38        foreground_loss: nn.Module = DiceLoss(),
39        with_boundaries: bool = False,
40        boundary_dice_weight: float = 1.0,
41    ) -> None:
42        super().__init__()
43
44        if not 0.0 <= boundary_dice_weight <= 1.0:
45            raise ValueError(f"boundary_dice_weight must be between zero and one, got {boundary_dice_weight}.")
46
47        self.foreground_loss = foreground_loss
48        self.mask_distances_in_bg = mask_distances_in_bg
49        self.with_boundaries = with_boundaries
50        self.boundary_dice_weight = boundary_dice_weight
51        self.boundary_loss = DiceLoss() if with_boundaries else None
52
53        self.init_kwargs = {
54            "mask_distances_in_bg": mask_distances_in_bg,
55            "with_boundaries": with_boundaries,
56            "boundary_dice_weight": boundary_dice_weight,
57        }

Initialize internal Module state, shared by both nn.Module and ScriptModule.

foreground_loss
mask_distances_in_bg
with_boundaries
boundary_dice_weight
boundary_loss
init_kwargs
n_channels: int
59    @property
60    def n_channels(self) -> int:
61        """Return the number of prediction and target channels."""
62        return 4 + int(self.with_boundaries)

Return the number of prediction and target channels.

def forward(self, input_: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
 64    def forward(self, input_: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
 65        assert input_.shape == target.shape, (input_.shape, target.shape)
 66        assert input_.shape[1] == self.n_channels, (input_.shape, self.n_channels)
 67
 68        # IMPORTANT: preserve the channels!
 69        # Otherwise the Dice Loss will do all kinds of shennanigans.
 70        # Because it always interprets the first axis as channel,
 71        # and treats it differently (sums over it independently).
 72        # This will lead to a very large dice loss that dominates over everything else.
 73        fg_input, fg_target = input_[:, 0:1], target[:, 0:1]
 74
 75        # Voxels without ground truth carry FOREGROUND_IGNORE_VALUE (-1) in the foreground channel. Zeroing both
 76        # tensors there is a Dice loss mask, and the zeroed fg_target also drops them from the distance masks below.
 77        valid = (fg_target != FOREGROUND_IGNORE_VALUE).to(fg_target.dtype)
 78        fg_target = fg_target * valid
 79        fg_loss = self.foreground_loss(fg_input * valid, fg_target)
 80
 81        # Check whether the input is 2d or not.
 82        # For 2d inputs, we avoid computing gradients for masked (pseudo) z-distances.
 83        is_3d = (target.shape[2] != 1)
 84
 85        if self.mask_distances_in_bg:
 86            # The all-zero mask zeroes out the z-term (and its gradient) for 2d inputs.
 87            z_mask = fg_target if is_3d else torch.zeros_like(fg_target)
 88            yx_mask = fg_target
 89        else:
 90            z_mask = yx_mask = torch.ones_like(fg_target)
 91
 92        zdist_loss = _masked_mse(input_[:, 1:2], target[:, 1:2], z_mask)
 93        ydist_loss = _masked_mse(input_[:, 2:3], target[:, 2:3], yx_mask)
 94        xdist_loss = _masked_mse(input_[:, 3:4], target[:, 3:4], yx_mask)
 95
 96        overall_loss = fg_loss + zdist_loss + ydist_loss + xdist_loss
 97        if self.with_boundaries:
 98            boundary_input, boundary_target = input_[:, 4:5], target[:, 4:5]
 99            dice_loss = self.boundary_loss(boundary_input * valid, boundary_target * valid)
100            if self.boundary_dice_weight == 1.0:
101                boundary_loss = dice_loss
102            else:
103                # CUDA autocast prohibits BCE on probabilities.
104                with torch.autocast(device_type=boundary_input.device.type, enabled=False):
105                    # Clamp rounded sigmoid outputs to keep them away from zero and one.
106                    probability = boundary_input.float().clamp(1e-6, 1.0 - 1e-6)
107                    error = F.binary_cross_entropy(probability, boundary_target.float(), reduction="none")
108                    # Normalize over valid voxels per sample, as for the distance terms.
109                    boundary_valid = valid.float()
110                    dims = tuple(range(1, error.ndim))
111                    bce_loss = ((error * boundary_valid).sum(dims) / boundary_valid.sum(dims).clamp_min(1.0)).mean()
112                boundary_loss = self.boundary_dice_weight * dice_loss + (1.0 - self.boundary_dice_weight) * bce_loss
113            overall_loss = overall_loss + boundary_loss
114        return overall_loss

Define the computation performed at every call.

Should be overridden by all subclasses.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.