micro_sam.v2.loss.custom_sam2_loss

  1import torch
  2import torch.nn as nn
  3import torch.nn.functional as F
  4import torch.distributed as dist
  5
  6from torch_em.loss import DiceLoss
  7
  8# Key under which the combined, backpropagated loss is returned. Must match
  9# CORE_LOSS_KEY = "core_loss" in the SAM2 training repo, which Sam2Trainer indexes.
 10CORE_LOSS_KEY = "core_loss"
 11
 12
 13def dice_loss(logits, targets, eps=1.0):
 14    """Soft Dice loss per object and mask candidate.
 15
 16    Args:
 17        logits: Predicted mask logits of shape (N, M, H, W).
 18        targets: Binary target masks of shape (N, M, H, W).
 19        eps: Laplace smoothing added to the numerator and denominator.
 20
 21    Returns:
 22        Dice loss of shape (N, M), one value per object and mask candidate.
 23    """
 24    probs = logits.sigmoid().flatten(2)
 25    targets = targets.flatten(2)
 26    numerator = 2 * (probs * targets).sum(-1)
 27    denominator = probs.sum(-1) + targets.sum(-1)
 28    return 1 - (numerator + eps) / (denominator + eps)
 29
 30
 31def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
 32    """Sigmoid focal loss per object and mask candidate, averaged over pixels.
 33
 34    Args:
 35        logits: Predicted mask logits of shape (N, M, H, W).
 36        targets: Binary target masks of shape (N, M, H, W).
 37        alpha: Class-balancing weight in (0, 1); set < 0 to disable balancing.
 38        gamma: Focusing parameter that down-weights easy pixels.
 39
 40    Returns:
 41        Focal loss of shape (N, M).
 42    """
 43    prob = logits.sigmoid()
 44    ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")
 45    p_t = prob * targets + (1 - prob) * (1 - targets)
 46    loss = ce * (1 - p_t) ** gamma
 47    if alpha >= 0:
 48        alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
 49        loss = alpha_t * loss
 50    return loss.flatten(2).mean(-1)
 51
 52
 53def iou_regression_loss(logits, targets, pred_ious, use_l1_loss=False):
 54    """Regression loss between the predicted IoU and the true mask IoU.
 55
 56    Args:
 57        logits: Predicted mask logits of shape (N, M, H, W).
 58        targets: Binary target masks of shape (N, M, H, W).
 59        pred_ious: IoU scores predicted by the model, of shape (N, M).
 60        use_l1_loss: Use L1 loss instead of MSE.
 61
 62    Returns:
 63        IoU regression loss of shape (N, M).
 64    """
 65    pred_mask = logits.flatten(2) > 0
 66    gt_mask = targets.flatten(2) > 0
 67    intersection = (pred_mask & gt_mask).sum(-1).float()
 68    union = (pred_mask | gt_mask).sum(-1).float()
 69    true_iou = intersection / union.clamp(min=1.0)
 70    if use_l1_loss:
 71        return F.l1_loss(pred_ious, true_iou, reduction="none")
 72    return F.mse_loss(pred_ious, true_iou, reduction="none")
 73
 74
 75def _num_objects(targets_batch):
 76    """Number of objects per frame, averaged across distributed ranks (min 1)."""
 77    num_objects = torch.tensor(float(targets_batch.shape[1]), device=targets_batch.device)
 78    if dist.is_available() and dist.is_initialized():
 79        dist.all_reduce(num_objects)
 80        num_objects = num_objects / dist.get_world_size()
 81    return num_objects.clamp(min=1).item()
 82
 83
 84class CustomSAM2Loss(nn.Module):
 85    """Readable interactive loss for SAM2 training, modeled on micro_sam's v1 SamTrainer.
 86
 87    Consumes the output structure of SAM2Train (a list of per-frame dicts holding the
 88    ``multistep_*`` keys) and returns a dict with the combined loss under ``"core_loss"``
 89    plus the individual components for logging.
 90
 91    The core supervision mirrors :class:`micro_sam.training.sam_trainer.SamTrainer`: a
 92    best-mask Dice loss plus an IoU regression loss, accumulated over all correction
 93    steps and frames. The two SAM2-specific terms - the focal mask loss and the
 94    object-presence (object-score) loss - are optional and toggled with booleans.
 95
 96    For each correction step the best mask candidate per object is selected by the
 97    smallest active mask loss (Dice alone, or Dice + focal when ``use_focal_loss`` is
 98    set). The Dice and focal terms use this best candidate; the IoU term is averaged over
 99    all candidates (matching both v1 and SAM2's ``supervise_all_iou=True``).
100
101    Args:
102        dice_weight: Weight of the Dice mask loss.
103        iou_weight: Weight of the IoU regression loss.
104        iou_use_l1_loss: Use L1 instead of MSE for the IoU regression loss.
105        use_focal_loss: Add SAM2's sigmoid focal mask loss alongside the Dice loss.
106        focal_weight: Weight of the focal mask loss when enabled.
107        focal_alpha: Alpha for the focal mask loss.
108        focal_gamma: Gamma for the focal mask loss.
109        use_object_score_loss: Supervise the object-presence score with a BCE loss.
110        object_score_weight: Weight of the object-score loss when enabled.
111        average_over_frames: Average the loss over frames instead of summing them. This
112            puts 2D (1 frame) and 3D (many frames) batches on the same scale, so neither
113            dominates when training on mixed 2D + 3D data. Summing is the SAM2 convention.
114        compile_kernels: Compile the Dice and the focal loss with ``torch.compile``. Both are chains
115            of elementwise ops over the (N, M, 1024, 1024) masks. The fused kernels read and write
116            less memory. The result does not change.
117    """
118
119    def __init__(
120        self,
121        dice_weight: float = 1.0,
122        iou_weight: float = 1.0,
123        iou_use_l1_loss: bool = False,
124        use_focal_loss: bool = False,
125        focal_weight: float = 20.0,
126        focal_alpha: float = 0.25,
127        focal_gamma: float = 2.0,
128        use_object_score_loss: bool = False,
129        object_score_weight: float = 1.0,
130        average_over_frames: bool = False,
131        compile_kernels: bool = False,
132    ):
133        super().__init__()
134        self.dice_weight = dice_weight
135        self.iou_weight = iou_weight
136        self.iou_use_l1_loss = iou_use_l1_loss
137        self.use_focal_loss = use_focal_loss
138        self.focal_weight = focal_weight
139        self.focal_alpha = focal_alpha
140        self.focal_gamma = focal_gamma
141        self.use_object_score_loss = use_object_score_loss
142        self.object_score_weight = object_score_weight
143        self.average_over_frames = average_over_frames
144        self.init_kwargs = {
145            "dice_weight": dice_weight, "iou_weight": iou_weight, "iou_use_l1_loss": iou_use_l1_loss,
146            "use_focal_loss": use_focal_loss, "focal_weight": focal_weight, "focal_alpha": focal_alpha,
147            "focal_gamma": focal_gamma, "use_object_score_loss": use_object_score_loss,
148            "object_score_weight": object_score_weight, "average_over_frames": average_over_frames,
149        }
150        # The number of objects varies per batch, so the kernels must be dynamic.
151        self.dice_loss = torch.compile(dice_loss, dynamic=True) if compile_kernels else dice_loss
152        self.focal_loss = torch.compile(focal_loss, dynamic=True) if compile_kernels else focal_loss
153
154    def _loss_per_frame(self, outputs, targets, num_objects):
155        """Accumulate the loss components over all correction steps for one frame."""
156        target_masks = targets.unsqueeze(1).float()  # (N, 1, H, W)
157        masks_list = outputs["multistep_pred_multimasks_high_res"]  # steps of (N, M, H, W)
158        ious_list = outputs["multistep_pred_ious"]  # steps of (N, M)
159        object_score_list = outputs["multistep_object_score_logits"]  # steps of (N, 1)
160
161        components = {"loss_dice": 0.0, "loss_iou": 0.0, "loss_focal": 0.0, "loss_object_score": 0.0}
162        for src_masks, pred_ious, object_score_logits in zip(masks_list, ious_list, object_score_list):
163            target = target_masks.expand_as(src_masks)  # (N, M, H, W)
164
165            dice = self.dice_loss(src_masks, target)  # (N, M)
166            iou = iou_regression_loss(src_masks, target, pred_ious, self.iou_use_l1_loss)  # (N, M)
167            focal = None
168            if self.use_focal_loss:
169                focal = self.focal_loss(src_masks, target, self.focal_alpha, self.focal_gamma)
170
171            # Pick the best mask candidate per object by the active mask loss.
172            select = dice if focal is None else self.dice_weight * dice + self.focal_weight * focal
173            best = select.argmin(dim=-1)  # (N,)
174            rows = torch.arange(select.shape[0], device=select.device)
175
176            # Only supervise the mask terms for objects that are present in this frame.
177            target_obj = (target_masks[:, 0].flatten(1) > 0).any(-1).float()  # (N,)
178
179            components["loss_dice"] += (dice[rows, best] * target_obj).sum() / num_objects
180            components["loss_iou"] += (iou.mean(-1) * target_obj).sum() / num_objects
181            if focal is not None:
182                components["loss_focal"] += (focal[rows, best] * target_obj).sum() / num_objects
183            if self.use_object_score_loss:
184                # BCE drives the presence score for both present and absent objects.
185                object_score_bce = F.binary_cross_entropy_with_logits(
186                    object_score_logits, target_obj.unsqueeze(-1), reduction="none",
187                )
188                components["loss_object_score"] += object_score_bce.mean(-1).sum() / num_objects
189
190        return components
191
192    def forward(self, outs_batch, targets_batch):
193        """Compute the loss over a batch of per-frame SAM2 outputs.
194
195        Args:
196            outs_batch: List of per-frame output dicts from SAM2Train.
197            targets_batch: Target instance masks of shape (T, N, H, W).
198
199        Returns:
200            Dict with the per-component losses and the combined loss under "core_loss".
201        """
202        assert len(outs_batch) == len(targets_batch)
203        num_objects = _num_objects(targets_batch)
204
205        losses = {"loss_dice": 0.0, "loss_iou": 0.0, "loss_focal": 0.0, "loss_object_score": 0.0}
206        for outputs, targets in zip(outs_batch, targets_batch):
207            for key, value in self._loss_per_frame(outputs, targets, num_objects).items():
208                losses[key] += value
209
210        # Average over frames so 2D (1 frame) and 3D (many frames) batches share a scale.
211        if self.average_over_frames:
212            n_frames = max(len(outs_batch), 1)
213            losses = {key: value / n_frames for key, value in losses.items()}
214
215        core_loss = self.dice_weight * losses["loss_dice"] + self.iou_weight * losses["loss_iou"]
216        if self.use_focal_loss:
217            core_loss = core_loss + self.focal_weight * losses["loss_focal"]
218        if self.use_object_score_loss:
219            core_loss = core_loss + self.object_score_weight * losses["loss_object_score"]
220
221        losses[CORE_LOSS_KEY] = core_loss
222        return losses
223
224
225class CustomSAM2Metric(nn.Module):
226    """Best-mask Dice metric for SAM2 interactive training, mirroring micro_sam's v1 SamTrainer.
227
228    Consumes SAM2Train's per-frame output dicts and scores only the initial (step-0)
229    prompt response - a single forward like v1's validation, which does not iterate over
230    correction steps. The later correction steps are oracle-driven toward the ground truth
231    and would inflate the score, so they are excluded. The oracle best mask candidate per
232    object (smallest Dice loss) is used.
233
234    The Dice loss is computed with :class:`torch_em.loss.DiceLoss` (the object axis placed
235    on the channel axis, ``reduce_channel=None``) so the values match v1's metric exactly.
236    Returns the mean Dice loss over present objects and frames (a [0, 1] value, lower is
237    better, like the metric returned by v1's SamTrainer). Report ``1 - value`` as the Dice
238    score.
239    """
240
241    def __init__(self):
242        super().__init__()
243        self.dice_loss = DiceLoss(reduce_channel=None)
244        self.init_kwargs = {}
245
246    def forward(self, outs_batch, targets_batch):
247        dice_sum = 0.0
248        dice_count = 0.0
249        for outputs, targets in zip(outs_batch, targets_batch):
250            target_masks = targets.unsqueeze(1).float()  # (N, 1, H, W)
251            probs = outputs["multistep_pred_multimasks_high_res"][0].sigmoid().float()  # step 0: (N, M, H, W)
252
253            # Per-object Dice loss for each mask candidate, with the object axis as the
254            # channel axis (matching v1's DiceLoss(reduce_channel=None) usage).
255            target = target_masks.swapaxes(0, 1)  # (1, N, H, W)
256            dice = torch.stack([
257                self.dice_loss(probs[:, i:i + 1].swapaxes(0, 1), target) for i in range(probs.shape[1])
258            ])  # (M, N)
259            best_dice = dice.min(dim=0).values  # (N,) oracle best of M candidates
260
261            # Only score objects that are present in this frame.
262            target_obj = (target_masks[:, 0].flatten(1) > 0).any(-1).float()  # (N,)
263            dice_sum = dice_sum + (best_dice * target_obj).sum()
264            dice_count = dice_count + target_obj.sum()
265
266        if torch.is_tensor(dice_count):
267            return dice_sum / dice_count.clamp(min=1.0)
268        return torch.zeros((), device=targets_batch.device)
CORE_LOSS_KEY = 'core_loss'
def dice_loss(logits, targets, eps=1.0):
14def dice_loss(logits, targets, eps=1.0):
15    """Soft Dice loss per object and mask candidate.
16
17    Args:
18        logits: Predicted mask logits of shape (N, M, H, W).
19        targets: Binary target masks of shape (N, M, H, W).
20        eps: Laplace smoothing added to the numerator and denominator.
21
22    Returns:
23        Dice loss of shape (N, M), one value per object and mask candidate.
24    """
25    probs = logits.sigmoid().flatten(2)
26    targets = targets.flatten(2)
27    numerator = 2 * (probs * targets).sum(-1)
28    denominator = probs.sum(-1) + targets.sum(-1)
29    return 1 - (numerator + eps) / (denominator + eps)

