micro_sam.v2.training.util

  1import os
  2import functools
  3from typing import Callable, Dict, List, Optional, Union
  4
  5import torch
  6
  7from micro_sam.util import get_device
  8from micro_sam.v2.util import CFG_PATHS, FINETUNED_MODELS, _get_checkpoint, _download_finetuned_sam2_model
  9
 10
 11def check_start_peft(peft_kwargs: Optional[Dict], start_peft_config: Optional[Dict]) -> None:
 12    """Check that the PEFT settings of a training match the PEFT layers of its start weights.
 13
 14    Args:
 15        peft_kwargs: The PEFT settings of the training, or None.
 16        start_peft_config: The serialized PEFT settings of the start weights, or None.
 17
 18    Raises:
 19        ValueError: If both are given and they are not the same.
 20    """
 21    from micro_sam.models.peft import serialize_peft_kwargs
 22
 23    if not peft_kwargs or start_peft_config is None:
 24        return
 25    requested = {k: v for k, v in serialize_peft_kwargs(peft_kwargs).items() if k != "quantize"}
 26    if requested != start_peft_config:
 27        raise ValueError(
 28            f"The start weights have PEFT layers with {start_peft_config}, but the training uses {requested}. "
 29            "Pass the same 'peft_kwargs', or none to use the PEFT settings of the start weights."
 30        )
 31
 32
 33def read_start_weights(model_type: str, checkpoint_path: Union[str, os.PathLike]):
 34    """Read the SAM2 weights to start a training from.
 35
 36    The function accepts all checkpoints that `micro_sam.v2.util.get_sam2_model` accepts: the SAM2 and registry
 37    files, the checkpoints of a micro-sam2 training (also from DDP or a compiled model), and a decoder file,
 38    whose image encoder is used.
 39
 40    Args:
 41        model_type: The SAM2 model. The backbone of the checkpoint replaces the backbone of this name.
 42        checkpoint_path: The checkpoint.
 43
 44    Returns:
 45        The weights of the SAM2 model.
 46        The model type, with the backbone of the checkpoint.
 47        The serialized PEFT settings of the weights, or None for weights without PEFT layers.
 48    """
 49    from micro_sam.v2.util import get_sam2_model
 50
 51    model = get_sam2_model(model_type=model_type, device="cpu", checkpoint_path=checkpoint_path)
 52    return model.state_dict(), model.model_type, getattr(model, "peft_config", None)
 53
 54
 55@functools.lru_cache(maxsize=1)
 56def sam2_train_class():
 57    """Build the SAM2Train subclass that micro_sam uses for training.
 58
 59    The function builds the class once. It imports the SAM2 training package, which exists only in
 60    training environments.
 61    """
 62    from training.model.sam2 import SAM2Train
 63
 64    class MicroSAM2Train(SAM2Train):
 65        """SAM2Train with optional bidirectional 3D propagation.
 66
 67        With ``bidirectional`` set, each 3D training step samples a random start frame. The model
 68        propagates forward from the start frame to the last frame. Then it propagates backward from the
 69        frame before the start to the first frame, with ``track_in_reverse=True``, and reads the memory
 70        of the forward pass. It samples correction clicks for both directions. 2D inputs (T=1) and eval
 71        use the standard SAM2Train pass.
 72        """
 73
 74        bidirectional = False
 75
 76        def forward(self, input):
 77            if not (self.bidirectional and self.training and input.num_frames > 1):
 78                return super().forward(input)
 79            backbone_out = self.forward_image(input.flat_img_batch)
 80            # Clamp so there are always enough forward frames for num_init_cond_frames.
 81            # prepare_prompt_inputs samples (num_init_cond_frames - 1) additional cond
 82            # frames from range(start + 1, T), which is empty if start >= T - 1 when
 83            # num_init_cond_frames > 1.
 84            max_start = max(0, input.num_frames - self.num_init_cond_frames_for_train)
 85            start_frame_idx = int(self.rng.integers(0, max_start + 1))
 86            backbone_out = self.prepare_prompt_inputs(backbone_out, input, start_frame_idx)
 87            return self._forward_bidirectional(backbone_out, input, start_frame_idx)
 88
 89        def _forward_bidirectional(self, backbone_out, input, start_frame_idx):
 90            img_feats_already_computed = backbone_out["backbone_fpn"] is not None
 91            feat_sizes = None
 92            if img_feats_already_computed:
 93                _, vision_feats, vision_pos_embeds, feat_sizes = self._prepare_backbone_features(backbone_out)
 94
 95            num_frames = backbone_out["num_frames"]
 96            init_cond_frames = backbone_out["init_cond_frames"]
 97            forward_order = init_cond_frames + backbone_out["frames_not_in_init_cond"]
 98            backward_order = list(range(start_frame_idx - 1, -1, -1))
 99