Soft Dice loss per object and mask candidate.

Arguments:
  • logits: Predicted mask logits of shape (N, M, H, W).
  • targets: Binary target masks of shape (N, M, H, W).
  • eps: Laplace smoothing added to the numerator and denominator.
Returns:

Dice loss of shape (N, M), one value per object and mask candidate.

def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
32def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
33    """Sigmoid focal loss per object and mask candidate, averaged over pixels.
34
35    Args:
36        logits: Predicted mask logits of shape (N, M, H, W).
37        targets: Binary target masks of shape (N, M, H, W).
38        alpha: Class-balancing weight in (0, 1); set < 0 to disable balancing.
39        gamma: Focusing parameter that down-weights easy pixels.
40
41    Returns:
42        Focal loss of shape (N, M).
43    """
44    prob = logits.sigmoid()
45    ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")
46    p_t = prob * targets + (1 - prob) * (1 - targets)
47    loss = ce * (1 - p_t) ** gamma
48    if alpha >= 0:
49        alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
50        loss = alpha_t * loss
51    return loss.flatten(2).mean(-1)

Sigmoid focal loss per object and mask candidate, averaged over pixels.

Arguments:
  • logits: Predicted mask logits of shape (N, M, H, W).
  • targets: Binary target masks of shape (N, M, H, W).
  • alpha: Class-balancing weight in (0, 1); set < 0 to disable balancing.
  • gamma: Focusing parameter that down-weights easy pixels.