100            # Extend correction frames symmetrically to backward frames.
101            # Only when use_pt_input=True: when False, prepare_prompt_inputs sets
102            # frames_to_add_correction_pt=[] (no corrections in mask-input mode),
103            # so backward frames must follow the same rule.
104            frames_to_add_correction_pt = list(backbone_out["frames_to_add_correction_pt"])
105            if backbone_out["use_pt_input"] and backward_order and self.num_frames_to_correct_for_train > 0:
106                n_back = min(self.num_frames_to_correct_for_train, len(backward_order))
107                if self.rand_frames_to_correct_for_train and n_back > 1:
108                    n_back = int(self.rng.integers(1, n_back, endpoint=True))
109                back_correct = list(self.rng.choice(backward_order, n_back, replace=False))
110                frames_to_add_correction_pt = frames_to_add_correction_pt + back_correct
111
112            output_dict = {"cond_frame_outputs": {}, "non_cond_frame_outputs": {}}
113
114            for stage_id in forward_order:
115                img_ids = input.flat_obj_to_img_idx[stage_id]
116                if img_feats_already_computed:
117                    cvf = [x[:, img_ids] for x in vision_feats]
118                    cvpe = [x[:, img_ids] for x in vision_pos_embeds]
119                else:
120                    _, cvf, cvpe, feat_sizes = self._prepare_backbone_features_per_frame(
121                        input.flat_img_batch, img_ids
122                    )
123                current_out = self.track_step(
124                    frame_idx=stage_id,
125                    is_init_cond_frame=stage_id in init_cond_frames,
126                    current_vision_feats=cvf,
127                    current_vision_pos_embeds=cvpe,
128                    feat_sizes=feat_sizes,
129                    point_inputs=backbone_out["point_inputs_per_frame"].get(stage_id, None),
130                    mask_inputs=backbone_out["mask_inputs_per_frame"].get(stage_id, None),
131                    gt_masks=backbone_out["gt_masks_per_frame"].get(stage_id, None),
132                    frames_to_add_correction_pt=frames_to_add_correction_pt,
133                    output_dict=output_dict,
134                    num_frames=num_frames,
135                    track_in_reverse=False,
136                )
137                add_as_cond = stage_id in init_cond_frames or (
138                    self.add_all_frames_to_correct_as_cond and stage_id in frames_to_add_correction_pt
139                )
140                if add_as_cond:
141                    output_dict["cond_frame_outputs"][stage_id] = current_out
142                else:
143                    output_dict["non_cond_frame_outputs"][stage_id] = current_out
144
145            for stage_id in backward_order:
146                img_ids = input.flat_obj_to_img_idx[stage_id]
147                if img_feats_already_computed:
148                    cvf = [x[:, img_ids] for x in vision_feats]
149                    cvpe = [x[:, img_ids] for x in vision_pos_embeds]
150                else:
151                    _, cvf, cvpe, feat_sizes = self._prepare_backbone_features_per_frame(
152                        input.flat_img_batch, img_ids
153                    )
154                current_out = self.track_step(
155                    frame_idx=stage_id,
156                    is_init_cond_frame=False,
157                    current_vision_feats=cvf,
158                    current_vision_pos_embeds=cvpe,
159                    feat_sizes=feat_sizes,
160                    point_inputs=None,
161                    mask_inputs=None,
162                    gt_masks=backbone_out["gt_masks_per_frame"].get(stage_id, None),
163                    frames_to_add_correction_pt=frames_to_add_correction_pt,
164                    output_dict=output_dict,
165                    num_frames=num_frames,
166                    track_in_reverse=True,
167                )
168                add_as_cond = (
169                    self.add_all_frames_to_correct_as_cond and stage_id in frames_to_add_correction_pt
170                )
171                if add_as_cond:
172                    output_dict["cond_frame_outputs"][stage_id] = current_out
173                else:
174                    output_dict["non_cond_frame_outputs"][stage_id] = current_out
175
176            all_frame_outputs = {}
177            all_frame_outputs.update(output_dict["cond_frame_outputs"])
178            all_frame_outputs.update(output_dict["non_cond_frame_outputs"])
179            all_frame_outputs = [all_frame_outputs[t] for t in range(num_frames)]
180            all_frame_outputs = [{k: v for k, v in d.items() if k != "obj_ptr"} for d in all_frame_outputs]
181            return all_frame_outputs
182
183    return MicroSAM2Train
184
185
186def get_sam2_train_model(
187    model_type: str = "hvit_t",
188    device: Optional[Union[str, torch.device]] = None,
189    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
190    freeze: Optional[List[str]] = None,
191    peft_kwargs: Optional[Dict] = None,
192    prob_to_use_pt_input: float = 0.5,
193    prob_to_use_box_input: float = 0.5,
194    num_frames_to_correct: int = 1,
195    rand_frames_to_correct: bool = True,
196    prob_to_sample_from_gt: float = 0.1,
197    add_all_frames_to_correct_as_cond: bool = True,
198    num_correction_pt_per_frame: int = 7,
199    num_init_cond_frames_for_train: int = 1,
200    prob_to_use_pt_input_for_eval: Optional[float] = None,
201    prob_to_use_box_input_for_eval: Optional[float] = None,
202    num_frames_to_correct_for_eval: Optional[int] = None,
203    num_init_cond_frames_for_eval: Optional[int] = None,
204    bidirectional: bool = False,
205) -> torch.nn.Module:
206    """Build a SAM2Train model for interactive segmentation training.
207
208    SAM2Train uses SAM2's native prompting strategy (point/box/mask inputs sampled
209    from GT, iterative correction on error regions) and supports both 2D (T=1) and
210    3D (T=Z, video) batches in a single training run.
211
212    Args:
213        model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
214        device: Target device. Auto-selects if None.
215        checkpoint_path: The checkpoint to start from, see `read_start_weights`. By default the weights of
216            `model_type`. The backbone of the checkpoint replaces the backbone of `model_type`.
217        freeze: Component name prefixes to freeze (e.g. ["image_encoder"]).
218        peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method.
219        prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation).
220        prob_to_use_box_input: Conditional probability of using a box instead of a click.
221        num_frames_to_correct: Max number of frames per volume that receive iterative
222            correction clicks. Set to the number of z-slices to correct all frames.
223        rand_frames_to_correct: If True, randomly sample 1..num_frames_to_correct frames
224            to correct per step (more robust than always correcting the maximum).
225        prob_to_sample_from_gt: Probability of sampling a correction click from the GT
226            mask instead of the error region - reduces overfitting to error patterns.
227        add_all_frames_to_correct_as_cond: If True, any frame that receives a correction
228            click is also added as a conditioning frame for memory propagation.
229        num_correction_pt_per_frame: Number of correction clicks sampled per frame per
230            correction round. SAM2 default is 7.
231        num_init_cond_frames_for_train: Number of initial conditioning frames (frames that
232            receive the first prompt before any correction round). SAM2 default is 1;
233            the MOSE finetune config uses 2.
234        prob_to_use_pt_input_for_eval: Probability of using point/box prompts during validation.
235            Defaults to prob_to_use_pt_input, so validation measures the task that was trained.
236            SAM2's own default is 0.0, which validates GT-mask propagation instead.
237        prob_to_use_box_input_for_eval: Conditional probability of a box during validation.
238            Defaults to prob_to_use_box_input.
239        num_frames_to_correct_for_eval: Frames receiving correction clicks during validation.
240            Defaults to num_frames_to_correct.
241        num_init_cond_frames_for_eval: Initial conditioning frames during validation.
242            Defaults to num_init_cond_frames_for_train.
243        bidirectional: If True, replace the forward pass with bidirectional propagation:
244            a random z-slice is chosen as the start frame each step, memory is propagated
245            both forward (to higher z) and backward (to lower z, with track_in_reverse=True),
246            and correction clicks are sampled for frames in both directions.
247
248    Returns:
249        SAM2Train model on the target device in train mode.
250    """
251    from sam2.build_sam import build_sam2
252
253    device = get_device(device)
254    start_state, start_peft_config = None, None
255    if checkpoint_path is None:
256        if model_type in FINETUNED_MODELS:
257            checkpoint_path, _, _ = _download_finetuned_sam2_model(model_type)
258        else:
259            checkpoint_path = _get_checkpoint(model_type=model_type)
260    else:
261        # SAM2 reads only its own format, so read the weights here and load them after the model is built.
262        start_state, model_type, start_peft_config = read_start_weights(model_type, checkpoint_path)
263        check_start_peft(peft_kwargs, start_peft_config)
264        checkpoint_path = None
265
266    model_cfg = CFG_PATHS[model_type[:6]]
267
268    # SAM2's eval defaults propagate a GT mask instead of prompting, so mirror the training
269    # configuration and validation scores the task actually being trained.
270    if prob_to_use_pt_input_for_eval is None:
271        prob_to_use_pt_input_for_eval = prob_to_use_pt_input
272    if prob_to_use_box_input_for_eval is None:
273        prob_to_use_box_input_for_eval = prob_to_use_box_input
274    if num_frames_to_correct_for_eval is None:
275        num_frames_to_correct_for_eval = num_frames_to_correct
276    if num_init_cond_frames_for_eval is None:
277        num_init_cond_frames_for_eval = num_init_cond_frames_for_train
278
279    model = build_sam2(
280        config_file=model_cfg,
281        ckpt_path=None if checkpoint_path is None else str(checkpoint_path),
282        device=str(device),
283        mode="train",
284        hydra_overrides_extra=[
285            "++model._target_=training.model.sam2.SAM2Train",
286            f"++model.prob_to_use_pt_input_for_train={prob_to_use_pt_input}",
287            f"++model.prob_to_use_box_input_for_train={prob_to_use_box_input}",
288            f"++model.num_frames_to_correct_for_train={max(num_frames_to_correct, num_init_cond_frames_for_train)}",
289            f"++model.rand_frames_to_correct_for_train={rand_frames_to_correct}",
290            f"++model.prob_to_sample_from_gt_for_train={prob_to_sample_from_gt}",
291            f"++model.add_all_frames_to_correct_as_cond={add_all_frames_to_correct_as_cond}",
292            f"++model.num_correction_pt_per_frame={num_correction_pt_per_frame}",
293            f"++model.num_init_cond_frames_for_train={num_init_cond_frames_for_train}",
294            f"++model.prob_to_use_pt_input_for_eval={prob_to_use_pt_input_for_eval}",
295            f"++model.prob_to_use_box_input_for_eval={prob_to_use_box_input_for_eval}",
296            "++model.num_frames_to_correct_for_eval="
297            f"{max(num_frames_to_correct_for_eval, num_init_cond_frames_for_eval)}",
298            f"++model.num_init_cond_frames_for_eval={num_init_cond_frames_for_eval}",
299            # Deterministic eval sampling, so the metric is comparable across epochs.
300            "++model.rand_frames_to_correct_for_eval=False",
301            "++model.rand_init_cond_frames_for_eval=False",
302            # SAM2's default eval sampling ('center') runs two OpenCV distance transforms on the 1024x1024 error
303            # masks of every object and correction click on the CPU, which made validation ~9x slower per batch
304            # than training. Sample the correction clicks uniformly from the error regions as in training.
305            "++model.pt_sampling_for_eval=uniform",
306        ],
307        apply_postprocessing=False,
308    )
309
310    if start_peft_config is not None:
311        # The start weights hold PEFT layers, so add the same layers before the weights are loaded.
312        from micro_sam.v2.models.peft_sam2 import PEFT_MODULES, PEFT_Sam2
313        from micro_sam.models.peft import deserialize_peft_kwargs
314
315        model = PEFT_Sam2(model, **deserialize_peft_kwargs(start_peft_config, PEFT_MODULES)).sam.to(device)
316        model.load_state_dict(start_state)
317        model.peft_config = start_peft_config
318    else:
319        if start_state is not None:
320            model.load_state_dict(start_state)
321        if peft_kwargs:
322            from micro_sam.v2.models.peft_sam2 import PEFT_Sam2
323            from micro_sam.models.peft import serialize_peft_kwargs
324
325            model = PEFT_Sam2(model, **peft_kwargs).sam.to(device)
326            model.peft_config = serialize_peft_kwargs(peft_kwargs)
327
328    if freeze is not None:
329        components = [freeze] if isinstance(freeze, str) else freeze
330        if peft_kwargs and "image_encoder" in components:
331            raise ValueError("You cannot use PEFT and freeze the image encoder at the same time.")
332        for name, param in model.named_parameters():
333            if any(name.startswith(c) for c in components):
334                param.requires_grad = False
335
336    model.__class__ = sam2_train_class()
337    model.bidirectional = bidirectional
338
339    return model
340
341
342class ConvertToSam2VideoBatch:
343    """Convert torch-em (x, y) batches to BatchedVideoDatapoint for SAM2Train.
344
345    2D inputs (x: B,C,H,W  /  y: B,1,H,W): each image becomes a 1-frame video (T=1).
346    3D inputs (x: B,C,Z,H,W  /  y: B,1,Z,H,W): Z-slices become video frames (T=Z).
347
348    Images are converted to SAM2 input format:
349    - [0, 1] range -> ImageNet-normalized -> resized to 1024x1024
350    - Single-channel inputs are broadcast to 3 channels.
351
352    Masks are resized to 1024×1024 (required so that get_next_point returns
353    coordinates in the model's input coordinate space).
354
355    Args:
356        max_num_objects: Maximum number of objects to sample per image/volume.
357            Excess objects are randomly subsampled.
358        largest_first: Fill half the object slots with the largest instances and the rest
359            at random, instead of sampling all of them at random.
360        augmentor: Optional augmentation, called as ``augmentor(x, y)`` and returning the
361            augmented pair. Must apply spatial transforms to both, or the masks stop matching
362            the image. See :class:`~micro_sam.v2.transforms.raw.VideoAugment`.
363    """
364
365    _PIXEL_MEAN = [0.485, 0.456, 0.406]
366    _PIXEL_STD = [0.229, 0.224, 0.225]
367    _SAM2_SIZE = 1024
368
369    def __init__(self, max_num_objects: int = 20, largest_first: bool = False, augmentor: Optional[Callable] = None):
370        self.max_num_objects = max_num_objects
371        self.largest_first = largest_first
372        self.augmentor = augmentor
373        self.init_kwargs = {"max_num_objects": max_num_objects, "largest_first": largest_first}
374        # Built once instead of per frame.
375        self.pixel_mean = torch.tensor(self._PIXEL_MEAN).view(1, 3, 1, 1)
376        self.pixel_std = torch.tensor(self._PIXEL_STD).view(1, 3, 1, 1)
377
378    def _to_sam2_size(self, x: torch.Tensor, mode: str) -> torch.Tensor:
379        """Resize longest side to SAM2_SIZE then zero-pad to square.
380
381        Padding is applied in image space to the right and bottom edges.
382        """
383        from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_tensor
384        return resize_longest_side_and_pad_tensor(x, self._SAM2_SIZE, mode=mode)[0]
385
386    def _to_sam2_image(self, x: torch.Tensor) -> torch.Tensor:
387        """(B,C,H,W) float [0,1] -> (B,3,1024,1024) ImageNet-normalized."""
388        x = x.float()
389        if x.shape[1] == 1:
390            x = x.expand(-1, 3, -1, -1)
391        # Pad before normalization to keep padding black in image space.
392        x = self._to_sam2_size(x, mode="bilinear")
393        mean = self.pixel_mean.to(device=x.device, dtype=x.dtype)
394        std = self.pixel_std.to(device=x.device, dtype=x.dtype)
395        return (x - mean) / std
396
397    def _resize_masks(self, masks: torch.Tensor) -> torch.Tensor:
398        """(O,H,W) bool -> (O,1024,1024) bool, aspect-ratio preserving + padded."""
399        m = masks.float().unsqueeze(1)  # (O,1,H,W)
400        m = self._to_sam2_size(m, mode="nearest")
401        return m.squeeze(1).bool()
402
403    def _sample_obj_ids(self, label_2d: torch.Tensor) -> torch.Tensor:
404        """Return up to max_num_objects non-zero unique IDs from a 2-D label map."""
405        ids = torch.unique(label_2d)
406        ids = ids[ids > 0]
407        if len(ids) <= self.max_num_objects:
408            return ids
409        if not self.largest_first:
410            perm = torch.randperm(len(ids), device=ids.device)[:self.max_num_objects]
411            return ids[perm]
412        # Mixed: first n//2 by descending size, remaining n - n//2 at random.
413        n_largest = self.max_num_objects // 2
414        n_random = self.max_num_objects - n_largest
415        counts = torch.bincount(label_2d.flatten().long(), minlength=int(ids.max().item()) + 1)
416        sorted_idx = torch.argsort(counts[ids.long()], descending=True)
417        largest_ids = ids[sorted_idx[:n_largest]]
418        perm = torch.randperm(len(ids) - n_largest, device=ids.device)[:n_random]
419        random_ids = ids[sorted_idx[n_largest:]][perm]
420        return torch.cat([largest_ids, random_ids])
421
422    def __call__(self, x: torch.Tensor, y: torch.Tensor):
423        """
424        Args:
425            x: Images - (B,C,H,W) for 2D or (B,C,Z,H,W) for 3D, in [0, 1].
426            y: Instance labels - (B,1,H,W) or (B,1,Z,H,W) with integer IDs.
427
428        Returns:
429            BatchedVideoDatapoint compatible with SAM2Train.forward().
430        """
431        from training.utils.data_utils import BatchedVideoDatapoint, BatchedVideoMetaData
432
433        if self.augmentor is not None:
434            x, y = self.augmentor(x, y)
435
436        is_3d = (x.ndim == 5)
437        B = x.shape[0]
438        if is_3d:
439            _, _, T, H, W = x.shape
440        else:
441            _, _, H, W = x.shape
442            T = 1
443
444        # Resized per frame: x[:, :, t] is a view, whereas flattening to one frame batch needs
445        # a permute+copy for no gain, since the resize cost is the same either way.
446        if is_3d:
447            img_batch = torch.stack([self._to_sam2_image(x[:, :, t]) for t in range(T)])
448        else:
449            img_batch = self._to_sam2_image(x).unsqueeze(0)
450
451        y = y.squeeze(1)  # (B,H,W) or (B,Z,H,W)
452
453        # For 3D: sample from the union of IDs across all z-slices so that it includes objects
454        # present in any frame (frame 0 alone can be empty at patch boundaries).
455        obj_ids_per_b = [
456            self._sample_obj_ids(y[b].flatten() if is_3d else y[b]) for b in range(B)
457        ]
458        # The sampled IDs do not depend on the time step, so emptiness is the same for all of them.
459        n_objects = sum(len(ids) for ids in obj_ids_per_b)
460        if n_objects == 0:
461            raise RuntimeError(
462                "ConvertToSam2VideoBatch: no objects found in batch. "
463                "Use MinInstanceSampler to ensure each sample has objects."
464            )
465
466        # One broadcast comparison per frame instead of stacking objects one at a time. The
467        # 1024x1024 resize dominates regardless of how the masks are batched into it.
468        step_masks = []
469        for t in range(T):
470            raw = [
471                (y[b, t] if is_3d else y[b]).unsqueeze(0) == obj_ids_per_b[b].view(-1, 1, 1)
472                for b in range(B) if len(obj_ids_per_b[b]) > 0
473            ]
474            step_masks.append(self._resize_masks(torch.cat(raw)))  # (O,1024,1024)
475
476        # Per-time-step metadata (same structure as collate_fn in data_utils.py). The object
477        # slots are identical for every frame, so the flat lists are built once.
478        batch_index = [b for b in range(B) for _ in range(len(obj_ids_per_b[b]))]
479        object_ids = [int(oid) for b in range(B) for oid in obj_ids_per_b[b].tolist()]
480        step_obj2frame, step_identifier = [], []
481        for t in range(T):
482            step_obj2frame.append(torch.tensor([[t, b] for b in batch_index], dtype=torch.int))
483            step_identifier.append(
484                torch.tensor([[b, oid, t] for b, oid in zip(batch_index, object_ids)], dtype=torch.long)
485            )
486        orig_size = torch.tensor([H, W], dtype=torch.long).expand(T, n_objects, 2).contiguous()
487
488        return BatchedVideoDatapoint(
489            img_batch=img_batch,
490            obj_to_frame_idx=torch.stack(step_obj2frame),  # (T,O,2)
491            masks=torch.stack(step_masks),  # (T,O,1024,1024)
492            metadata=BatchedVideoMetaData(
493                unique_objects_identifier=torch.stack(step_identifier),
494                frame_orig_size=orig_size,
495            ),
496            dict_key="torch_em",
497            batch_size=[T],
498        )
499
500
501class MixedLoader:
502    """Round-robin DataLoader wrapper for joint 2D + 3D training.
503
504    Each iteration yields one batch from the first loader, then one from the
505    second, cycling until the shorter one is exhausted. This ensures that every
506    training step sees both 2D and 3D data.
507
508    Args:
509        loader_2d: DataLoader yielding (B,C,H,W) batches.
510        loader_3d: DataLoader yielding (B,C,Z,H,W) batches.
511    """
512
513    def __init__(self, loader_2d, loader_3d):
514        self.loader_2d = loader_2d
515        self.loader_3d = loader_3d
516        self.shuffle = getattr(loader_2d, "shuffle", True)
517
518    def __len__(self):
519        return len(self.loader_2d) + len(self.loader_3d)
520
521    def __iter__(self):
522        iter_2d = iter(self.loader_2d)
523        iter_3d = iter(self.loader_3d)
524        done_2d = done_3d = False
525        while not (done_2d and done_3d):
526            if not done_2d:
527                try:
528                    yield next(iter_2d)
529                except StopIteration:
530                    done_2d = True
531            if not done_3d:
532                try:
533                    yield next(iter_3d)
534                except StopIteration:
535                    done_3d = True
def check_start_peft(peft_kwargs: Optional[Dict], start_peft_config: Optional[Dict]) -> None:
12def check_start_peft(peft_kwargs: Optional[Dict], start_peft_config: Optional[Dict]) -> None:
13    """Check that the PEFT settings of a training match the PEFT layers of its start weights.
14
15    Args:
16        peft_kwargs: The PEFT settings of the training, or None.
17        start_peft_config: The serialized PEFT settings of the start weights, or None.
18
19    Raises:
20        ValueError: If both are given and they are not the same.
21    """
22    from micro_sam.models.peft import serialize_peft_kwargs
23
24    if not peft_kwargs or start_peft_config is None:
25        return
26    requested = {k: v for k, v in serialize_peft_kwargs(peft_kwargs).items() if k != "quantize"}
27    if requested != start_peft_config:
28        raise ValueError(
29            f"The start weights have PEFT layers with {start_peft_config}, but the training uses {requested}. "
30            "Pass the same 'peft_kwargs', or none to use the PEFT settings of the start weights."
31        )