Returns:

Focal loss of shape (N, M).

def iou_regression_loss(logits, targets, pred_ious, use_l1_loss=False):
54def iou_regression_loss(logits, targets, pred_ious, use_l1_loss=False):
55    """Regression loss between the predicted IoU and the true mask IoU.
56
57    Args:
58        logits: Predicted mask logits of shape (N, M, H, W).
59        targets: Binary target masks of shape (N, M, H, W).
60        pred_ious: IoU scores predicted by the model, of shape (N, M).
61        use_l1_loss: Use L1 loss instead of MSE.
62
63    Returns:
64        IoU regression loss of shape (N, M).
65    """
66    pred_mask = logits.flatten(2) > 0
67    gt_mask = targets.flatten(2) > 0
68    intersection = (pred_mask & gt_mask).sum(-1).float()
69    union = (pred_mask | gt_mask).sum(-1).float()
70    true_iou = intersection / union.clamp(min=1.0)
71    if use_l1_loss:
72        return F.l1_loss(pred_ious, true_iou, reduction="none")
73    return F.mse_loss(pred_ious, true_iou, reduction="none")

Regression loss between the predicted IoU and the true mask IoU.

Arguments:
  • logits: Predicted mask logits of shape (N, M, H, W).
  • targets: Binary target masks of shape (N, M, H, W).
  • pred_ious: IoU scores predicted by the model, of shape (N, M).
  • use_l1_loss: Use L1 loss instead of MSE.