Check that the PEFT settings of a training match the PEFT layers of its start weights.

Arguments:
  • peft_kwargs: The PEFT settings of the training, or None.
  • start_peft_config: The serialized PEFT settings of the start weights, or None.
Raises:
  • ValueError: If both are given and they are not the same.
def read_start_weights(model_type: str, checkpoint_path: Union[str, os.PathLike]):
34def read_start_weights(model_type: str, checkpoint_path: Union[str, os.PathLike]):
35    """Read the SAM2 weights to start a training from.
36
37    The function accepts all checkpoints that `micro_sam.v2.util.get_sam2_model` accepts: the SAM2 and registry
38    files, the checkpoints of a micro-sam2 training (also from DDP or a compiled model), and a decoder file,
39    whose image encoder is used.
40
41    Args:
42        model_type: The SAM2 model. The backbone of the checkpoint replaces the backbone of this name.
43        checkpoint_path: The checkpoint.
44
45    Returns:
46        The weights of the SAM2 model.
47        The model type, with the backbone of the checkpoint.
48        The serialized PEFT settings of the weights, or None for weights without PEFT layers.
49    """
50    from micro_sam.v2.util import get_sam2_model
51
52    model = get_sam2_model(model_type=model_type, device="cpu", checkpoint_path=checkpoint_path)
53    return model.state_dict(), model.model_type, getattr(model, "peft_config", None)

Read the SAM2 weights to start a training from.

The function accepts all checkpoints that micro_sam.v2.util.get_sam2_model accepts: the SAM2 and registry files, the checkpoints of a micro-sam2 training (also from DDP or a compiled model), and a decoder file, whose image encoder is used.

Arguments:
  • model_type: The SAM2 model. The backbone of the checkpoint replaces the backbone of this name.
  • checkpoint_path: The checkpoint.
Returns:

The weights of the SAM2 model. The model type, with the backbone of the checkpoint. The serialized PEFT settings of the weights, or None for weights without PEFT layers.

@functools.lru_cache(maxsize=1)
def sam2_train_class():
 56@functools.lru_cache(maxsize=1)
 57def sam2_train_class():
 58    """Build the SAM2Train subclass that micro_sam uses for training.
 59
 60    The function builds the class once. It imports the SAM2 training package, which exists only in
 61    training environments.
 62    """
 63    from training.model.sam2 import SAM2Train
 64
 65    class MicroSAM2Train(SAM2Train):
 66        """SAM2Train with optional bidirectional 3D propagation.
 67
 68        With ``bidirectional`` set, each 3D training step samples a random start frame. The model
 69        propagates forward from the start frame to the last frame. Then it propagates backward from the
 70        frame before the start to the first frame, with ``track_in_reverse=True``, and reads the memory
 71        of the forward pass. It samples correction clicks for both directions. 2D inputs (T=1) and eval
 72        use the standard SAM2Train pass.
 73        """
 74
 75        bidirectional = False
 76
 77        def forward(self, input):
 78            if not (self.bidirectional and self.training and input.num_frames > 1):
 79                return super().forward(input)
 80            backbone_out = self.forward_image(input.flat_img_batch)
 81            # Clamp so there are always enough forward frames for num_init_cond_frames.
 82            # prepare_prompt_inputs samples (num_init_cond_frames - 1) additional cond
 83            # frames from range(start + 1, T), which is empty if start >= T - 1 when
 84            # num_init_cond_frames > 1.
 85            max_start = max(0, input.num_frames - self.num_init_cond_frames_for_train)
 86            start_frame_idx = int(self.rng.integers(0, max_start + 1))
 87            backbone_out = self.prepare_prompt_inputs(backbone_out, input, start_frame_idx)
 88            return self._forward_bidirectional(backbone_out, input, start_frame_idx)
 89
 90        def _forward_bidirectional(self, backbone_out, input, start_frame_idx):
 91            img_feats_already_computed = backbone_out["backbone_fpn"] is not None
 92            feat_sizes = None
 93            if img_feats_already_computed:
 94                _, vision_feats, vision_pos_embeds, feat_sizes = self._prepare_backbone_features(backbone_out)
 95
 96            num_frames = backbone_out["num_frames"]
 97            init_cond_frames = backbone_out["init_cond_frames"]
 98            forward_order = init_cond_frames + backbone_out["frames_not_in_init_cond"]
 99            backward_order = list(range(start_frame_idx - 1, -1, -1))