Returns:

IoU regression loss of shape (N, M).

class CustomSAM2Loss(torch.nn.modules.module.Module):
 85class CustomSAM2Loss(nn.Module):
 86    """Readable interactive loss for SAM2 training, modeled on micro_sam's v1 SamTrainer.
 87
 88    Consumes the output structure of SAM2Train (a list of per-frame dicts holding the
 89    ``multistep_*`` keys) and returns a dict with the combined loss under ``"core_loss"``
 90    plus the individual components for logging.
 91
 92    The core supervision mirrors :class:`micro_sam.training.sam_trainer.SamTrainer`: a
 93    best-mask Dice loss plus an IoU regression loss, accumulated over all correction
 94    steps and frames. The two SAM2-specific terms - the focal mask loss and the
 95    object-presence (object-score) loss - are optional and toggled with booleans.
 96
 97    For each correction step the best mask candidate per object is selected by the
 98    smallest active mask loss (Dice alone, or Dice + focal when ``use_focal_loss`` is
 99    set). The Dice and focal terms use this best candidate; the IoU term is averaged over
100    all candidates (matching both v1 and SAM2's ``supervise_all_iou=True``).
101
102    Args:
103        dice_weight: Weight of the Dice mask loss.
104        iou_weight: Weight of the IoU regression loss.
105        iou_use_l1_loss: Use L1 instead of MSE for the IoU regression loss.
106        use_focal_loss: Add SAM2's sigmoid focal mask loss alongside the Dice loss.
107        focal_weight: Weight of the focal mask loss when enabled.
108        focal_alpha: Alpha for the focal mask loss.
109        focal_gamma: Gamma for the focal mask loss.
110        use_object_score_loss: Supervise the object-presence score with a BCE loss.
111        object_score_weight: Weight of the object-score loss when enabled.
112        average_over_frames: Average the loss over frames instead of summing them. This
113            puts 2D (1 frame) and 3D (many frames) batches on the same scale, so neither
114            dominates when training on mixed 2D + 3D data. Summing is the SAM2 convention.
115        compile_kernels: Compile the Dice and the focal loss with ``torch.compile``. Both are chains
116            of elementwise ops over the (N, M, 1024, 1024) masks. The fused kernels read and write
117            less memory. The result does not change.
118    """
119
120    def __init__(
121        self,
122        dice_weight: float = 1.0,
123        iou_weight: float = 1.0,
124        iou_use_l1_loss: bool = False,
125        use_focal_loss: bool = False,
126        focal_weight: float = 20.0,
127        focal_alpha: float = 0.25,
128        focal_gamma: float = 2.0,
129        use_object_score_loss: bool = False,
130        object_score_weight: float = 1.0,
131        average_over_frames: bool = False,
132        compile_kernels: bool = False,
133    ):
134        super().__init__()
135        self.dice_weight = dice_weight
136        self.iou_weight = iou_weight
137        self.iou_use_l1_loss = iou_use_l1_loss
138        self.use_focal_loss = use_focal_loss
139        self.focal_weight = focal_weight
140        self.focal_alpha = focal_alpha
141        self.focal_gamma = focal_gamma
142        self.use_object_score_loss = use_object_score_loss
143        self.object_score_weight = object_score_weight
144        self.average_over_frames = average_over_frames
145        self.init_kwargs = {
146            "dice_weight": dice_weight, "iou_weight": iou_weight, "iou_use_l1_loss": iou_use_l1_loss,
147            "use_focal_loss": use_focal_loss, "focal_weight": focal_weight, "focal_alpha": focal_alpha,
148            "focal_gamma": focal_gamma, "use_object_score_loss": use_object_score_loss,
149            "object_score_weight": object_score_weight, "average_over_frames": average_over_frames,
150        }
151        # The number of objects varies per batch, so the kernels must be dynamic.
152        self.dice_loss = torch.compile(dice_loss, dynamic=True) if compile_kernels else dice_loss
153        self.focal_loss = torch.compile(focal_loss, dynamic=True) if compile_kernels else focal_loss
154
155    def _loss_per_frame(self, outputs, targets, num_objects):
156        """Accumulate the loss components over all correction steps for one frame."""
157        target_masks = targets.unsqueeze(1).float()  # (N, 1, H, W)
158        masks_list = outputs["multistep_pred_multimasks_high_res"]  # steps of (N, M, H, W)
159        ious_list = outputs["multistep_pred_ious"]  # steps of (N, M)
160        object_score_list = outputs["multistep_object_score_logits"]  # steps of (N, 1)
161
162        components = {"loss_dice": 0.0, "loss_iou": 0.0, "loss_focal": 0.0, "loss_object_score": 0.0}
163        for src_masks, pred_ious, object_score_logits in zip(masks_list, ious_list, object_score_list):
164            target = target_masks.expand_as(src_masks)  # (N, M, H, W)
165
166            dice = self.dice_loss(src_masks, target)  # (N, M)
167            iou = iou_regression_loss(src_masks, target, pred_ious, self.iou_use_l1_loss)  # (N, M)
168            focal = None
169            if self.use_focal_loss:
170                focal = self.focal_loss(src_masks, target, self.focal_alpha, self.focal_gamma)
171
172            # Pick the best mask candidate per object by the active mask loss.
173            select = dice if focal is None else self.dice_weight * dice + self.focal_weight * focal
174            best = select.argmin(dim=-1)  # (N,)
175            rows = torch.arange(select.shape[0], device=select.device)
176
177            # Only supervise the mask terms for objects that are present in this frame.
178            target_obj = (target_masks[:, 0].flatten(1) > 0).any(-1).float()  # (N,)
179
180            components["loss_dice"] += (dice[rows, best] * target_obj).sum() / num_objects
181            components["loss_iou"] += (iou.mean(-1) * target_obj).sum() / num_objects
182            if focal is not None:
183                components["loss_focal"] += (focal[rows, best] * target_obj).sum() / num_objects
184            if self.use_object_score_loss:
185                # BCE drives the presence score for both present and absent objects.
186                object_score_bce = F.binary_cross_entropy_with_logits(
187                    object_score_logits, target_obj.unsqueeze(-1), reduction="none",
188                )
189                components["loss_object_score"] += object_score_bce.mean(-1).sum() / num_objects
190
191        return components
192
193    def forward(self, outs_batch, targets_batch):
194        """Compute the loss over a batch of per-frame SAM2 outputs.
195
196        Args:
197            outs_batch: List of per-frame output dicts from SAM2Train.
198            targets_batch: Target instance masks of shape (T, N, H, W).
199
200        Returns:
201            Dict with the per-component losses and the combined loss under "core_loss".
202        """
203        assert len(outs_batch) == len(targets_batch)
204        num_objects = _num_objects(targets_batch)
205
206        losses = {"loss_dice": 0.0, "loss_iou": 0.0, "loss_focal": 0.0, "loss_object_score": 0.0}
207        for outputs, targets in zip(outs_batch, targets_batch):
208            for key, value in self._loss_per_frame(outputs, targets, num_objects).items():
209                losses[key] += value
210
211        # Average over frames so 2D (1 frame) and 3D (many frames) batches share a scale.
212        if self.average_over_frames:
213            n_frames = max(len(outs_batch), 1)
214            losses = {key: value / n_frames for key, value in losses.items()}
215
216        core_loss = self.dice_weight * losses["loss_dice"] + self.iou_weight * losses["loss_iou"]
217        if self.use_focal_loss:
218            core_loss = core_loss + self.focal_weight * losses["loss_focal"]
219        if self.use_object_score_loss:
220            core_loss = core_loss + self.object_score_weight * losses["loss_object_score"]
221
222        losses[CORE_LOSS_KEY] = core_loss
223        return losses