100
101            # Extend correction frames symmetrically to backward frames.
102            # Only when use_pt_input=True: when False, prepare_prompt_inputs sets
103            # frames_to_add_correction_pt=[] (no corrections in mask-input mode),
104            # so backward frames must follow the same rule.
105            frames_to_add_correction_pt = list(backbone_out["frames_to_add_correction_pt"])
106            if backbone_out["use_pt_input"] and backward_order and self.num_frames_to_correct_for_train > 0:
107                n_back = min(self.num_frames_to_correct_for_train, len(backward_order))
108                if self.rand_frames_to_correct_for_train and n_back > 1:
109                    n_back = int(self.rng.integers(1, n_back, endpoint=True))
110                back_correct = list(self.rng.choice(backward_order, n_back, replace=False))
111                frames_to_add_correction_pt = frames_to_add_correction_pt + back_correct
112
113            output_dict = {"cond_frame_outputs": {}, "non_cond_frame_outputs": {}}
114
115            for stage_id in forward_order:
116                img_ids = input.flat_obj_to_img_idx[stage_id]
117                if img_feats_already_computed:
118                    cvf = [x[:, img_ids] for x in vision_feats]
119                    cvpe = [x[:, img_ids] for x in vision_pos_embeds]
120                else:
121                    _, cvf, cvpe, feat_sizes = self._prepare_backbone_features_per_frame(
122                        input.flat_img_batch, img_ids
123                    )
124                current_out = self.track_step(
125                    frame_idx=stage_id,
126                    is_init_cond_frame=stage_id in init_cond_frames,
127                    current_vision_feats=cvf,
128                    current_vision_pos_embeds=cvpe,
129                    feat_sizes=feat_sizes,
130                    point_inputs=backbone_out["point_inputs_per_frame"].get(stage_id, None),
131                    mask_inputs=backbone_out["mask_inputs_per_frame"].get(stage_id, None),
132                    gt_masks=backbone_out["gt_masks_per_frame"].get(stage_id, None),
133                    frames_to_add_correction_pt=frames_to_add_correction_pt,
134                    output_dict=output_dict,
135                    num_frames=num_frames,
136                    track_in_reverse=False,
137                )
138                add_as_cond = stage_id in init_cond_frames or (
139                    self.add_all_frames_to_correct_as_cond and stage_id in frames_to_add_correction_pt
140                )
141                if add_as_cond:
142                    output_dict["cond_frame_outputs"][stage_id] = current_out
143                else:
144                    output_dict["non_cond_frame_outputs"][stage_id] = current_out
145
146            for stage_id in backward_order:
147                img_ids = input.flat_obj_to_img_idx[stage_id]
148                if img_feats_already_computed:
149                    cvf = [x[:, img_ids] for x in vision_feats]
150                    cvpe = [x[:, img_ids] for x in vision_pos_embeds]
151                else:
152                    _, cvf, cvpe, feat_sizes = self._prepare_backbone_features_per_frame(
153                        input.flat_img_batch, img_ids
154                    )
155                current_out = self.track_step(
156                    frame_idx=stage_id,
157                    is_init_cond_frame=False,
158                    current_vision_feats=cvf,
159                    current_vision_pos_embeds=cvpe,
160                    feat_sizes=feat_sizes,
161                    point_inputs=None,
162                    mask_inputs=None,
163                    gt_masks=backbone_out["gt_masks_per_frame"].get(stage_id, None),
164                    frames_to_add_correction_pt=frames_to_add_correction_pt,
165                    output_dict=output_dict,
166                    num_frames=num_frames,
167                    track_in_reverse=True,
168                )
169                add_as_cond = (
170                    self.add_all_frames_to_correct_as_cond and stage_id in frames_to_add_correction_pt
171                )
172                if add_as_cond:
173                    output_dict["cond_frame_outputs"][stage_id] = current_out
174                else:
175                    output_dict["non_cond_frame_outputs"][stage_id] = current_out
176
177            all_frame_outputs = {}
178            all_frame_outputs.update(output_dict["cond_frame_outputs"])
179            all_frame_outputs.update(output_dict["non_cond_frame_outputs"])
180            all_frame_outputs = [all_frame_outputs[t] for t in range(num_frames)]
181            all_frame_outputs = [{k: v for k, v in d.items() if k != "obj_ptr"} for d in all_frame_outputs]
182            return all_frame_outputs
183
184    return MicroSAM2Train

Build the SAM2Train subclass that micro_sam uses for training.

The function builds the class once. It imports the SAM2 training package, which exists only in training environments.

def get_sam2_train_model( model_type: str = 'hvit_t', device: Union[str, torch.device, NoneType] = None, checkpoint_path: Union[str, os.PathLike, NoneType] = None, freeze: Optional[List[str]] = None, peft_kwargs: Optional[Dict] = None, prob_to_use_pt_input: float = 0.5, prob_to_use_box_input: float = 0.5, num_frames_to_correct: int = 1, rand_frames_to_correct: bool = True, prob_to_sample_from_gt: float = 0.1, add_all_frames_to_correct_as_cond: bool = True, num_correction_pt_per_frame: int = 7, num_init_cond_frames_for_train: int = 1, prob_to_use_pt_input_for_eval: Optional[float] = None, prob_to_use_box_input_for_eval: Optional[float] = None, num_frames_to_correct_for_eval: Optional[int] = None, num_init_cond_frames_for_eval: Optional[int] = None, bidirectional: bool = False) -> torch.nn.modules.module.Module:
187def get_sam2_train_model(
188    model_type: str = "hvit_t",
189    device: Optional[Union[str, torch.device]] = None,
190    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
191    freeze: Optional[List[str]] = None,
192    peft_kwargs: Optional[Dict] = None,
193    prob_to_use_pt_input: float = 0.5,
194    prob_to_use_box_input: float = 0.5,
195    num_frames_to_correct: int = 1,
196    rand_frames_to_correct: bool = True,
197    prob_to_sample_from_gt: float = 0.1,
198    add_all_frames_to_correct_as_cond: bool = True,
199    num_correction_pt_per_frame: int = 7,
200    num_init_cond_frames_for_train: int = 1,
201    prob_to_use_pt_input_for_eval: Optional[float] = None,
202    prob_to_use_box_input_for_eval: Optional[float] = None,
203    num_frames_to_correct_for_eval: Optional[int] = None,
204    num_init_cond_frames_for_eval: Optional[int] = None,
205    bidirectional: bool = False,
206) -> torch.nn.Module:
207    """Build a SAM2Train model for interactive segmentation training.
208
209    SAM2Train uses SAM2's native prompting strategy (point/box/mask inputs sampled
210    from GT, iterative correction on error regions) and supports both 2D (T=1) and
211    3D (T=Z, video) batches in a single training run.
212
213    Args:
214        model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
215        device: Target device. Auto-selects if None.
216        checkpoint_path: The checkpoint to start from, see `read_start_weights`. By default the weights of
217            `model_type`. The backbone of the checkpoint replaces the backbone of `model_type`.
218        freeze: Component name prefixes to freeze (e.g. ["image_encoder"]).
219        peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method.
220        prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation).
221        prob_to_use_box_input: Conditional probability of using a box instead of a click.
222        num_frames_to_correct: Max number of frames per volume that receive iterative
223            correction clicks. Set to the number of z-slices to correct all frames.
224        rand_frames_to_correct: If True, randomly sample 1..num_frames_to_correct frames
225            to correct per step (more robust than always correcting the maximum).
226        prob_to_sample_from_gt: Probability of sampling a correction click from the GT
227            mask instead of the error region - reduces overfitting to error patterns.
228        add_all_frames_to_correct_as_cond: If True, any frame that receives a correction
229            click is also added as a conditioning frame for memory propagation.
230        num_correction_pt_per_frame: Number of correction clicks sampled per frame per
231            correction round. SAM2 default is 7.
232        num_init_cond_frames_for_train: Number of initial conditioning frames (frames that
233            receive the first prompt before any correction round). SAM2 default is 1;
234            the MOSE finetune config uses 2.
235        prob_to_use_pt_input_for_eval: Probability of using point/box prompts during validation.
236            Defaults to prob_to_use_pt_input, so validation measures the task that was trained.
237            SAM2's own default is 0.0, which validates GT-mask propagation instead.
238        prob_to_use_box_input_for_eval: Conditional probability of a box during validation.
239            Defaults to prob_to_use_box_input.
240        num_frames_to_correct_for_eval: Frames receiving correction clicks during validation.
241            Defaults to num_frames_to_correct.
242        num_init_cond_frames_for_eval: Initial conditioning frames during validation.
243            Defaults to num_init_cond_frames_for_train.
244        bidirectional: If True, replace the forward pass with bidirectional propagation:
245            a random z-slice is chosen as the start frame each step, memory is propagated
246            both forward (to higher z) and backward (to lower z, with track_in_reverse=True),
247            and correction clicks are sampled for frames in both directions.
248
249    Returns:
250        SAM2Train model on the target device in train mode.
251    """
252    from sam2.build_sam import build_sam2
253
254    device = get_device(device)
255    start_state, start_peft_config = None, None
256    if checkpoint_path is None:
257        if model_type in FINETUNED_MODELS:
258            checkpoint_path, _, _ = _download_finetuned_sam2_model(model_type)
259        else:
260            checkpoint_path = _get_checkpoint(model_type=model_type)
261    else:
262        # SAM2 reads only its own format, so read the weights here and load them after the model is built.
263        start_state, model_type, start_peft_config = read_start_weights(model_type, checkpoint_path)
264        check_start_peft(peft_kwargs, start_peft_config)
265        checkpoint_path = None
266
267    model_cfg = CFG_PATHS[model_type[:6]]
268
269    # SAM2's eval defaults propagate a GT mask instead of prompting, so mirror the training
270    # configuration and validation scores the task actually being trained.
271    if prob_to_use_pt_input_for_eval is None:
272        prob_to_use_pt_input_for_eval = prob_to_use_pt_input
273    if prob_to_use_box_input_for_eval is None:
274        prob_to_use_box_input_for_eval = prob_to_use_box_input
275    if num_frames_to_correct_for_eval is None:
276        num_frames_to_correct_for_eval = num_frames_to_correct
277    if num_init_cond_frames_for_eval is None:
278        num_init_cond_frames_for_eval = num_init_cond_frames_for_train
279
280    model = build_sam2(
281        config_file=model_cfg,
282        ckpt_path=None if checkpoint_path is None else str(checkpoint_path),
283        device=str(device),
284        mode="train",
285        hydra_overrides_extra=[
286            "++model._target_=training.model.sam2.SAM2Train",
287            f"++model.prob_to_use_pt_input_for_train={prob_to_use_pt_input}",
288            f"++model.prob_to_use_box_input_for_train={prob_to_use_box_input}",
289            f"++model.num_frames_to_correct_for_train={max(num_frames_to_correct, num_init_cond_frames_for_train)}",
290            f"++model.rand_frames_to_correct_for_train={rand_frames_to_correct}",
291            f"++model.prob_to_sample_from_gt_for_train={prob_to_sample_from_gt}",
292            f"++model.add_all_frames_to_correct_as_cond={add_all_frames_to_correct_as_cond}",
293            f"++model.num_correction_pt_per_frame={num_correction_pt_per_frame}",
294            f"++model.num_init_cond_frames_for_train={num_init_cond_frames_for_train}",
295            f"++model.prob_to_use_pt_input_for_eval={prob_to_use_pt_input_for_eval}",
296            f"++model.prob_to_use_box_input_for_eval={prob_to_use_box_input_for_eval}",
297            "++model.num_frames_to_correct_for_eval="
298            f"{max(num_frames_to_correct_for_eval, num_init_cond_frames_for_eval)}",
299            f"++model.num_init_cond_frames_for_eval={num_init_cond_frames_for_eval}",
300            # Deterministic eval sampling, so the metric is comparable across epochs.
301            "++model.rand_frames_to_correct_for_eval=False",
302            "++model.rand_init_cond_frames_for_eval=False",
303            # SAM2's default eval sampling ('center') runs two OpenCV distance transforms on the 1024x1024 error
304            # masks of every object and correction click on the CPU, which made validation ~9x slower per batch
305            # than training. Sample the correction clicks uniformly from the error regions as in training.
306            "++model.pt_sampling_for_eval=uniform",
307        ],
308        apply_postprocessing=False,
309    )
310
311    if start_peft_config is not None:
312        # The start weights hold PEFT layers, so add the same layers before the weights are loaded.
313        from micro_sam.v2.models.peft_sam2 import PEFT_MODULES, PEFT_Sam2
314        from micro_sam.models.peft import deserialize_peft_kwargs
315
316        model = PEFT_Sam2(model, **deserialize_peft_kwargs(start_peft_config, PEFT_MODULES)).sam.to(device)
317        model.load_state_dict(start_state)
318        model.peft_config = start_peft_config
319    else:
320        if start_state is not None:
321            model.load_state_dict(start_state)
322        if peft_kwargs:
323            from micro_sam.v2.models.peft_sam2 import PEFT_Sam2
324            from micro_sam.models.peft import serialize_peft_kwargs
325
326            model = PEFT_Sam2(model, **peft_kwargs).sam.to(device)
327            model.peft_config = serialize_peft_kwargs(peft_kwargs)
328
329    if freeze is not None:
330        components = [freeze] if isinstance(freeze, str) else freeze
331        if peft_kwargs and "image_encoder" in components:
332            raise ValueError("You cannot use PEFT and freeze the image encoder at the same time.")
333        for name, param in model.named_parameters():
334            if any(name.startswith(c) for c in components):
335                param.requires_grad = False
336
337    model.__class__ = sam2_train_class()
338    model.bidirectional = bidirectional
339
340    return model