Readable interactive loss for SAM2 training, modeled on micro_sam's v1 SamTrainer.

Consumes the output structure of SAM2Train (a list of per-frame dicts holding the multistep_* keys) and returns a dict with the combined loss under "core_loss" plus the individual components for logging.

The core supervision mirrors micro_sam.training.sam_trainer.SamTrainer: a best-mask Dice loss plus an IoU regression loss, accumulated over all correction steps and frames. The two SAM2-specific terms - the focal mask loss and the object-presence (object-score) loss - are optional and toggled with booleans.

For each correction step the best mask candidate per object is selected by the smallest active mask loss (Dice alone, or Dice + focal when use_focal_loss is set). The Dice and focal terms use this best candidate; the IoU term is averaged over all candidates (matching both v1 and SAM2's supervise_all_iou=True).

Arguments:
  • dice_weight: Weight of the Dice mask loss.
  • iou_weight: Weight of the IoU regression loss.
  • iou_use_l1_loss: Use L1 instead of MSE for the IoU regression loss.
  • use_focal_loss: Add SAM2's sigmoid focal mask loss alongside the Dice loss.
  • focal_weight: Weight of the focal mask loss when enabled.
  • focal_alpha: Alpha for the focal mask loss.
  • focal_gamma: Gamma for the focal mask loss.
  • use_object_score_loss: Supervise the object-presence score with a BCE loss.
  • object_score_weight: Weight of the object-score loss when enabled.
  • average_over_frames: Average the loss over frames instead of summing them. This puts 2D (1 frame) and 3D (many frames) batches on the same scale, so neither dominates when training on mixed 2D + 3D data. Summing is the SAM2 convention.
  • compile_kernels: Compile the Dice and the focal loss with torch.compile. Both are chains of elementwise ops over the (N, M, 1024, 1024) masks. The fused kernels read and write less memory. The result does not change.
CustomSAM2Loss( dice_weight: float = 1.0, iou_weight: float = 1.0, iou_use_l1_loss: bool = False, use_focal_loss: bool = False, focal_weight: float = 20.0, focal_alpha: float = 0.25, focal_gamma: float = 2.0, use_object_score_loss: bool = False, object_score_weight: float = 1.0, average_over_frames: bool = False, compile_kernels: bool = False)
120    def __init__(
121        self,
122        dice_weight: float = 1.0,
123        iou_weight: float = 1.0,
124        iou_use_l1_loss: bool = False,
125        use_focal_loss: bool = False,
126        focal_weight: float = 20.0,
127        focal_alpha: float = 0.25,
128        focal_gamma: float = 2.0,
129        use_object_score_loss: bool = False,
130        object_score_weight: float = 1.0,
131        average_over_frames: bool = False,
132        compile_kernels: bool = False,
133    ):
134        super().__init__()
135        self.dice_weight = dice_weight
136        self.iou_weight = iou_weight
137        self.iou_use_l1_loss = iou_use_l1_loss
138        self.use_focal_loss = use_focal_loss
139        self.focal_weight = focal_weight
140        self.focal_alpha = focal_alpha
141        self.focal_gamma = focal_gamma
142        self.use_object_score_loss = use_object_score_loss
143        self.object_score_weight = object_score_weight
144        self.average_over_frames = average_over_frames
145        self.init_kwargs = {
146            "dice_weight": dice_weight, "iou_weight": iou_weight, "iou_use_l1_loss": iou_use_l1_loss,
147            "use_focal_loss": use_focal_loss, "focal_weight": focal_weight, "focal_alpha": focal_alpha,
148            "focal_gamma": focal_gamma, "use_object_score_loss": use_object_score_loss,
149            "object_score_weight": object_score_weight, "average_over_frames": average_over_frames,
150        }
151        # The number of objects varies per batch, so the kernels must be dynamic.
152        self.dice_loss = torch.compile(dice_loss, dynamic=True) if compile_kernels else dice_loss
153        self.focal_loss = torch.compile(focal_loss, dynamic=True) if compile_kernels else focal_loss

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

dice_weight
iou_weight
iou_use_l1_loss
use_focal_loss
focal_weight
focal_alpha
focal_gamma
use_object_score_loss
object_score_weight
average_over_frames
init_kwargs
dice_loss
focal_loss
def forward(self, outs_batch, targets_batch):
193    def forward(self, outs_batch, targets_batch):
194        """Compute the loss over a batch of per-frame SAM2 outputs.
195
196        Args:
197            outs_batch: List of per-frame output dicts from SAM2Train.
198            targets_batch: Target instance masks of shape (T, N, H, W).
199
200        Returns:
201            Dict with the per-component losses and the combined loss under "core_loss".
202        """
203        assert len(outs_batch) == len(targets_batch)
204        num_objects = _num_objects(targets_batch)
205
206        losses = {"loss_dice": 0.0, "loss_iou": 0.0, "loss_focal": 0.0, "loss_object_score": 0.0}
207        for outputs, targets in zip(outs_batch, targets_batch):
208            for key, value in self._loss_per_frame(outputs, targets, num_objects).items():
209                losses[key] += value
210
211        # Average over frames so 2D (1 frame) and 3D (many frames) batches share a scale.
212        if self.average_over_frames:
213            n_frames = max(len(outs_batch), 1)
214            losses = {key: value / n_frames for key, value in losses.items()}
215
216        core_loss = self.dice_weight * losses["loss_dice"] + self.iou_weight * losses["loss_iou"]
217        if self.use_focal_loss:
218            core_loss = core_loss + self.focal_weight * losses["loss_focal"]
219        if self.use_object_score_loss:
220            core_loss = core_loss + self.object_score_weight * losses["loss_object_score"]
221
222        losses[CORE_LOSS_KEY] = core_loss
223        return losses

Compute the loss over a batch of per-frame SAM2 outputs.

Arguments:
  • outs_batch: List of per-frame output dicts from SAM2Train.
  • targets_batch: Target instance masks of shape (T, N, H, W).
Returns:

Dict with the per-component losses and the combined loss under "core_loss".

class CustomSAM2Metric(torch.nn.modules.module.Module):
226class CustomSAM2Metric(nn.Module):
227    """Best-mask Dice metric for SAM2 interactive training, mirroring micro_sam's v1 SamTrainer.
228
229    Consumes SAM2Train's per-frame output dicts and scores only the initial (step-0)
230    prompt response - a single forward like v1's validation, which does not iterate over
231    correction steps. The later correction steps are oracle-driven toward the ground truth
232    and would inflate the score, so they are excluded. The oracle best mask candidate per
233    object (smallest Dice loss) is used.
234
235    The Dice loss is computed with :class:`torch_em.loss.DiceLoss` (the object axis placed
236    on the channel axis, ``reduce_channel=None``) so the values match v1's metric exactly.
237    Returns the mean Dice loss over present objects and frames (a [0, 1] value, lower is
238    better, like the metric returned by v1's SamTrainer). Report ``1 - value`` as the Dice
239    score.
240    """
241
242    def __init__(self):
243        super().__init__()
244        self.dice_loss = DiceLoss(reduce_channel=None)
245        self.init_kwargs = {}
246
247    def forward(self, outs_batch, targets_batch):
248        dice_sum = 0.0
249        dice_count = 0.0
250        for outputs, targets in zip(outs_batch, targets_batch):
251            target_masks = targets.unsqueeze(1).float()  # (N, 1, H, W)
252            probs = outputs["multistep_pred_multimasks_high_res"][0].sigmoid().float()  # step 0: (N, M, H, W)
253
254            # Per-object Dice loss for each mask candidate, with the object axis as the
255            # channel axis (matching v1's DiceLoss(reduce_channel=None) usage).
256            target = target_masks.swapaxes(0, 1)  # (1, N, H, W)
257            dice = torch.stack([
258                self.dice_loss(probs[:, i:i + 1].swapaxes(0, 1), target) for i in range(probs.shape[1])
259            ])  # (M, N)
260            best_dice = dice.min(dim=0).values  # (N,) oracle best of M candidates
261
262            # Only score objects that are present in this frame.
263            target_obj = (target_masks[:, 0].flatten(1) > 0).any(-1).float()  # (N,)
264            dice_sum = dice_sum + (best_dice * target_obj).sum()
265            dice_count = dice_count + target_obj.sum()
266
267        if torch.is_tensor(dice_count):
268            return dice_sum / dice_count.clamp(min=1.0)
269        return torch.zeros((), device=targets_batch.device)

Best-mask Dice metric for SAM2 interactive training, mirroring micro_sam's v1 SamTrainer.

Consumes SAM2Train's per-frame output dicts and scores only the initial (step-0) prompt response - a single forward like v1's validation, which does not iterate over correction steps. The later correction steps are oracle-driven toward the ground truth and would inflate the score, so they are excluded. The oracle best mask candidate per object (smallest Dice loss) is used.

The Dice loss is computed with torch_em.loss.DiceLoss (the object axis placed on the channel axis, reduce_channel=None) so the values match v1's metric exactly. Returns the mean Dice loss over present objects and frames (a [0, 1] value, lower is better, like the metric returned by v1's SamTrainer). Report 1 - value as the Dice score.