Build a SAM2Train model for interactive segmentation training.

SAM2Train uses SAM2's native prompting strategy (point/box/mask inputs sampled from GT, iterative correction on error regions) and supports both 2D (T=1) and 3D (T=Z, video) batches in a single training run.

Arguments:
  • model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
  • device: Target device. Auto-selects if None.
  • checkpoint_path: The checkpoint to start from, see read_start_weights. By default the weights of model_type. The backbone of the checkpoint replaces the backbone of model_type.
  • freeze: Component name prefixes to freeze (e.g. ["image_encoder"]).
  • peft_kwargs: The arguments for PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method.
  • prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation).
  • prob_to_use_box_input: Conditional probability of using a box instead of a click.
  • num_frames_to_correct: Max number of frames per volume that receive iterative correction clicks. Set to the number of z-slices to correct all frames.
  • rand_frames_to_correct: If True, randomly sample 1..num_frames_to_correct frames to correct per step (more robust than always correcting the maximum).
  • prob_to_sample_from_gt: Probability of sampling a correction click from the GT mask instead of the error region - reduces overfitting to error patterns.
  • add_all_frames_to_correct_as_cond: If True, any frame that receives a correction click is also added as a conditioning frame for memory propagation.
  • num_correction_pt_per_frame: Number of correction clicks sampled per frame per correction round. SAM2 default is 7.
  • num_init_cond_frames_for_train: Number of initial conditioning frames (frames that receive the first prompt before any correction round). SAM2 default is 1; the MOSE finetune config uses 2.
  • prob_to_use_pt_input_for_eval: Probability of using point/box prompts during validation. Defaults to prob_to_use_pt_input, so validation measures the task that was trained. SAM2's own default is 0.0, which validates GT-mask propagation instead.
  • prob_to_use_box_input_for_eval: Conditional probability of a box during validation. Defaults to prob_to_use_box_input.
  • num_frames_to_correct_for_eval: Frames receiving correction clicks during validation. Defaults to num_frames_to_correct.
  • num_init_cond_frames_for_eval: Initial conditioning frames during validation. Defaults to num_init_cond_frames_for_train.
  • bidirectional: If True, replace the forward pass with bidirectional propagation: a random z-slice is chosen as the start frame each step, memory is propagated both forward (to higher z) and backward (to lower z, with track_in_reverse=True), and correction clicks are sampled for frames in both directions.
Returns:

SAM2Train model on the target device in train mode.

class ConvertToSam2VideoBatch:
343class ConvertToSam2VideoBatch:
344    """Convert torch-em (x, y) batches to BatchedVideoDatapoint for SAM2Train.
345
346    2D inputs (x: B,C,H,W  /  y: B,1,H,W): each image becomes a 1-frame video (T=1).
347    3D inputs (x: B,C,Z,H,W  /  y: B,1,Z,H,W): Z-slices become video frames (T=Z).
348
349    Images are converted to SAM2 input format:
350    - [0, 1] range -> ImageNet-normalized -> resized to 1024x1024
351    - Single-channel inputs are broadcast to 3 channels.
352
353    Masks are resized to 1024×1024 (required so that get_next_point returns
354    coordinates in the model's input coordinate space).
355
356    Args:
357        max_num_objects: Maximum number of objects to sample per image/volume.
358            Excess objects are randomly subsampled.
359        largest_first: Fill half the object slots with the largest instances and the rest
360            at random, instead of sampling all of them at random.
361        augmentor: Optional augmentation, called as ``augmentor(x, y)`` and returning the
362            augmented pair. Must apply spatial transforms to both, or the masks stop matching
363            the image. See :class:`~micro_sam.v2.transforms.raw.VideoAugment`.
364    """
365
366    _PIXEL_MEAN = [0.485, 0.456, 0.406]
367    _PIXEL_STD = [0.229, 0.224, 0.225]
368    _SAM2_SIZE = 1024
369
370    def __init__(self, max_num_objects: int = 20, largest_first: bool = False, augmentor: Optional[Callable] = None):
371        self.max_num_objects = max_num_objects
372        self.largest_first = largest_first
373        self.augmentor = augmentor
374        self.init_kwargs = {"max_num_objects": max_num_objects, "largest_first": largest_first}
375        # Built once instead of per frame.
376        self.pixel_mean = torch.tensor(self._PIXEL_MEAN).view(1, 3, 1, 1)
377        self.pixel_std = torch.tensor(self._PIXEL_STD).view(1, 3, 1, 1)
378
379    def _to_sam2_size(self, x: torch.Tensor, mode: str) -> torch.Tensor:
380        """Resize longest side to SAM2_SIZE then zero-pad to square.
381
382        Padding is applied in image space to the right and bottom edges.
383        """
384        from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_tensor
385        return resize_longest_side_and_pad_tensor(x, self._SAM2_SIZE, mode=mode)[0]
386
387    def _to_sam2_image(self, x: torch.Tensor) -> torch.Tensor:
388        """(B,C,H,W) float [0,1] -> (B,3,1024,1024) ImageNet-normalized."""
389        x = x.float()
390        if x.shape[1] == 1:
391            x = x.expand(-1, 3, -1, -1)
392        # Pad before normalization to keep padding black in image space.
393        x = self._to_sam2_size(x, mode="bilinear")
394        mean = self.pixel_mean.to(device=x.device, dtype=x.dtype)
395        std = self.pixel_std.to(device=x.device, dtype=x.dtype)
396        return (x - mean) / std
397
398    def _resize_masks(self, masks: torch.Tensor) -> torch.Tensor:
399        """(O,H,W) bool -> (O,1024,1024) bool, aspect-ratio preserving + padded."""
400        m = masks.float().unsqueeze(1)  # (O,1,H,W)
401        m = self._to_sam2_size(m, mode="nearest")
402        return m.squeeze(1).bool()
403
404    def _sample_obj_ids(self, label_2d: torch.Tensor) -> torch.Tensor:
405        """Return up to max_num_objects non-zero unique IDs from a 2-D label map."""
406        ids = torch.unique(label_2d)
407        ids = ids[ids > 0]
408        if len(ids) <= self.max_num_objects:
409            return ids
410        if not self.largest_first:
411            perm = torch.randperm(len(ids), device=ids.device)[:self.max_num_objects]
412            return ids[perm]
413        # Mixed: first n//2 by descending size, remaining n - n//2 at random.
414        n_largest = self.max_num_objects // 2
415        n_random = self.max_num_objects - n_largest
416        counts = torch.bincount(label_2d.flatten().long(), minlength=int(ids.max().item()) + 1)
417        sorted_idx = torch.argsort(counts[ids.long()], descending=True)
418        largest_ids = ids[sorted_idx[:n_largest]]
419        perm = torch.randperm(len(ids) - n_largest, device=ids.device)[:n_random]
420        random_ids = ids[sorted_idx[n_largest:]][perm]
421        return torch.cat([largest_ids, random_ids])
422
423    def __call__(self, x: torch.Tensor, y: torch.Tensor):
424        """
425        Args:
426            x: Images - (B,C,H,W) for 2D or (B,C,Z,H,W) for 3D, in [0, 1].
427            y: Instance labels - (B,1,H,W) or (B,1,Z,H,W) with integer IDs.
428
429        Returns:
430            BatchedVideoDatapoint compatible with SAM2Train.forward().
431        """
432        from training.utils.data_utils import BatchedVideoDatapoint, BatchedVideoMetaData
433
434        if self.augmentor is not None:
435            x, y = self.augmentor(x, y)
436
437        is_3d = (x.ndim == 5)
438        B = x.shape[0]
439        if is_3d:
440            _, _, T, H, W = x.shape
441        else:
442            _, _, H, W = x.shape
443            T = 1
444
445        # Resized per frame: x[:, :, t] is a view, whereas flattening to one frame batch needs
446        # a permute+copy for no gain, since the resize cost is the same either way.
447        if is_3d:
448            img_batch = torch.stack([self._to_sam2_image(x[:, :, t]) for t in range(T)])
449        else:
450            img_batch = self._to_sam2_image(x).unsqueeze(0)
451
452        y = y.squeeze(1)  # (B,H,W) or (B,Z,H,W)
453
454        # For 3D: sample from the union of IDs across all z-slices so that it includes objects
455        # present in any frame (frame 0 alone can be empty at patch boundaries).
456        obj_ids_per_b = [
457            self._sample_obj_ids(y[b].flatten() if is_3d else y[b]) for b in range(B)
458        ]
459        # The sampled IDs do not depend on the time step, so emptiness is the same for all of them.
460        n_objects = sum(len(ids) for ids in obj_ids_per_b)
461        if n_objects == 0:
462            raise RuntimeError(
463                "ConvertToSam2VideoBatch: no objects found in batch. "
464                "Use MinInstanceSampler to ensure each sample has objects."
465            )
466
467        # One broadcast comparison per frame instead of stacking objects one at a time. The
468        # 1024x1024 resize dominates regardless of how the masks are batched into it.
469        step_masks = []
470        for t in range(T):
471            raw = [
472                (y[b, t] if is_3d else y[b]).unsqueeze(0) == obj_ids_per_b[b].view(-1, 1, 1)
473                for b in range(B) if len(obj_ids_per_b[b]) > 0
474            ]
475            step_masks.append(self._resize_masks(torch.cat(raw)))  # (O,1024,1024)
476
477        # Per-time-step metadata (same structure as collate_fn in data_utils.py). The object
478        # slots are identical for every frame, so the flat lists are built once.
479        batch_index = [b for b in range(B) for _ in range(len(obj_ids_per_b[b]))]
480        object_ids = [int(oid) for b in range(B) for oid in obj_ids_per_b[b].tolist()]
481        step_obj2frame, step_identifier = [], []
482        for t in range(T):
483            step_obj2frame.append(torch.tensor([[t, b] for b in batch_index], dtype=torch.int))
484            step_identifier.append(
485                torch.tensor([[b, oid, t] for b, oid in zip(batch_index, object_ids)], dtype=torch.long)
486            )
487        orig_size = torch.tensor([H, W], dtype=torch.long).expand(T, n_objects, 2).contiguous()
488
489        return BatchedVideoDatapoint(
490            img_batch=img_batch,
491            obj_to_frame_idx=torch.stack(step_obj2frame),  # (T,O,2)
492            masks=torch.stack(step_masks),  # (T,O,1024,1024)
493            metadata=BatchedVideoMetaData(
494                unique_objects_identifier=torch.stack(step_identifier),
495                frame_orig_size=orig_size,
496            ),
497            dict_key="torch_em",
498            batch_size=[T],
499        )

Convert torch-em (x, y) batches to BatchedVideoDatapoint for SAM2Train.

2D inputs (x: B,C,H,W / y: B,1,H,W): each image becomes a 1-frame video (T=1). 3D inputs (x: B,C,Z,H,W / y: B,1,Z,H,W): Z-slices become video frames (T=Z).

Images are converted to SAM2 input format:

  • [0, 1] range -> ImageNet-normalized -> resized to 1024x1024
  • Single-channel inputs are broadcast to 3 channels.

Masks are resized to 1024×1024 (required so that get_next_point returns coordinates in the model's input coordinate space).

Arguments:
  • max_num_objects: Maximum number of objects to sample per image/volume. Excess objects are randomly subsampled.
  • largest_first: Fill half the object slots with the largest instances and the rest at random, instead of sampling all of them at random.
  • augmentor: Optional augmentation, called as augmentor(x, y) and returning the augmented pair. Must apply spatial transforms to both, or the masks stop matching the image. See ~micro_sam.v2.transforms.raw.VideoAugment.
ConvertToSam2VideoBatch( max_num_objects: int = 20, largest_first: bool = False, augmentor: Optional[Callable] = None)
370    def __init__(self, max_num_objects: int = 20, largest_first: bool = False, augmentor: Optional[Callable] = None):
371        self.max_num_objects = max_num_objects
372        self.largest_first = largest_first
373        self.augmentor = augmentor
374        self.init_kwargs = {"max_num_objects": max_num_objects, "largest_first": largest_first}
375        # Built once instead of per frame.
376        self.pixel_mean = torch.tensor(self._PIXEL_MEAN).view(1, 3, 1, 1)
377        self.pixel_std = torch.tensor(self._PIXEL_STD).view(1, 3, 1, 1)
max_num_objects
largest_first
augmentor
init_kwargs
pixel_mean
pixel_std
class MixedLoader:
502class MixedLoader:
503    """Round-robin DataLoader wrapper for joint 2D + 3D training.
504
505    Each iteration yields one batch from the first loader, then one from the
506    second, cycling until the shorter one is exhausted. This ensures that every
507    training step sees both 2D and 3D data.
508
509    Args:
510        loader_2d: DataLoader yielding (B,C,H,W) batches.
511        loader_3d: DataLoader yielding (B,C,Z,H,W) batches.
512    """
513
514    def __init__(self, loader_2d, loader_3d):
515        self.loader_2d = loader_2d
516        self.loader_3d = loader_3d
517        self.shuffle = getattr(loader_2d, "shuffle", True)
518
519    def __len__(self):
520        return len(self.loader_2d) + len(self.loader_3d)
521
522    def __iter__(self):
523        iter_2d = iter(self.loader_2d)
524        iter_3d = iter(self.loader_3d)
525        done_2d = done_3d = False
526        while not (done_2d and done_3d):
527            if not done_2d:
528                try:
529                    yield next(iter_2d)
530                except StopIteration:
531                    done_2d = True
532            if not done_3d:
533                try:
534                    yield next(iter_3d)
535                except StopIteration:
536                    done_3d = True

Round-robin DataLoader wrapper for joint 2D + 3D training.

Each iteration yields one batch from the first loader, then one from the second, cycling until the shorter one is exhausted. This ensures that every training step sees both 2D and 3D data.

Arguments:
  • loader_2d: DataLoader yielding (B,C,H,W) batches.
  • loader_3d: DataLoader yielding (B,C,Z,H,W) batches.
MixedLoader(loader_2d, loader_3d)
514    def __init__(self, loader_2d, loader_3d):
515        self.loader_2d = loader_2d
516        self.loader_3d = loader_3d
517        self.shuffle = getattr(loader_2d, "shuffle", True)
loader_2d
loader_3d
shuffle