CustomSAM2Metric()
242    def __init__(self):
243        super().__init__()
244        self.dice_loss = DiceLoss(reduce_channel=None)
245        self.init_kwargs = {}

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

dice_loss
init_kwargs
def forward(self, outs_batch, targets_batch):
247    def forward(self, outs_batch, targets_batch):
248        dice_sum = 0.0
249        dice_count = 0.0
250        for outputs, targets in zip(outs_batch, targets_batch):
251            target_masks = targets.unsqueeze(1).float()  # (N, 1, H, W)
252            probs = outputs["multistep_pred_multimasks_high_res"][0].sigmoid().float()  # step 0: (N, M, H, W)
253
254            # Per-object Dice loss for each mask candidate, with the object axis as the
255            # channel axis (matching v1's DiceLoss(reduce_channel=None) usage).
256            target = target_masks.swapaxes(0, 1)  # (1, N, H, W)
257            dice = torch.stack([
258                self.dice_loss(probs[:, i:i + 1].swapaxes(0, 1), target) for i in range(probs.shape[1])
259            ])  # (M, N)
260            best_dice = dice.min(dim=0).values  # (N,) oracle best of M candidates
261
262            # Only score objects that are present in this frame.
263            target_obj = (target_masks[:, 0].flatten(1) > 0).any(-1).float()  # (N,)
264            dice_sum = dice_sum + (best_dice * target_obj).sum()
265            dice_count = dice_count + target_obj.sum()
266
267        if torch.is_tensor(dice_count):
268            return dice_sum / dice_count.clamp(min=1.0)
269        return torch.zeros((), device=targets_batch.device)

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.