micro_sam.v2.instance_segmentation

Automatic instance segmentation backends for the SAM2 model.

This module holds all the backend engines for automatic segmentation with SAM2, mirroring the micro-sam v1 instance_segmentation module (which holds AMG / AIS / APG). Two engines are provided:

Both engines share the initialize / generate / get_state / set_state interface of micro_sam.util.AutoSegBase, support in-plane (xy) tiling with a halo, and are selected via get_instance_segmentation_generator.

   1"""Automatic instance segmentation backends for the SAM2 model.
   2
   3This module holds all the backend engines for automatic segmentation with SAM2, mirroring the
   4micro-sam v1 `instance_segmentation` module (which holds AMG / AIS / APG). Two engines are provided:
   5
   6- AMG (`AutomaticMaskGenerationSegmenter`, `TiledAutomaticMaskGenerationSegmenter`): grid-based
   7  automatic mask generation, no decoder required. The expensive grid prediction happens in
   8  `initialize`, the cheap conversion to an instance segmentation in `generate`. Supported for 2d
   9  images and, via `amg_3d_segmentation`, for 3d volumes (run slice-by-slice and stitched
  10  across z with `micro_sam.v1.multi_dimensional_segmentation.merge_instance_segmentation_3d`).
  11
  12- AIS (`UniSAM2InstanceSegmentation`, `TiledUniSAM2InstanceSegmentation`): decoder-based instance
  13  segmentation with the UniSAM2 model (a UNETR decoder on top of the SAM2 image encoder, see
  14  `micro_sam.v2.models.util.UniSAM2`). The decoder predicts a foreground probability map and three
  15  directed distance channels, which `generate` converts into an instance segmentation via
  16  `micro_sam.v2.postprocessing` ('sparse' -> flow following for LM data, 'dense' -> multicut for EM
  17  data). All UniSAM2 inference is encapsulated in these classes.
  18
  19Both engines share the `initialize` / `generate` / `get_state` / `set_state` interface of
  20`micro_sam.util.AutoSegBase`, support in-plane (xy) tiling with a halo, and are selected via
  21`get_instance_segmentation_generator`.
  22"""
  23
  24import shutil
  25import contextlib
  26from pathlib import Path
  27from typing import Any, Dict, List, Optional, Tuple, Union
  28
  29import numpy as np
  30
  31import torch
  32
  33from bioimage_cpp.utils import Blocking
  34
  35from micro_sam.v1.inference import _merge_segmentations
  36from micro_sam.v2.postprocessing import flow_instance_segmentation, run_multicut
  37from micro_sam.v1.multi_dimensional_segmentation import merge_instance_segmentation_3d
  38from micro_sam.util import AutoSegBase, load_checkpoint, make_temp_embedding_path, mask_data_to_segmentation
  39from micro_sam.v2.util import (
  40    autocast, precompute_image_embeddings, set_precomputed, to_float32, _load_list_datasets,
  41    DEFAULT_BASE_MODEL, DEFAULT_TILE_Z, DEFAULT_HALO_Z, Devices, UNISAM2_OUTPUT_CHANNELS,
  42)
  43
  44DEFAULT_SEGMENTATION_MODE_WITH_DECODER = "ais"
  45
  46# Sentinel: pin the decoder to its model device unless the front end passes an explicit device intent.
  47USE_MODEL_DEVICE = object()
  48
  49
  50def _set_image_predictor_from_backbone(predictor, fpn_list, pos_enc_list, features, original_size, i):
  51    """Set a SAM2 image predictor's ``_features`` for slice ``i`` from stored backbone outputs.
  52
  53    ``fpn_list`` and ``features`` are indexed by the slice, ``level[i] -> (1, C, H, W)``; ``features``
  54    is the last FPN level, which is not stored twice. ``pos_enc_list`` is stored once for the whole
  55    volume and is always read at index 0. This reconstructs the image predictor's features exactly as
  56    ``SAM2ImagePredictor.set_image`` does (``_prepare_backbone_features`` + reshape) but without
  57    re-running the (expensive) image encoder.
  58    """
  59    from micro_sam.v2.util import _backbone_fpn
  60
  61    model = predictor.model
  62    device = next(model.parameters()).device
  63
  64    def _slice(level, index):
  65        t = torch.as_tensor(np.asarray(level[index]), device=device).float()
  66        return t if t.ndim == 4 else t.unsqueeze(0)  # ensure (B, C, H, W)
  67
  68    backbone_out = {
  69        "backbone_fpn": _backbone_fpn([_slice(level, i) for level in fpn_list], _slice(features, i)),
  70        "vision_pos_enc": [_slice(level, 0) for level in pos_enc_list],
  71    }
  72    _, vision_feats, _, _ = model._prepare_backbone_features(backbone_out)
  73    if model.directly_add_no_mem_embed:
  74        vision_feats[-1] = vision_feats[-1] + model.no_mem_embed
  75
  76    feats = [
  77        feat.permute(1, 2, 0).view(1, -1, *feat_size)
  78        for feat, feat_size in zip(vision_feats[::-1], predictor._bb_feat_sizes[::-1])
  79    ][::-1]
  80    predictor._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
  81    predictor._orig_hw = [tuple(int(s) for s in np.array(original_size).reshape(-1)[:2])]
  82    predictor._is_image_set = True
  83
  84
  85def _set_image_predictor_from_3d_embeddings(predictor, image_embeddings, i):
  86    """Set a SAM2 image predictor's features for slice ``i`` from precomputed 3d (video-style) embeddings.
  87
  88    The 3d embeddings produced for the volume (the same ones used for interactive 3d and the decoder)
  89    store the per-slice backbone FPN outputs (``fpn``) and positional encodings (``pos_enc``), so the
  90    per-slice AMG reuses them instead of re-encoding each slice.
  91    """
  92    _set_image_predictor_from_backbone(
  93        predictor, image_embeddings["fpn"], image_embeddings["pos_enc"], image_embeddings["features"],
  94        image_embeddings["original_size"], i,
  95    )
  96
  97
  98class _LazyRLEMask(dict):
  99    """A mask dict whose 'segmentation' is stored as an (uncompressed) RLE and decoded on access.
 100
 101    The SAM2 mask generator can emit hundreds-thousands of masks; holding them all as full-resolution
 102    binary arrays is what makes AMG run out of memory (it gets OS-killed even for 2d). Storing them as
 103    compact RLE and decoding to a binary mask only when 'segmentation' is read (e.g. inside
 104    `mask_data_to_segmentation`'s loop) keeps the peak at a single full-resolution mask at a time.
 105    All other fields (area, bbox, ...) are plain dict entries and are read without decoding.
 106    """
 107
 108    def __getitem__(self, key):
 109        value = super().__getitem__(key)
 110        if key == "segmentation" and isinstance(value, dict):
 111            from sam2.utils.amg import rle_to_mask
 112            return rle_to_mask(value)
 113        return value
 114
 115
 116class AutomaticMaskGenerationSegmenter(AutoSegBase):
 117    """Generates an instance segmentation for the SAM2 model using grid-based prompting (AMG).
 118
 119    Wraps the native `sam2.automatic_mask_generator.SAM2AutomaticMaskGenerator` and exposes the
 120    same `initialize` / `generate` interface as the micro-sam v1 `AutomaticMaskGenerator`, so it
 121    can be used both for single 2d images and, via `amg_3d_segmentation`, for 3d volumes.
 122
 123    The parameters that control the (expensive) mask prediction, e.g. `points_per_side` and the
 124    quality thresholds, are passed to the constructor. The (cheap) conversion of the predicted
 125    masks into an instance segmentation is controlled via `generate`.
 126
 127    The image embeddings are computed and cached via `micro_sam.v2.util.precompute_image_embeddings`
 128    (or taken from precomputed embeddings passed to `initialize`, e.g. by the GUI) and set on the
 129    predictor with `set_precomputed`, so the grid prediction reuses them instead of recomputing.
 130
 131    Use this class as follows:
 132    ```python
 133    segmenter = AutomaticMaskGenerationSegmenter(model)
 134    segmenter.initialize(image)  # Run the grid prediction, this is the expensive computation.
 135    masks = segmenter.generate(min_object_size=50)  # Convert to an instance segmentation, fast.
 136    ```
 137
 138    Args:
 139        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
 140        model_type: The SAM2 model type, e.g. 'hvit_t'. Used to tag cached embeddings; only needed
 141            when caching embeddings via `save_path`.
 142        points_per_side: The number of points sampled along one side of the image. By default '32'.
 143        points_per_batch: The number of points run simultaneously by the model. By default '64'.
 144        pred_iou_thresh: Filter threshold in [0, 1] using the model's predicted mask quality.
 145            By default '0.8'.
 146        stability_score_thresh: Filter threshold in [0, 1] using the stability of the mask under
 147            changes to the binarization cutoff. By default '0.9'. This is lower than SAM2's native
 148            default of '0.95' because the embeddings here come from micro-sam's percentile-normalized
 149            inputs, under which masks score marginally lower in stability.
 150        kwargs: Additional keyword arguments forwarded to `SAM2AutomaticMaskGenerator`.
 151    """
 152
 153    def __init__(
 154        self,
 155        model: torch.nn.Module,
 156        model_type: Optional[str] = None,
 157        points_per_side: Optional[int] = 32,
 158        points_per_batch: int = 32,
 159        pred_iou_thresh: float = 0.8,
 160        stability_score_thresh: float = 0.9,
 161        **kwargs,
 162    ) -> None:
 163        from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
 164
 165        # RLE masks, decoded one at a time by '_LazyRLEMask': holding every mask at full resolution
 166        # runs a large image out of memory.
 167        self._mask_generator = SAM2AutomaticMaskGenerator(
 168            model=model,
 169            points_per_side=points_per_side,
 170            points_per_batch=points_per_batch,
 171            pred_iou_thresh=pred_iou_thresh,
 172            stability_score_thresh=stability_score_thresh,
 173            output_mode="uncompressed_rle",
 174            **kwargs,
 175        )
 176        # Use the shared resize-longest transform for AMG.
 177        from micro_sam.v2.util import configure_image_predictor
 178        configure_image_predictor(self._mask_generator.predictor)
 179        # The embedding signature is keyed on these, which an image predictor does not carry itself.
 180        predictor = self._mask_generator.predictor
 181        predictor.model_type = model_type or getattr(model, "model_type", None) or "hvit"
 182        predictor.model_name = model_type or getattr(model, "model_name", None) or predictor.model_type
 183        # Baked into the masks by 'initialize', so a reused state can be validated against them.
 184        self._amg_params = {
 185            "points_per_side": points_per_side,
 186            "pred_iou_thresh": pred_iou_thresh,
 187            "stability_score_thresh": stability_score_thresh,
 188            "model_type": predictor.model_type,
 189        }
 190        self._masks = None
 191        self._original_size = None
 192        self._is_initialized = False
 193
 194    def _generate_masks_for_shape(self, shape: Tuple[int, int]) -> List[Dict[str, Any]]:
 195        """Run the grid-based mask prediction reusing the embeddings already set on the predictor.
 196
 197        The embeddings are expected to be set on `self._mask_generator.predictor` (via
 198        `precompute_image_embeddings` or `set_precomputed`). We temporarily neutralize the
 199        predictor's `set_image`, which the native mask generator calls once per crop, so that it
 200        reuses the precomputed embeddings instead of recomputing them. This is only valid for the
 201        single-crop case (`crop_n_layers=0`, the default). `shape` is the (Y, X) size the mask
 202        generator should assume (the full image, or a single tile).
 203        """
 204        predictor = self._mask_generator.predictor
 205        dummy = np.zeros((*shape, 3), dtype="uint8")
 206        original_set_image = predictor.set_image
 207        predictor.set_image = lambda *args, **kwargs: None
 208        try:
 209            masks = self._mask_generator.generate(dummy)
 210        finally:
 211            predictor.set_image = original_set_image
 212        # Decoded only when read, so not every mask is held at full resolution.
 213        return [_LazyRLEMask(mask) for mask in masks]
 214
 215    @torch.no_grad()
 216    def initialize(
 217        self,
 218        image: np.ndarray,
 219        image_embeddings: Optional[dict] = None,
 220        i: Optional[int] = None,
 221        save_path: Optional[str] = None,
 222        verbose: bool = False,
 223        pbar_init: Optional[callable] = None,
 224        pbar_update: Optional[callable] = None,
 225        **kwargs,
 226    ) -> None:
 227        """Run the grid-based mask prediction and store the resulting masks.
 228
 229        The image embeddings are computed (and cached if `save_path` is given) via
 230        `micro_sam.v2.util.precompute_image_embeddings`, or taken from `image_embeddings` if
 231        provided (e.g. by the GUI), and set on the predictor with `set_precomputed`. The grid
 232        prediction then reuses these embeddings instead of recomputing them.
 233
 234        Args:
 235            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). When `image_embeddings` is
 236                given the image content is not used (only the precomputed embeddings are).
 237            image_embeddings: Optional precomputed image embeddings. See `precompute_image_embeddings`.
 238            i: Index for the image data. Only relevant for externally precomputed embeddings; for
 239                a single 2d image (the per-slice case) it must be None.
 240            save_path: Optional path to cache the computed embeddings in a zarr container.
 241            verbose: Verbosity flag. By default 'False'.
 242            pbar_init: Callback to initialize an external progress bar.
 243            pbar_update: Callback to update an external progress bar.
 244            kwargs: Additional arguments, ignored. Kept for interface compatibility.
 245        """
 246        predictor = self._mask_generator.predictor
 247        if image_embeddings is None:
 248            # Computes (or loads from save_path) the embeddings and sets them on the predictor.
 249            precompute_image_embeddings(
 250                predictor, image, save_path=save_path, ndim=2, verbose=verbose,
 251                pbar_init=pbar_init, pbar_update=pbar_update,
 252            )
 253        elif "fpn" in image_embeddings and i is not None:
 254            # Reconstruct slice 'i' from the 3d embeddings, without re-running the encoder.
 255            _set_image_predictor_from_3d_embeddings(predictor, image_embeddings, i)
 256        else:
 257            set_precomputed(predictor, image_embeddings, i=i)
 258
 259        self._original_size = tuple(int(s) for s in predictor._orig_hw[0])
 260        self._masks = self._generate_masks_for_shape(self._original_size)
 261        self._is_initialized = True
 262
 263    def generate(
 264        self,
 265        min_object_size: int = 0,
 266        max_object_size: Optional[int] = None,
 267        with_background: bool = True,
 268        output_mode: str = "instance_segmentation",
 269    ) -> Union[List[Dict[str, Any]], np.ndarray]:
 270        """Convert the predicted masks into an instance segmentation.
 271
 272        Args:
 273            min_object_size: The minimal size of an object in pixels. By default '0'.
 274            max_object_size: The maximal size of an object in pixels. By default 'None'.
 275            with_background: Whether to remove the largest object, which often covers the
 276                background for AMG. By default 'True'.
 277            output_mode: The form masks are returned in. Either 'instance_segmentation' to return
 278                a single label array, or 'binary_mask' to return the list of mask dictionaries.
 279                By default 'instance_segmentation'.
 280
 281        Returns:
 282            The instance segmentation as a uint32 array, or the list of mask dictionaries.
 283        """
 284        if not self._is_initialized:
 285            raise RuntimeError(
 286                "AutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
 287            )
 288        if output_mode != "instance_segmentation":
 289            return self._masks
 290        if len(self._masks) == 0:  # No masks were found.
 291            return np.zeros(self._original_size, dtype="uint32")
 292        # Smaller masks paint over larger ones, as in micro-sam v1 AMG. With exclusive merging, the mask that
 293        # covers the whole image, which AMG always predicts, claims every pixel before the objects in it.
 294        return mask_data_to_segmentation(
 295            masks=self._masks,
 296            shape=self._original_size,
 297            min_object_size=min_object_size,
 298            max_object_size=max_object_size,
 299            with_background=with_background,
 300            merge_exclusively=False,
 301        )
 302
 303    def get_state(self) -> Dict[str, Any]:
 304        """Return the cached mask-generation state so it can be serialized and later restored.
 305
 306        The state holds the predicted masks (as compact RLE dicts), the image size and the
 307        parameters the masks were generated with (used to validate a reused state). Restore it
 308        with `set_state` to skip the expensive grid prediction in `initialize`.
 309        """
 310        if not self._is_initialized:
 311            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
 312        return {
 313            "masks": [dict(mask) for mask in self._masks],
 314            "original_size": self._original_size,
 315            "params": dict(self._amg_params),
 316        }
 317
 318    def set_state(self, state: Dict[str, Any]) -> None:
 319        """Restore the state produced by `get_state`, marking the segmenter initialized.
 320
 321        The masks are re-wrapped in `_LazyRLEMask` so `generate` decodes them lazily as before.
 322        """
 323        self._masks = [_LazyRLEMask(mask) for mask in state["masks"]]
 324        self._original_size = tuple(int(s) for s in state["original_size"])
 325        self._is_initialized = True
 326
 327    def clear_state(self) -> None:
 328        """Clear the cached masks."""
 329        self._masks = None
 330        self._original_size = None
 331        self._is_initialized = False
 332
 333
 334class TiledAutomaticMaskGenerationSegmenter(AutomaticMaskGenerationSegmenter):
 335    """Generates a tiled instance segmentation for the SAM2 model using grid-based prompting (AMG).
 336
 337    Implements the same functionality as `AutomaticMaskGenerationSegmenter`, but the image is split
 338    into tiles with a halo, AMG is run on each tile, and the per-tile instance segmentations are
 339    stitched back into a single segmentation. This is the tiled backend used for large images (and
 340    by the GUI). The `initialize` / `generate` interface matches the micro-sam v1
 341    `TiledAutomaticMaskGenerator`.
 342
 343    Args:
 344        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
 345        kwargs: Additional keyword arguments for `AutomaticMaskGenerationSegmenter`.
 346    """
 347
 348    @torch.no_grad()
 349    def initialize(
 350        self,
 351        image: np.ndarray,
 352        tile_shape: Optional[Tuple[int, int]] = None,
 353        halo: Optional[Tuple[int, int]] = None,
 354        image_embeddings: Optional[dict] = None,
 355        i: Optional[int] = None,
 356        save_path: Optional[str] = None,
 357        verbose: bool = False,
 358        pbar_init: Optional[callable] = None,
 359        pbar_update: Optional[callable] = None,
 360        **kwargs,
 361    ) -> None:
 362        """Run the grid-based mask prediction tile-by-tile and store the per-tile masks.
 363
 364        The tiled image embeddings are computed (and cached if `save_path` is given) via
 365        `precompute_image_embeddings`, or taken from `image_embeddings` if provided (e.g. by the
 366        GUI). The per-tile embeddings are then set on the predictor with `set_precomputed` and the
 367        grid prediction reuses them. When embeddings are provided the tiling is taken from them.
 368
 369        Args:
 370            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). Content unused when
 371                `image_embeddings` is given.
 372            tile_shape: The tile shape for the tiled prediction, (y, x). Taken from the embeddings
 373                when `image_embeddings` is given.
 374            halo: The overlap between the tiles, (y, x). Taken from the embeddings when given.
 375            image_embeddings: Optional precomputed tiled image embeddings.
 376            i: Index of the slice to segment if `image` has three spatial dimensions.
 377            save_path: Optional path to cache the computed embeddings in a zarr container.
 378            verbose: Verbosity flag. By default 'False'.
 379            kwargs: Additional arguments, ignored. Kept for interface compatibility.
 380        """
 381        predictor = self._mask_generator.predictor
 382        # Reconstruct slice 'i' per tile from the 3d embeddings, without re-running the encoder.
 383        if image_embeddings is not None and "fpn" in image_embeddings and i is not None:
 384            self._initialize_slice_from_3d_embeddings(image_embeddings, i)
 385            return
 386
 387        temporary_embedding_path = None
 388        self._is_initialized = False
 389        try:
 390            if image_embeddings is None:
 391                if tile_shape is None or halo is None:
 392                    raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled segmenter.")
 393                if image.ndim == 3 and image.shape[-1] != 3 and i is not None:
 394                    image = image[i]
 395                effective_save_path = save_path
 396                if effective_save_path is None:
 397                    temporary_embedding_path = make_temp_embedding_path()
 398                    effective_save_path = temporary_embedding_path
 399                image_embeddings = precompute_image_embeddings(
 400                    predictor, image, save_path=effective_save_path, ndim=2, tile_shape=tile_shape, halo=halo,
 401                    verbose=verbose, lazy_loading=True,
 402                )
 403
 404            self._initialize_from_tiled_embeddings(
 405                predictor, image_embeddings, verbose, pbar_init, pbar_update,
 406            )
 407        finally:
 408            if temporary_embedding_path is not None:
 409                try:
 410                    if image_embeddings is not None:
 411                        image_embeddings.close()
 412                finally:
 413                    image_embeddings = None
 414                    shutil.rmtree(temporary_embedding_path, ignore_errors=True)
 415
 416    def _initialize_from_tiled_embeddings(
 417        self, predictor, image_embeddings, verbose, pbar_init, pbar_update,
 418    ) -> None:
 419        """Run per-tile AMG from embeddings that remain valid for the duration of this call."""
 420        feats = image_embeddings["features"]
 421        tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"])
 422        halo = tuple(int(s) for s in feats.attrs["halo"])
 423        self._original_size = tuple(int(s) for s in feats.attrs["shape"])
 424        self._tile_shape = tile_shape
 425        self._tiling = Blocking([0, 0], list(self._original_size), list(tile_shape))
 426        self._halo = tuple(halo)
 427
 428        from micro_sam.util import handle_pbar
 429        _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update)
 430
 431        self._masks = []
 432        n_tiles = self._tiling.number_of_blocks
 433        pbar_init(n_tiles, "Automatic segmentation (tiles)")
 434        try:
 435            for tile_id in range(n_tiles):
 436                block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
 437                set_precomputed(predictor, image_embeddings, tile_id=tile_id)
 438                tile_size = tuple(end - begin for begin, end in zip(block.begin, block.end))
 439                self._masks.append(self._generate_masks_for_shape(tile_size))
 440                pbar_update(1)
 441        finally:
 442            pbar_close()
 443
 444        self._is_initialized = True
 445
 446    def _initialize_slice_from_3d_embeddings(self, image_embeddings, i):
 447        """Run the tiled AMG for slice ``i`` reusing precomputed 3d (video-style) tiled embeddings.
 448
 449        Each tile's image features for slice ``i`` are reconstructed from the per-tile ``fpn``/``pos_enc``
 450        (no encoder pass), the grid prediction is run per tile, and the per-tile masks are stitched
 451        in-plane by `generate`. The tiling is taken from the embeddings; the z axis is not tiled.
 452        """
 453        predictor = self._mask_generator.predictor
 454        feats = image_embeddings["features"]
 455        full_shape = tuple(int(s) for s in feats.attrs["shape"])  # (Z, Y, X)
 456        tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"])
 457        halo = tuple(int(s) for s in feats.attrs["halo"])
 458        self._original_size = full_shape[1:]  # in-plane (Y, X); z is not tiled
 459        self._tile_shape = tile_shape
 460        self._tiling = Blocking([0, 0], list(self._original_size), list(tile_shape))
 461        self._halo = halo
 462
 463        self._masks = []
 464        for tile_id in range(self._tiling.number_of_blocks):
 465            block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
 466            # Lazy, so only slice 'i' is read rather than the tile's whole z-stack on every slice.
 467            fpn_tile = _load_list_datasets(image_embeddings["fpn"], str(tile_id), lazy_loading=True)
 468            pos_tile = _load_list_datasets(image_embeddings["pos_enc"], str(tile_id), lazy_loading=True)
 469            original_size = feats[str(tile_id)].attrs["original_size"]
 470            _set_image_predictor_from_backbone(
 471                predictor, fpn_tile, pos_tile, feats[str(tile_id)], original_size, i
 472            )
 473            tile_size = tuple(end - begin for begin, end in zip(block.begin, block.end))
 474            self._masks.append(self._generate_masks_for_shape(tile_size))
 475
 476        self._is_initialized = True
 477
 478    def generate(
 479        self,
 480        min_object_size: int = 0,
 481        max_object_size: Optional[int] = None,
 482        with_background: bool = True,
 483        output_mode: str = "instance_segmentation",
 484    ) -> np.ndarray:
 485        """Convert the per-tile masks into an instance segmentation and stitch the tiles.
 486
 487        Args:
 488            min_object_size: The minimal size of an object in pixels. By default '0'.
 489            max_object_size: The maximal size of an object in pixels. By default 'None'.
 490            with_background: Whether to remove the largest object per tile. By default 'True'.
 491            output_mode: The form masks are returned in. Only 'instance_segmentation' is supported
 492                for the tiled segmenter. By default 'instance_segmentation'.
 493
 494        Returns:
 495            The stitched instance segmentation as a uint32 array.
 496        """
 497        if not self._is_initialized:
 498            raise RuntimeError(
 499                "TiledAutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
 500            )
 501        if output_mode != "instance_segmentation":
 502            raise ValueError("The tiled segmenter only supports output_mode='instance_segmentation'.")
 503
 504        segmentation = np.zeros(self._original_size, dtype="uint32")
 505        offset = 0
 506        for tile_id, masks in enumerate(self._masks):
 507            block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
 508            bb = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end))
 509            tile_shape = tuple(end - begin for begin, end in zip(block.begin, block.end))
 510
 511            if len(masks) == 0:
 512                continue
 513            this_seg = mask_data_to_segmentation(
 514                masks=masks,
 515                shape=tile_shape,
 516                min_object_size=min_object_size,
 517                max_object_size=max_object_size,
 518                with_background=with_background,
 519                merge_exclusively=False,
 520            )
 521
 522            # Offset the per-tile instance ids so that they stay unique across tiles.
 523            max_id = int(this_seg.max())
 524            if max_id == 0:
 525                continue
 526            this_seg[this_seg != 0] += offset
 527            offset += max_id
 528
 529            if tile_id == 0:
 530                segmentation[bb] = this_seg
 531            else:
 532                segmentation[bb] = _merge_segmentations(this_seg, segmentation[bb])
 533
 534        return segmentation
 535
 536    def get_state(self) -> Dict[str, Any]:
 537        """Return the cached per-tile mask state, plus the tiling needed to restore it."""
 538        if not self._is_initialized:
 539            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
 540        return {
 541            "masks": [[dict(mask) for mask in tile_masks] for tile_masks in self._masks],
 542            "original_size": self._original_size,
 543            "tile_shape": self._tile_shape,
 544            "halo": self._halo,
 545            "params": dict(self._amg_params),
 546        }
 547
 548    def set_state(self, state: Dict[str, Any]) -> None:
 549        """Restore the per-tile masks and rebuild the tiling from `get_state`."""
 550        self._masks = [[_LazyRLEMask(mask) for mask in tile_masks] for tile_masks in state["masks"]]
 551        self._original_size = tuple(int(s) for s in state["original_size"])
 552        self._tile_shape = tuple(int(s) for s in state["tile_shape"])
 553        self._halo = tuple(int(s) for s in state["halo"])
 554        self._tiling = Blocking([0, 0], list(self._original_size), list(self._tile_shape))
 555        self._is_initialized = True
 556
 557
 558def get_amg_segmenter(
 559    model: torch.nn.Module, is_tiled: bool = False, **kwargs
 560) -> AutomaticMaskGenerationSegmenter:
 561    """Get the SAM2 automatic mask generation segmenter.
 562
 563    Args:
 564        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
 565        is_tiled: Whether to use the tiled segmenter for large images. By default 'False'.
 566        kwargs: Additional keyword arguments for the segmenter.
 567
 568    Returns:
 569        The automatic mask generation segmenter, either `TiledAutomaticMaskGenerationSegmenter`
 570        (if tiled) or `AutomaticMaskGenerationSegmenter`.
 571    """
 572    if is_tiled:
 573        return TiledAutomaticMaskGenerationSegmenter(model, **kwargs)
 574    return AutomaticMaskGenerationSegmenter(model, **kwargs)
 575
 576
 577def amg_3d_segmentation(
 578    volume: np.ndarray,
 579    segmenter: AutomaticMaskGenerationSegmenter,
 580    with_background: bool = True,
 581    gap_closing: Optional[int] = None,
 582    min_z_extent: Optional[int] = None,
 583    tile_shape: Optional[Tuple[int, int]] = None,
 584    halo: Optional[Tuple[int, int]] = None,
 585    image_embeddings: Optional[dict] = None,
 586    state_save_path: Optional[str] = None,
 587    verbose: bool = True,
 588    pbar_init: Optional[callable] = None,
 589    pbar_update: Optional[callable] = None,
 590    **kwargs,
 591) -> np.ndarray:
 592    """Automatically segment objects in a volume with the SAM2 mask generator.
 593
 594    Segments each slice individually in 2d with AMG and then merges the slices across z based on
 595    the overlap of objects between adjacent slices, using the multi-dimensional segmentation
 596    stitching (`merge_instance_segmentation_3d`). When `tile_shape` and `halo` are given, the
 597    per-slice AMG is run with the tiled segmenter.
 598
 599    Args:
 600        volume: The input volume, shape (Z, Y, X), or (Z, Y, X, C) with a trailing channel axis.
 601        segmenter: The automatic mask generation segmenter. Use a
 602            `TiledAutomaticMaskGenerationSegmenter` together with `tile_shape` and `halo`.
 603        with_background: Whether the segmentation has background. By default 'True'.
 604        gap_closing: If given, gaps in the segmentation are closed with a binary closing operation.
 605            The value is the number of iterations for the closing. By default 'None'.
 606        min_z_extent: Require a minimal extent in z for the segmented objects. This can help to
 607            prevent segmentation artifacts. By default 'None'.
 608        tile_shape: The tile shape for the tiled per-slice prediction, (y, x). By default 'None'.
 609        halo: The overlap between the tiles, (y, x). By default 'None'.
 610        image_embeddings: Optional precomputed 3d (video-style) embeddings for the volume. When given
 611            (and not tiled), each slice's AMG reuses the precomputed features instead of re-encoding.
 612        state_save_path: Optional path to the embedding Zarr in which to cache the per-slice
 613            grid-prediction state. When set, a slice reuses its cached state instead of re-running
 614            the grid prediction; freshly computed slices are written back.
 615        verbose: Verbosity flag. By default 'True'.
 616        pbar_init: Callback to initialize an external progress bar, called with the number of slices.
 617        pbar_update: Callback to update an external progress bar, called once per segmented slice.
 618        kwargs: Keyword arguments for the 'generate' method of the segmenter.
 619
 620    Returns:
 621        The 3d instance segmentation, uint32 array of shape (Z, Y, X).
 622    """
 623    if volume.ndim not in (3, 4):
 624        raise ValueError(f"Expected a 3d volume of shape (Z, Y, X) or (Z, Y, X, C), got shape {volume.shape}.")
 625
 626    init_kwargs = {}
 627    if tile_shape is not None and halo is not None:
 628        init_kwargs = {"tile_shape": tile_shape, "halo": halo}
 629    # The segmenter reconstructs each slice's features from the 3d embeddings, so nothing re-encodes.
 630    reuse_embeddings = image_embeddings is not None
 631
 632    from micro_sam.util import handle_pbar
 633    _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update)
 634    pbar_init(volume.shape[0], "Automatic segmentation (slices)")
 635
 636    def init_slice(i):
 637        if reuse_embeddings:
 638            segmenter.initialize(volume[i], image_embeddings=image_embeddings, i=i, verbose=False, **init_kwargs)
 639        else:
 640            segmenter.initialize(volume[i], verbose=False, **init_kwargs)
 641
 642    if state_save_path is not None:
 643        from micro_sam.precompute_state import _cache_amg_slice, _embedding_signature
 644        state_signature = _embedding_signature(state_save_path)
 645
 646    segmentation = np.zeros(volume.shape[:3], dtype="uint32")
 647    offset = 0
 648    for i in range(volume.shape[0]):
 649        if state_save_path is not None:
 650            _cache_amg_slice(segmenter, state_save_path, i, init_slice, embedding_signature=state_signature)
 651        else:
 652            init_slice(i)
 653        seg = segmenter.generate(**kwargs)
 654
 655        # Offset the per-slice instance ids so that they are unique across the whole volume.
 656        max_z = int(seg.max())
 657        if max_z != 0:
 658            seg[seg != 0] += offset
 659            offset += max_z
 660            segmentation[i] = seg
 661        pbar_update(1)
 662    pbar_close()
 663
 664    segmentation = merge_instance_segmentation_3d(
 665        segmentation,
 666        beta=0.5,
 667        with_background=with_background,
 668        gap_closing=gap_closing,
 669        min_z_extent=min_z_extent,
 670        verbose=verbose,
 671    )
 672    return segmentation
 673
 674
 675def _convert_automatic_qlora_state(model, model_state):
 676    """Merge trained QLoRA tensors into a full-precision UniSAM2 state."""
 677    full_precision_state = model.state_dict()
 678    trainable_encoder_keys = {
 679        name for name, param in model.named_parameters()
 680        if name.startswith("encoder.inner.") and param.requires_grad
 681    }
 682    finetuned_keys = trainable_encoder_keys | {
 683        key for key in full_precision_state if not key.startswith("encoder.inner.")
 684    }
 685
 686    missing_keys = sorted(key for key in finetuned_keys if key not in model_state)
 687    mismatched_keys = sorted(
 688        key for key in finetuned_keys
 689        if key in model_state and model_state[key].shape != full_precision_state[key].shape
 690    )
 691    if missing_keys or mismatched_keys:
 692        problems = []
 693        if missing_keys:
 694            problems.append(f"missing trained keys: {missing_keys}")
 695        if mismatched_keys:
 696            problems.append(f"incompatible trained keys: {mismatched_keys}")
 697        raise RuntimeError(f"Could not convert the automatic QLoRA checkpoint: {'; '.join(problems)}")
 698
 699    converted_state = dict(full_precision_state)
 700    converted_state.update({key: model_state[key] for key in finetuned_keys})
 701    return converted_state
 702
 703
 704# Older torch-em has no 'initial_features' in UNETR3D's signature, so '**kwargs' swallows it.
 705CONFIGURABLE_DECODER_WIDTH_VERSION = "0.10.3"
 706
 707
 708def _check_decoder_width(model, initial_features):
 709    """Check that the decoder was built at the width the checkpoint was trained with.
 710
 711    Without this an outdated torch-em surfaces as size mismatches from `load_state_dict`, which do
 712    not point at the dependency behind them.
 713
 714    Args:
 715        model: The freshly built UniSAM2 model.
 716        initial_features: The decoder width read off the checkpoint.
 717
 718    Raises:
 719        RuntimeError: If the built decoder is not `initial_features` wide.
 720    """
 721    # A stub or a custom module may have no 'out_conv'; this is a diagnostic, so it is skipped there.
 722    out_conv = getattr(model, "out_conv", None)
 723    if out_conv is None:
 724        return
 725
 726    built_features = out_conv.weight.shape[1]
 727    if built_features == initial_features:
 728        return
 729
 730    import torch_em
 731    raise RuntimeError(
 732        f"The UniSAM2 decoder was built {built_features} channels wide, but the checkpoint was trained "
 733        f"{initial_features} wide. The installed torch-em ({torch_em.__version__}) ignores the decoder "
 734        f"width micro-sam requests. Update it to {CONFIGURABLE_DECODER_WIDTH_VERSION} or later."
 735    )
 736
 737
 738class NoDecoderError(ValueError):
 739    """The checkpoint has no decoder, because the model was trained for interactive segmentation only."""
 740
 741    def __init__(self, checkpoint_path):
 742        super().__init__(
 743            f"The checkpoint '{checkpoint_path}' has no decoder for automatic segmentation, because the model was "
 744            "trained for interactive segmentation only. Automatic segmentation is not available with it. "
 745            "Train the model with 'train_automatic' or with joint training to get a decoder."
 746        )
 747
 748
 749def find_decoder_checkpoint(checkpoint_path):
 750    """Find the decoder file that belongs to a model file.
 751
 752    The decoder file is next to the model file and has the name of the model file with '_decoder' added,
 753    for example 'hvit_t_cells_decoder.pt' for 'hvit_t_cells.pt' or 'hvit_t_cells_decoder' for 'hvit_t_cells'.
 754
 755    Args:
 756        checkpoint_path: The path of the model file.
 757
 758    Returns:
 759        The path of the decoder file, or None if there is no decoder file.
 760    """
 761    path = Path(checkpoint_path)
 762    candidates = [path.with_name(f"{path.stem}_decoder{path.suffix}"), path.with_name(f"{path.stem}_decoder.pt")]
 763    if path.suffix:
 764        candidates.append(path.with_name(f"{path.stem}_decoder"))
 765    return next((str(candidate) for candidate in candidates if candidate.is_file()), None)
 766
 767
 768def get_unisam2_model(
 769    checkpoint_path, device=None, encoder=DEFAULT_BASE_MODEL, peft_kwargs=None, encoder_model_type=None
 770):
 771    """Load a UniSAM2 model for automatic segmentation from a checkpoint.
 772
 773    Args:
 774        checkpoint_path: Path to the UniSAM2 checkpoint.
 775        device: The device to load the model onto.
 776        encoder: The SAM2 encoder to build the decoder on. Either the backbone name to build from
 777            scratch, e.g. 'hvit_t', or a prebuilt SAM2 image-encoder module to reuse (which avoids
 778            rebuilding / downloading the base backbone). Its weights are (re)defined by the checkpoint.
 779        peft_kwargs: The arguments for `PEFT_Sam2`. The function uses the saved arguments by default.
 780        encoder_model_type: The SAM2 model type for a prebuilt PEFT encoder. You must set this argument for modules.
 781
 782    Returns:
 783        The UniSAM2 model in eval mode.
 784
 785    Raises:
 786        NoDecoderError: If the checkpoint has no decoder, because it was trained for interactive segmentation only.
 787    """
 788    from micro_sam.v2.models.util import UniSAM2, read_unisam2_state
 789
 790    # Captured before 'encoder' is reassigned to the built PEFT module below.
 791    resolved_model_type = encoder if isinstance(encoder, str) else encoder_model_type
 792
 793    device = "cpu" if device is None else device
 794    state = load_checkpoint(checkpoint_path, map_location=device)
 795    model_state = read_unisam2_state(state)
 796    if model_state is None:
 797        raise NoDecoderError(checkpoint_path)
 798
 799    if peft_kwargs is None and isinstance(state, dict) and state.get("peft_kwargs") is not None:
 800        from micro_sam.v2.models.peft_sam2 import PEFT_MODULES
 801        from micro_sam.models.peft import deserialize_peft_kwargs
 802
 803        peft_kwargs = deserialize_peft_kwargs(state["peft_kwargs"], PEFT_MODULES)
 804
 805    is_qlora = bool(peft_kwargs and peft_kwargs.get("quantize", False))
 806    # A prebuilt encoder with the PEFT layers of the checkpoint is reused, so that no base backbone is built.
 807    if peft_kwargs and not is_qlora and isinstance(encoder, torch.nn.Module):
 808        encoder_keys = {"encoder.inner." + k for k in encoder.state_dict()}
 809        if encoder_keys == {k for k in model_state if k.startswith("encoder.inner.")}:
 810            peft_kwargs = None
 811    if peft_kwargs:
 812        from micro_sam.v2.util import get_sam2_model
 813        from micro_sam.v2.models.peft_sam2 import PEFT_Sam2
 814
 815        peft_kwargs = {k: v for k, v in peft_kwargs.items() if k != "quantize"}
 816        base_model_type = encoder if isinstance(encoder, str) else encoder_model_type
 817        if base_model_type is None:
 818            raise ValueError("Set 'encoder_model_type' when you pass a prebuilt PEFT encoder.")
 819        sam2_model = get_sam2_model(model_type=base_model_type, input_type="images", device=device)
 820        sam2_model = PEFT_Sam2(sam2_model, **peft_kwargs).sam
 821        encoder = sam2_model.image_encoder
 822
 823    # Neither the decoder width nor the channel count is recorded in the checkpoint, so read both off 'out_conv'.
 824    output_channels, initial_features = model_state["out_conv.weight"].shape[:2]
 825    if output_channels != UNISAM2_OUTPUT_CHANNELS:
 826        raise ValueError(
 827            f"The decoder predicts {output_channels} channels, but only decoders with {UNISAM2_OUTPUT_CHANNELS} "
 828            "output channels (foreground, three directed distances, boundary) are supported."
 829        )
 830
 831    model = UniSAM2(encoder=encoder, output_channels=output_channels, initial_features=initial_features, device=device)
 832    _check_decoder_width(model, initial_features)
 833    if peft_kwargs and is_qlora:
 834        model_state = _convert_automatic_qlora_state(model, model_state)
 835    model.load_state_dict(model_state)
 836
 837    model.eval()
 838    model.model_type = resolved_model_type
 839    return model
 840
 841
 842def get_decoder(model_type, checkpoint=None, device=None, encoder=None):
 843    """Resolve and load the UniSAM2 decoder for a SAM2 model.
 844
 845    The decoder is provided either by an explicit `checkpoint` or by a finetuned model with a
 846    registered decoder (e.g. 'hvit_t_cells'). Mirrors the micro-sam v1 `get_decoder`.
 847    If `checkpoint` has no decoder, the decoder file next to it is used, see `find_decoder_checkpoint`.
 848
 849    Args:
 850        model_type: The SAM2 model. A finetuned model with a registered decoder, or a base backbone
 851            combined with `checkpoint`.
 852        checkpoint: Optional path to a decoder checkpoint to build the UniSAM2 decoder from. This can also be
 853            a joint checkpoint, or a model file with its decoder file next to it.
 854        device: The device to load the decoder onto.
 855        encoder: Optional prebuilt SAM2 image-encoder module to build the decoder on, reused instead
 856            of rebuilding the base backbone (its weights are redefined by the checkpoint's strict
 857            load). By default the base backbone name (first 6 chars of `model_type`) is used.
 858
 859    Returns:
 860        The UniSAM2 decoder model.
 861
 862    Raises:
 863        NoDecoderError: If `checkpoint` has no decoder and there is no decoder file next to it.
 864    """
 865    from micro_sam.v2.util import FINETUNED_MODELS, has_registered_decoder, _download_finetuned_sam2_model
 866
 867    # Without a prebuilt encoder, build on the base backbone name, e.g. 'hvit_t_cells' -> 'hvit_t'.
 868    if encoder is None:
 869        encoder = model_type[:6]
 870    if checkpoint is not None:
 871        decoder_source = checkpoint
 872    elif model_type in FINETUNED_MODELS and has_registered_decoder(model_type):
 873        _, _, decoder_source = _download_finetuned_sam2_model(model_type)
 874    else:
 875        raise ValueError(
 876            f"Automatic segmentation with SAM2 requires a finetuned model with a registered decoder "
 877            f"or a decoder checkpoint. '{model_type}' provides neither."
 878        )
 879
 880    def _load(source):
 881        return get_unisam2_model(source, device=device, encoder=encoder, encoder_model_type=model_type[:6])
 882
 883    try:
 884        decoder = _load(decoder_source)
 885    except NoDecoderError:
 886        decoder_source = None if checkpoint is None else find_decoder_checkpoint(checkpoint)
 887        if decoder_source is None:
 888            raise
 889        decoder = _load(decoder_source)
 890    # The defaults are looked up by the family of the full name.
 891    decoder.model_type = model_type
 892    return decoder
 893
 894
 895def _resize_spatial(x: torch.Tensor, size: tuple) -> torch.Tensor:
 896    """Resize the trailing (Y, X) of a (B, C, Z, Y, X) tensor to `size`, leaving Z unchanged."""
 897    b, c, z, y, x_dim = x.shape
 898    x = x.permute(0, 2, 1, 3, 4).reshape(b * z, c, y, x_dim)
 899    x = torch.nn.functional.interpolate(x, size=tuple(size), mode="bilinear", align_corners=False)
 900    return x.reshape(b, z, c, size[0], size[1]).permute(0, 2, 1, 3, 4)
 901
 902
 903class ResizeLongestSideWrapper(torch.nn.Module):
 904    """Run UniSAM2 with resize-longest and bottom/right padding."""
 905
 906    def __init__(self, model: torch.nn.Module, img_size: int) -> None:
 907        super().__init__()
 908        self.model = model
 909        self.img_size = img_size
 910
 911    def forward(self, x: torch.Tensor) -> torch.Tensor:
 912        from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_tensor
 913
 914        spatial = x.shape[-2:]
 915        x, resized = resize_longest_side_and_pad_tensor(x, self.img_size)
 916        out = self.model(x)
 917        out = out[..., :resized[0], :resized[1]]
 918        return _resize_spatial(out, spatial)
 919
 920
 921@contextlib.contextmanager
 922def _bridge_halo_progress(pbar_update):
 923    """Bridge `predict_with_halo`'s internal per-block tqdm to an external `pbar_update` callback.
 924
 925    `predict_with_halo` wraps its thread-pool map in a tqdm (a napari progress bar inside napari)
 926    that micro-sam cannot otherwise drive, so 3d/tiled auto-segmentation showed no real progress.
 927    This temporarily swaps that module-level tqdm for a thin iterator that fires `pbar_update` once
 928    per completed block. It is a no-op fallback if `pbar_update` is None.
 929    """
 930    if pbar_update is None:
 931        yield
 932        return
 933
 934    import torch_em.util.prediction as prediction_module
 935    original_tqdm = prediction_module.tqdm
 936
 937    class _ProgressBridge:
 938        def __init__(self, iterable=None, *args, **kwargs):
 939            self._iterable = iterable
 940
 941        def __iter__(self):
 942            for item in self._iterable:
 943                yield item
 944                pbar_update(1)
 945
 946        def __enter__(self):
 947            return self
 948
 949        def __exit__(self, *exc):
 950            return False
 951
 952        def update(self, n=1):
 953            pbar_update(n)
 954
 955        def set_description(self, *args, **kwargs):
 956            pass
 957
 958        def close(self):
 959            pass
 960
 961    prediction_module.tqdm = _ProgressBridge
 962    try:
 963        yield
 964    finally:
 965        prediction_module.tqdm = original_tqdm
 966
 967
 968def _n_blocks(spatial_shape, ndim, block_shape):
 969    """Number of blocks `predict_with_halo` iterates over, for a determinate progress total."""
 970    blocked = spatial_shape if ndim == 3 else (1, *spatial_shape)
 971    return int(np.prod([int(np.ceil(s / b)) for s, b in zip(blocked, block_shape)]))
 972
 973
 974def _block_shape_and_halo(spatial_shape, ndim, tile_shape, halo):
 975    """Compute the (z, y, x) block shape and halo for `predict_with_halo`.
 976
 977    For 3d data a volume is always chunked along z - the default z block when `tile_shape` is None,
 978    or its own z entry when tiling is given, since a 3d `tile_shape` is always the full (z, y, x),
 979    never in-plane only. The model is trained on small z crops, so running every slice at once is
 980    both out-of-distribution and a memory blow-up (the cause of the 3d 'killed' reports). 2d data is
 981    a single (1, y, x) block.
 982
 983    Args:
 984        spatial_shape: The spatial image shape, (Y, X) for 2d or (Z, Y, X) for 3d.
 985        ndim: The number of spatial dimensions (2 or 3).
 986        tile_shape: The tile shape, or None for no tiling. Always the full (z, y, x) for 3d data.
 987        halo: The tile halo, or None for no overlap.
 988
 989    Returns:
 990        The (block_shape, block_halo) tuples in (z, y, x) order for `predict_with_halo`.
 991    """
 992    is_3d = ndim == 3
 993    if tile_shape is None and is_3d:
 994        n_slices = spatial_shape[0]
 995        z_block = min(DEFAULT_TILE_Z, n_slices)
 996        block_shape = (z_block, spatial_shape[1], spatial_shape[2])
 997        block_halo = (DEFAULT_HALO_Z if z_block < n_slices else 0, 0, 0)
 998    elif tile_shape is None:
 999        block_shape = (1, *spatial_shape)
1000        block_halo = (0, 0, 0)
1001    elif is_3d:
1002        if len(tile_shape) != 3:
1003            raise ValueError(f"A 3d tile_shape must have 3 entries (z, y, x), got {len(tile_shape)}.")
1004        block_shape = tuple(int(v) for v in tile_shape)
1005        block_halo = (0, 0, 0) if halo is None else tuple(int(v) for v in halo)
1006    else:
1007        block_shape = (1, *tile_shape)  # (1, y, x)
1008        block_halo = (0, *((0, 0) if halo is None else halo))
1009    return block_shape, block_halo
1010
1011
1012def _resolve_z_chunk(tile_shape, halo, n_slices: int) -> Tuple[int, int]:
1013    """Derive the (z_block, z_halo) a 3d decoder-from-embeddings job chunks z with.
1014
1015    `tile_shape`/`halo` are None (fully automatic) or the full (z, y, x) / (z_halo, y_halo, x_halo);
1016    only the z entry matters here - the y, x entries are either not tiled, or the tiling already
1017    lives in the embeddings the job decodes from, so they cannot be changed at decode time.
1018    """
1019    if tile_shape is None:
1020        z_block = min(DEFAULT_TILE_Z, n_slices)
1021        return z_block, (DEFAULT_HALO_Z if z_block < n_slices else 0)
1022    if len(tile_shape) != 3:
1023        raise ValueError(f"A 3d tile_shape must have 3 entries (z, y, x), got {len(tile_shape)}.")
1024    return int(tile_shape[0]), (0 if halo is None else int(halo[0]))
1025
1026
1027class _StubEncoder(torch.nn.Module):
1028    """Encoder replacement that returns precomputed per-slice features in call order.
1029
1030    For a single feature volume, `features` has shape (Z, C, H, W). Batched decoder inference uses
1031    (B, Z, C, H, W), in which case each encoder call returns the corresponding slice for all batch
1032    elements. This reproduces the encoder outputs expected by `UNETR3D.forward` without re-encoding.
1033    """
1034
1035    def __init__(self, features: torch.Tensor, img_size: int = 1024) -> None:
1036        super().__init__()
1037        self.features = features
1038        self.img_size = img_size
1039        self._idx = 0
1040
1041    def forward(self, x):  # noqa
1042        if self.features.ndim == 5:
1043            feature = self.features[:, self._idx]
1044        else:
1045            feature = self.features[self._idx:self._idx + 1]
1046        self._idx += 1
1047        return [feature]
1048
1049
1050def _decode_3d_feature_batch(model, features, original_size, device):
1051    """Decode precomputed feature volumes with shape (B, Z, C, H, W).
1052
1053    Runs in the device precision (see `micro_sam.v2.util.autocast_dtype`). Predictions stay float32.
1054    """
1055    if features.ndim != 5:
1056        raise ValueError(f"Expected batched features with shape (B, Z, C, H, W), got {features.shape}.")
1057    device = features.device if device is None else torch.device(device)
1058    img_size = getattr(model.encoder, "img_size", 1024)
1059    real_encoder = model.encoder
1060    model.encoder = _StubEncoder(features, img_size)
1061    try:
1062        dummy = torch.zeros((features.shape[0], 3, features.shape[1], *original_size), device=device)
1063        with autocast(device):
1064            output = model(dummy)
1065    finally:
1066        model.encoder = real_encoder
1067    # Moved before casting: an fp32 copy on the device would cancel out what fp16 inference saves.
1068    return output.detach().cpu().float().numpy()
1069
1070
1071def _decode_3d_feature_block(model, feature, original_size, device):
1072    """Decode one precomputed feature volume with shape (Z, C, H, W)."""
1073    return _decode_3d_feature_batch(model, feature.unsqueeze(0), original_size, device)[0]
1074
1075
1076def _segment_from_predictions(prediction: np.ndarray, mode: str = "sparse", **kwargs) -> np.ndarray:
1077    """Convert UniSAM2 predictions into an instance segmentation.
1078
1079    Args:
1080        prediction: The UniSAM2 predictions, shape (5, *spatial). Channel 0 is the foreground probability,
1081            channels 1-3 are the directed distances and channel 4 is the object boundary, which the sparse mode
1082            forwards as 'boundary'.
1083        mode: The segmentation mode. 'sparse' uses flow-based segmentation (LM data, 2d and 3d),
1084            'dense' uses multicut-based segmentation (EM data, 2d and 3d).
1085        kwargs: Additional parameters forwarded to the postprocessing function
1086            (`flow_instance_segmentation` for 'sparse', `run_multicut` for 'dense').
1087
1088    Returns:
1089        The instance segmentation, uint32 array with the spatial shape of the prediction.
1090    """
1091    if prediction.shape[0] != UNISAM2_OUTPUT_CHANNELS:
1092        raise ValueError(
1093            f"Expected a UniSAM2 prediction with {UNISAM2_OUTPUT_CHANNELS} channels (foreground, three directed "
1094            f"distances, boundary), got {prediction.shape[0]}."
1095        )
1096    foreground = prediction[0]
1097    if mode == "dense":
1098        boundary_map = foreground.max() - foreground
1099        denom = boundary_map.max()
1100        if denom > 0:
1101            boundary_map = boundary_map / denom
1102        # Multicut uses the in-plane (y, x) distance channels.
1103        distances = np.stack([prediction[2], prediction[3]])
1104        # run_multicut takes a volume, so 2d data runs as a single slice, which has no z-edges.
1105        if boundary_map.ndim == 2:
1106            seg = run_multicut(boundary_map[None], distances[:, None], **kwargs)[0]
1107        else:
1108            seg = run_multicut(boundary_map, distances, **kwargs)
1109    else:
1110        seg = flow_instance_segmentation(foreground, prediction[1:4], boundary=prediction[4], **kwargs)
1111    return seg.astype("uint32")
1112
1113
1114class UniSAM2InstanceSegmentation(AutoSegBase):
1115    """Generates an instance segmentation with the UniSAM2 decoder (AIS).
1116
1117    A concrete `AutoSegBase` (like `AutomaticMaskGenerationSegmenter`), but predicts the segmentation
1118    with the UniSAM2 decoder instead of grid prompts. All UniSAM2 inference is encapsulated here (the
1119    only way to run it). Use it as follows:
1120    ```python
1121    segmenter = UniSAM2InstanceSegmentation(model)
1122    segmenter.initialize(image, ndim=2)  # Run the UniSAM2 inference.
1123    masks = segmenter.generate(mode="sparse", foreground_threshold=0.6)  # Post-process.
1124    ```
1125
1126    Args:
1127        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
1128        device: The device the model lives on (used for the non-tiled 2d decoder).
1129        inference_device: The device intent used as the `devices=None` fallback. Defaults to the
1130            model device (single GPU); pass None to fan out over all visible GPUs, or a device / list.
1131    """
1132
1133    _is_decoder_based = True
1134    _precompute_embeddings_in_frontend = True
1135
1136    def __init__(
1137        self,
1138        model: torch.nn.Module,
1139        device: Optional[Union[str, torch.device]] = None,
1140        inference_device: Devices = USE_MODEL_DEVICE,
1141    ) -> None:
1142        self._model = model
1143        # 'model_type' can be unset on a manually assembled module; the postprocessing defaults need
1144        # a concrete backbone to look up, so fall back to the single-source default rather than None.
1145        self._model_type = getattr(model, "model_type", None) or DEFAULT_BASE_MODEL
1146        self._device = device
1147        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
1148        self._prediction = None
1149        self._is_initialized = False
1150
1151    def _inference_devices(self, devices: Devices) -> Devices:
1152        """Resolve the inference devices, falling back to the configured device intent."""
1153        return devices if devices is not None else self._inference_device
1154
1155    def _run_full_inference(
1156        self, raw, ndim, tile_shape=None, halo=None, pbar_init=None, pbar_update=None,
1157        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1158        normalization=None,
1159    ):
1160        """Run queued, batched UniSAM2 encoder and decoder inference.
1161
1162        Tiled reads and preprocessing, GPU inference, and output writes overlap through the torch-em
1163        prediction pipeline. If `batch_size` is None, candidate sizes are benchmarked and a
1164        throughput-efficient batch is selected independently on every CUDA device. `normalization`
1165        overrides the per-block input normalization, which defaults to the 2nd / 98th percentile.
1166        """
1167        from torch_em.util.prediction import predict_with_halo_pipelined
1168        from micro_sam.v2.normalization import normalize_raw
1169        from micro_sam.v2.batched_inference import (
1170            _compute_auto_batch_sizes, _prepare_models, _release_model_replicas, _resolve_devices,
1171        )
1172
1173        def _normalize(crop):
1174            if normalization is None:
1175                return normalize_raw(crop, axis=(-2, -1))
1176            return normalization(crop)
1177
1178        def _preprocess(crop):
1179            return np.concatenate([_normalize(crop)] * 3, axis=0)
1180
1181        def _predict(this_model, inputs):
1182            # The pipeline writes numpy blocks, which have no bfloat16.
1183            with autocast(inputs.device):
1184                return to_float32(this_model(inputs))
1185
1186        def _predict_probe(this_model, inputs):
1187            return _predict(this_model, inputs.clamp(0.0, 1.0))
1188
1189        is_3d = ndim == 3
1190        block_shape, block_halo = _block_shape_and_halo(tuple(raw.shape), ndim, tile_shape, halo)
1191        n_blocks = _n_blocks(tuple(raw.shape), ndim, block_shape)
1192        if pbar_init is not None:
1193            desc = "Automatic segmentation (volume)" if is_3d else "Automatic segmentation"
1194            pbar_init(n_blocks, desc)
1195
1196        if is_3d:
1197            input_ = raw[np.newaxis].astype("float32")
1198            output = np.zeros((UNISAM2_OUTPUT_CHANNELS, *raw.shape), dtype="float32")
1199        else:
1200            input_ = raw[np.newaxis, np.newaxis].astype("float32")
1201            output = np.zeros((UNISAM2_OUTPUT_CHANNELS, 1, *raw.shape), dtype="float32")
1202
1203        img_size = getattr(getattr(self._model, "encoder", None), "img_size", 1024)
1204        resize_model = ResizeLongestSideWrapper(self._model, img_size)
1205        resolved_devices = _resolve_devices(resize_model, self._inference_devices(devices))
1206
1207        if batch_size is None:
1208            model_devices = _prepare_models(resize_model, resolved_devices)
1209            patch_shape = tuple(block + 2 * overlap for block, overlap in zip(block_shape, block_halo))
1210            try:
1211                batch_sizes = _compute_auto_batch_sizes(
1212                    model_devices=model_devices,
1213                    n_jobs=n_blocks,
1214                    patch_shape=patch_shape,
1215                    in_channels=3,
1216                    # The synthetic input bypasses `_preprocess`, so clamp it into the asserted range.
1217                    prediction_function=_predict_probe,
1218                )
1219                batch_size = min(batch_sizes)
1220            finally:
1221                _release_model_replicas(model_devices)
1222        elif int(batch_size) < 1:
1223            raise ValueError(f"batch_size must be positive or None, got {batch_size}.")
1224
1225        with _bridge_halo_progress(pbar_update):
1226            output = predict_with_halo_pipelined(
1227                input_=input_,
1228                model=resize_model,
1229                block_shape=block_shape,
1230                halo=block_halo,
1231                preprocess=_preprocess,
1232                prediction_function=_predict,
1233                gpu_ids=resolved_devices,
1234                output=output,
1235                with_channels=True,
1236                batch_size=int(batch_size),
1237                num_prefetch_workers=num_prefetch_workers,
1238                num_write_workers=num_write_workers,
1239                disable_tqdm=pbar_update is not None,
1240            )
1241        if not is_3d:
1242            output = output[:, 0]
1243        return output
1244
1245    @torch.no_grad()
1246    def _run_decoder_2d(self, image_embeddings):
1247        """Run only the UniSAM2 decoder on precomputed 2d image embeddings (no encoder pass).
1248
1249        Reuses resize-longest 2d embeddings produced by `precompute_image_embeddings`. Returns the
1250        predictions stacked along the channel axis, shape (5, Y, X).
1251        """
1252        features = np.asarray(image_embeddings["features"])
1253        # A slice of 3d embeddings keeps a singleton batch axis: (1, 1, C, h, w) rather than (1, C, h, w).
1254        if features.ndim == 5 and features.shape[1] == 1:
1255            features = features[:, 0]
1256        if features.ndim != 4:
1257            raise ValueError(
1258                f"Decoder-from-embeddings requires 2d image embeddings (features with ndim 4), got {features.ndim}."
1259            )
1260        feature = torch.as_tensor(features, device=self._device).float()
1261        original_size = tuple(int(s) for s in np.array(image_embeddings["original_size"]).reshape(-1)[:2])
1262
1263        output = _decode_3d_feature_batch(self._model, feature.unsqueeze(1), original_size, self._device)
1264        return output[0, :, 0]
1265
1266    @torch.no_grad()
1267    def _run_decoder_3d(
1268        self, image_embeddings, z_block=None, z_halo=None, pbar_init=None, pbar_update=None,
1269        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1270    ):
1271        """Decode queued z blocks from precomputed 3d embeddings."""
1272        from micro_sam.v2.batched_inference import _decode_volume_embeddings
1273
1274        return _decode_volume_embeddings(
1275            model=self._model,
1276            image_embeddings=image_embeddings,
1277            z_block=z_block,
1278            z_halo=z_halo,
1279            pbar_init=pbar_init,
1280            pbar_update=pbar_update,
1281            batch_size=batch_size,
1282            devices=self._inference_devices(devices),
1283            num_prefetch_workers=num_prefetch_workers,
1284            num_write_workers=num_write_workers,
1285        )
1286
1287    @torch.no_grad()
1288    def initialize(
1289        self,
1290        image: np.ndarray,
1291        ndim: int,
1292        image_embeddings: Optional[dict] = None,
1293        i: Optional[int] = None,
1294        tile_shape: Optional[tuple] = None,
1295        halo: Optional[tuple] = None,
1296        pbar_init: Optional[callable] = None,
1297        pbar_update: Optional[callable] = None,
1298        batch_size: Optional[int] = 1,
1299        devices: Devices = None,
1300        num_prefetch_workers: int = 4,
1301        num_write_workers: int = 2,
1302        normalization: Optional[callable] = None,
1303    ) -> None:
1304        """Run the UniSAM2 inference and store foreground and distance predictions.
1305
1306        Args:
1307            image: The input image, shape (Y, X) for 2d or (Z, Y, X) for 3d.
1308            ndim: The number of spatial dimensions (2 or 3).
1309            image_embeddings: Optional precomputed image embeddings. If given, only the decoder runs.
1310            i: Index for the image data. Unused here, kept for interface compatibility.
1311            tile_shape: Unused for a 2d segmenter. For a 3d one, this segmenter is not itself tiled,
1312                but a volume is still chunked along z for memory - None for the default z chunk, or
1313                the full (z, y, x) to set it explicitly (the y, x entries are ignored: there is no
1314                in-plane tiling here).
1315            halo: Unused for a 2d segmenter; for a 3d one, matches `tile_shape` - only its z entry is
1316                used, as the halo of the z chunk above.
1317            normalization: Overrides the input normalization, which defaults to the 2nd / 98th percentile.
1318            pbar_init: Callback to initialize an external progress bar.
1319            pbar_update: Callback to update an external progress bar.
1320            batch_size: The batch size used when running inference for multiple z-blocks and / or tiles.
1321                Defaults to one; pass None for throughput-based automatic selection.
1322            devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA.
1323            num_prefetch_workers: Number of input reading and preprocessing threads.
1324            num_write_workers: Number of output writing threads.
1325        """
1326        if image_embeddings is not None and ndim == 3:
1327            n_slices = int(image_embeddings["features"].shape[0])
1328            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1329            self._prediction = self._run_decoder_3d(
1330                image_embeddings,
1331                z_block=z_block,
1332                z_halo=z_halo,
1333                pbar_init=pbar_init,
1334                pbar_update=pbar_update,
1335                batch_size=batch_size,
1336                devices=devices,
1337                num_prefetch_workers=num_prefetch_workers,
1338                num_write_workers=num_write_workers,
1339            )
1340        elif image_embeddings is not None:
1341            if pbar_init is not None:
1342                pbar_init(1, "Automatic segmentation")
1343            self._prediction = self._run_decoder_2d(image_embeddings)
1344            if pbar_update is not None:
1345                pbar_update(1)
1346        else:
1347            self._prediction = self._run_full_inference(
1348                image,
1349                ndim,
1350                pbar_init=pbar_init,
1351                pbar_update=pbar_update,
1352                batch_size=batch_size,
1353                devices=devices,
1354                num_prefetch_workers=num_prefetch_workers,
1355                num_write_workers=num_write_workers,
1356                normalization=normalization,
1357            )
1358        self._is_initialized = True
1359
1360    def generate(self, mode: str = "sparse", **kwargs) -> np.ndarray:
1361        """Convert the stored predictions into an instance segmentation.
1362
1363        Args:
1364            mode: The segmentation mode, 'sparse' (flow) or 'dense' (multicut).
1365            kwargs: Additional parameters forwarded to the postprocessing.
1366
1367        Returns:
1368            The instance segmentation, uint32 array.
1369        """
1370        if not self._is_initialized:
1371            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1372        kwargs.setdefault("model_type", self._model_type)
1373        return _segment_from_predictions(self._prediction, mode=mode, **kwargs)
1374
1375    def get_state(self) -> dict:
1376        """Return the cached decoder predictions so they can be serialized and later restored.
1377
1378        The state holds the (5, *spatial) foreground, directed-distance and boundary predictions. Restore it
1379        with `set_state` to skip the expensive decoder inference in `initialize`. It is independent
1380        of the post-processing parameters (those are applied in `generate`), so it is always reusable.
1381        """
1382        if not self._is_initialized:
1383            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
1384        return {"prediction": self._prediction}
1385
1386    def set_state(self, state: dict) -> None:
1387        """Restore the state produced by `get_state`, marking the segmenter initialized."""
1388        self._prediction = np.asarray(state["prediction"])
1389        self._is_initialized = True
1390
1391    def clear_state(self) -> None:
1392        """Clear the cached decoder predictions."""
1393        self._prediction = None
1394        self._is_initialized = False
1395
1396
1397class TiledUniSAM2InstanceSegmentation(UniSAM2InstanceSegmentation):
1398    """Generates a tiled instance segmentation with the UniSAM2 decoder (AIS).
1399
1400    Like `UniSAM2InstanceSegmentation`, but the model inference is tiled in-plane (xy) with a halo,
1401    and for a volume also chunked along z (see `initialize`).
1402
1403    Args:
1404        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
1405        device: The device to run inference on.
1406    """
1407
1408    @torch.no_grad()
1409    def _run_decoder_tiled_2d(
1410        self, image_embeddings, pbar_init=None, pbar_update=None,
1411        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1412    ):
1413        """Decode and stitch queued 2d embedding tiles."""
1414        from micro_sam.v2.batched_inference import _decode_tiled_2d_embeddings
1415
1416        return _decode_tiled_2d_embeddings(
1417            model=self._model,
1418            image_embeddings=image_embeddings,
1419            pbar_init=pbar_init,
1420            pbar_update=pbar_update,
1421            batch_size=batch_size,
1422            devices=self._inference_devices(devices),
1423            num_prefetch_workers=num_prefetch_workers,
1424            num_write_workers=num_write_workers,
1425        )
1426
1427    @torch.no_grad()
1428    def _run_decoder_tiled_3d(
1429        self, image_embeddings, pbar_init=None, pbar_update=None, z_block=None, z_halo=None,
1430        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1431    ):
1432        """Decode batches spanning tile columns and z blocks, then stitch them."""
1433        from micro_sam.v2.batched_inference import _decode_tiled_3d_embeddings
1434
1435        return _decode_tiled_3d_embeddings(
1436            model=self._model,
1437            image_embeddings=image_embeddings,
1438            pbar_init=pbar_init,
1439            pbar_update=pbar_update,
1440            z_block=z_block,
1441            z_halo=z_halo,
1442            batch_size=batch_size,
1443            devices=self._inference_devices(devices),
1444            num_prefetch_workers=num_prefetch_workers,
1445            num_write_workers=num_write_workers,
1446        )
1447
1448    @torch.no_grad()
1449    def _run_decoder_tiled_3d_slice(
1450        self, image_embeddings, i, pbar_init=None, pbar_update=None,
1451        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1452    ):
1453        """Decode one volume slice across all embedding tiles in batches."""
1454        from micro_sam.v2.batched_inference import _decode_tiled_3d_slice
1455
1456        return _decode_tiled_3d_slice(
1457            model=self._model,
1458            image_embeddings=image_embeddings,
1459            index=i,
1460            pbar_init=pbar_init,
1461            pbar_update=pbar_update,
1462            batch_size=batch_size,
1463            devices=self._inference_devices(devices),
1464            num_prefetch_workers=num_prefetch_workers,
1465            num_write_workers=num_write_workers,
1466        )
1467
1468    @torch.no_grad()
1469    def initialize(
1470        self,
1471        image: np.ndarray,
1472        ndim: int,
1473        tile_shape: Optional[tuple] = None,
1474        halo: Optional[tuple] = None,
1475        image_embeddings: Optional[dict] = None,
1476        i: Optional[int] = None,
1477        pbar_init: Optional[callable] = None,
1478        pbar_update: Optional[callable] = None,
1479        batch_size: Optional[int] = 1,
1480        devices: Devices = None,
1481        num_prefetch_workers: int = 4,
1482        num_write_workers: int = 2,
1483        normalization: Optional[callable] = None,
1484    ) -> None:
1485        """Run tiled UniSAM2 inference and store foreground and distance predictions.
1486
1487        `tile_shape`/`halo` are in-plane (y, x) for an image. For a volume they are always the full
1488        (z, y, x) / (z_halo, y_halo, x_halo): a volume is tiled in-plane and chunked along z, and
1489        `tile_shape`'s z entry sets that chunk (None keeps the library default). When precomputed
1490        `image_embeddings` are given, only the z entry is used - the in-plane tiling was fixed when
1491        the embeddings were computed and cannot change at decode time.
1492
1493        `batch_size=None` benchmarks candidate sizes and selects a throughput-efficient batch
1494        independently on each selected CUDA device.
1495        Reads and preprocessing are queued through `num_prefetch_workers`, output writes through
1496        `num_write_workers`. `normalization` overrides the per-tile input normalization, which
1497        defaults to the 2nd / 98th percentile.
1498        """
1499        decoder_kwargs = {
1500            "pbar_init": pbar_init,
1501            "pbar_update": pbar_update,
1502            "batch_size": batch_size,
1503            "devices": devices,
1504            "num_prefetch_workers": num_prefetch_workers,
1505            "num_write_workers": num_write_workers,
1506        }
1507        if image_embeddings is not None and ndim == 2 and "fpn" in image_embeddings and i is not None:
1508            self._prediction = self._run_decoder_tiled_3d_slice(
1509                image_embeddings, i, **decoder_kwargs,
1510            )
1511        elif image_embeddings is not None and ndim == 3:
1512            n_slices = int(np.asarray(image_embeddings["features"].attrs["shape"])[0])
1513            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1514            self._prediction = self._run_decoder_tiled_3d(
1515                image_embeddings, z_block=z_block, z_halo=z_halo, **decoder_kwargs,
1516            )
1517        elif image_embeddings is not None and ndim == 2:
1518            self._prediction = self._run_decoder_tiled_2d(image_embeddings, **decoder_kwargs)
1519        else:
1520            self._prediction = self._run_full_inference(
1521                image,
1522                ndim,
1523                tile_shape=tile_shape,
1524                halo=halo,
1525                pbar_init=pbar_init,
1526                pbar_update=pbar_update,
1527                batch_size=batch_size,
1528                devices=devices,
1529                num_prefetch_workers=num_prefetch_workers,
1530                num_write_workers=num_write_workers,
1531                normalization=normalization,
1532            )
1533        self._is_initialized = True
1534
1535
1536def get_unisam2_segmentation_generator(
1537    model: torch.nn.Module,
1538    is_tiled: bool = False,
1539    device: Optional[Union[str, torch.device]] = None,
1540    inference_device: Devices = USE_MODEL_DEVICE,
1541) -> UniSAM2InstanceSegmentation:
1542    """Get the UniSAM2 decoder-based (AIS) instance segmentation generator.
1543
1544    Args:
1545        model: The UniSAM2 model.
1546        is_tiled: Whether to use tiled inference.
1547        device: The device the model lives on.
1548        inference_device: The `devices=None` fallback (see `UniSAM2InstanceSegmentation`).
1549
1550    Returns:
1551        The instance segmentation generator, either `TiledUniSAM2InstanceSegmentation` (if tiled)
1552        or `UniSAM2InstanceSegmentation`.
1553    """
1554    cls = TiledUniSAM2InstanceSegmentation if is_tiled else UniSAM2InstanceSegmentation
1555    return cls(model, device=device, inference_device=inference_device)
1556
1557
1558def get_instance_segmentation_generator(
1559    model: Optional[torch.nn.Module] = None,
1560    decoder: Optional[torch.nn.Module] = None,
1561    is_tiled: bool = False,
1562    segmentation_mode: Optional[str] = None,
1563    device: Optional[Union[str, torch.device]] = None,
1564    inference_device: Devices = USE_MODEL_DEVICE,
1565    ndim: int = 2,
1566    **kwargs,
1567) -> AutoSegBase:
1568    """Get the automatic instance segmentation generator (AMG, AIS or APG), mirroring the v1 factory.
1569
1570    Args:
1571        model: The SAM2 model, required for the 'amg' and 'apg' modes. For volumetric APG this must
1572            be the SAM2 video predictor, which propagates the derived prompts through the volume.
1573        decoder: The UniSAM2 decoder model, required for the 'ais' and 'apg' modes.
1574        is_tiled: Whether to use the tiled segmenter.
1575        segmentation_mode: One of 'amg', 'ais' or 'apg'. By default 'ais' is used if a decoder is
1576            given, otherwise 'amg'.
1577        device: The device the model lives on ('ais' and 'apg' only).
1578        inference_device: The `devices=None` fallback ('ais' and 'apg' only, see
1579            `UniSAM2InstanceSegmentation`).
1580        ndim: The number of spatial dimensions. Only 'apg' has a separate volumetric segmenter; the
1581            other modes handle a volume in their front-end (see `automatic_instance_segmentation`).
1582        kwargs: Additional keyword arguments for the segmenter, e.g. 'beta' for tiled/blocked APG
1583            (see `TiledAutomaticPromptGenerator`).
1584
1585    Returns:
1586        The segmentation generator instance.
1587    """
1588    if segmentation_mode is None:
1589        segmentation_mode = DEFAULT_SEGMENTATION_MODE_WITH_DECODER if decoder is not None else "amg"
1590
1591    # Record what the generator was built from, so the tiled and non-tiled variants of the same
1592    # engine can be swapped without reloading the weights (see `retile_instance_segmentation_generator`).
1593    config = dict(
1594        model=model, decoder=decoder, is_tiled=is_tiled, segmentation_mode=segmentation_mode,
1595        device=device, inference_device=inference_device, ndim=ndim, **kwargs,
1596    )
1597    segmenter = _build_instance_segmentation_generator(
1598        model, decoder, is_tiled, segmentation_mode, device, inference_device, ndim, **kwargs
1599    )
1600    try:
1601        segmenter._generator_config = config
1602    except AttributeError:  # A generator that takes no attributes simply cannot be swapped.
1603        pass
1604    return segmenter
1605
1606
1607def retile_instance_segmentation_generator(segmenter: AutoSegBase, is_tiled: bool) -> AutoSegBase:
1608    """Return the same generator, or the other tiling variant of it, rebuilt from its build config.
1609
1610    The tiled and non-tiled generators are different classes, so a front-end that decides on tiling
1611    only once it has seen the image (see `micro_sam.v2.automatic_segmentation`) has to be able to
1612    swap them. The swap reuses the already loaded model and decoder, so it costs nothing but the
1613    wrapper, and the counterpart is cached on both objects so repeated swaps are free. A generator
1614    built by hand (without a config) is returned unchanged.
1615
1616    Args:
1617        segmenter: The automatic instance segmentation generator.
1618        is_tiled: Whether the returned generator should be the tiled one.
1619
1620    Returns:
1621        The generator matching `is_tiled`.
1622    """
1623    config = getattr(segmenter, "_generator_config", None)
1624    if config is None or bool(config["is_tiled"]) == bool(is_tiled):
1625        return segmenter
1626
1627    counterpart = getattr(segmenter, "_retiled_counterpart", None)
1628    if counterpart is None:
1629        counterpart = get_instance_segmentation_generator(**{**config, "is_tiled": is_tiled})
1630        segmenter._retiled_counterpart = counterpart
1631        counterpart._retiled_counterpart = segmenter
1632    return counterpart
1633
1634
1635def _build_instance_segmentation_generator(
1636    model, decoder, is_tiled, segmentation_mode, device, inference_device, ndim, **kwargs
1637):
1638    """Build the generator for one engine and tiling; see `get_instance_segmentation_generator`."""
1639    if segmentation_mode.lower() == "amg":
1640        if model is None:
1641            raise ValueError("The 'amg' segmentation mode requires a SAM2 'model'.")
1642        return get_amg_segmenter(model, is_tiled=is_tiled, **kwargs)
1643    elif segmentation_mode.lower() == "ais":
1644        if decoder is None:
1645            raise ValueError("The 'ais' segmentation mode requires a UniSAM2 'decoder'.")
1646        return get_unisam2_segmentation_generator(
1647            decoder, is_tiled=is_tiled, device=device, inference_device=inference_device,
1648        )
1649    elif segmentation_mode.lower() == "apg":
1650        # Imported here because the APG module builds on this one.
1651        from micro_sam.v2.automatic_prompt_generation import (
1652            AutomaticPromptGenerator, TiledAutomaticPromptGenerator,
1653        )
1654        from micro_sam.v2.util import get_sam2_image_predictor
1655
1656        if decoder is None:
1657            raise ValueError("The 'apg' segmentation mode requires a UniSAM2 'decoder'.")
1658        if model is None:
1659            raise ValueError(
1660                "The 'apg' segmentation mode requires a SAM2 'model', which it prompts to turn the "
1661                "decoder's candidates into masks."
1662            )
1663        if ndim == 3:
1664            # A volume is prompted through the video predictor, which propagates its prompts.
1665            cls = TiledAutomaticPromptGenerator if is_tiled else AutomaticPromptGenerator
1666            return cls(decoder, model, device=device, inference_device=inference_device, **kwargs)
1667        cls = TiledAutomaticPromptGenerator if is_tiled else AutomaticPromptGenerator
1668        return cls(
1669            decoder, get_sam2_image_predictor(model), device=device, inference_device=inference_device, **kwargs,
1670        )
1671    else:
1672        raise ValueError(
1673            f"Invalid segmentation_mode: {segmentation_mode}. Choose 'amg', 'ais' or 'apg'."
1674        )
DEFAULT_SEGMENTATION_MODE_WITH_DECODER = 'ais'
USE_MODEL_DEVICE = <object object>
class AutomaticMaskGenerationSegmenter(micro_sam.util.AutoSegBase):
117class AutomaticMaskGenerationSegmenter(AutoSegBase):
118    """Generates an instance segmentation for the SAM2 model using grid-based prompting (AMG).
119
120    Wraps the native `sam2.automatic_mask_generator.SAM2AutomaticMaskGenerator` and exposes the
121    same `initialize` / `generate` interface as the micro-sam v1 `AutomaticMaskGenerator`, so it
122    can be used both for single 2d images and, via `amg_3d_segmentation`, for 3d volumes.
123
124    The parameters that control the (expensive) mask prediction, e.g. `points_per_side` and the
125    quality thresholds, are passed to the constructor. The (cheap) conversion of the predicted
126    masks into an instance segmentation is controlled via `generate`.
127
128    The image embeddings are computed and cached via `micro_sam.v2.util.precompute_image_embeddings`
129    (or taken from precomputed embeddings passed to `initialize`, e.g. by the GUI) and set on the
130    predictor with `set_precomputed`, so the grid prediction reuses them instead of recomputing.
131
132    Use this class as follows:
133    ```python
134    segmenter = AutomaticMaskGenerationSegmenter(model)
135    segmenter.initialize(image)  # Run the grid prediction, this is the expensive computation.
136    masks = segmenter.generate(min_object_size=50)  # Convert to an instance segmentation, fast.
137    ```
138
139    Args:
140        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
141        model_type: The SAM2 model type, e.g. 'hvit_t'. Used to tag cached embeddings; only needed
142            when caching embeddings via `save_path`.
143        points_per_side: The number of points sampled along one side of the image. By default '32'.
144        points_per_batch: The number of points run simultaneously by the model. By default '64'.
145        pred_iou_thresh: Filter threshold in [0, 1] using the model's predicted mask quality.
146            By default '0.8'.
147        stability_score_thresh: Filter threshold in [0, 1] using the stability of the mask under
148            changes to the binarization cutoff. By default '0.9'. This is lower than SAM2's native
149            default of '0.95' because the embeddings here come from micro-sam's percentile-normalized
150            inputs, under which masks score marginally lower in stability.
151        kwargs: Additional keyword arguments forwarded to `SAM2AutomaticMaskGenerator`.
152    """
153
154    def __init__(
155        self,
156        model: torch.nn.Module,
157        model_type: Optional[str] = None,
158        points_per_side: Optional[int] = 32,
159        points_per_batch: int = 32,
160        pred_iou_thresh: float = 0.8,
161        stability_score_thresh: float = 0.9,
162        **kwargs,
163    ) -> None:
164        from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
165
166        # RLE masks, decoded one at a time by '_LazyRLEMask': holding every mask at full resolution
167        # runs a large image out of memory.
168        self._mask_generator = SAM2AutomaticMaskGenerator(
169            model=model,
170            points_per_side=points_per_side,
171            points_per_batch=points_per_batch,
172            pred_iou_thresh=pred_iou_thresh,
173            stability_score_thresh=stability_score_thresh,
174            output_mode="uncompressed_rle",
175            **kwargs,
176        )
177        # Use the shared resize-longest transform for AMG.
178        from micro_sam.v2.util import configure_image_predictor
179        configure_image_predictor(self._mask_generator.predictor)
180        # The embedding signature is keyed on these, which an image predictor does not carry itself.
181        predictor = self._mask_generator.predictor
182        predictor.model_type = model_type or getattr(model, "model_type", None) or "hvit"
183        predictor.model_name = model_type or getattr(model, "model_name", None) or predictor.model_type
184        # Baked into the masks by 'initialize', so a reused state can be validated against them.
185        self._amg_params = {
186            "points_per_side": points_per_side,
187            "pred_iou_thresh": pred_iou_thresh,
188            "stability_score_thresh": stability_score_thresh,
189            "model_type": predictor.model_type,
190        }
191        self._masks = None
192        self._original_size = None
193        self._is_initialized = False
194
195    def _generate_masks_for_shape(self, shape: Tuple[int, int]) -> List[Dict[str, Any]]:
196        """Run the grid-based mask prediction reusing the embeddings already set on the predictor.
197
198        The embeddings are expected to be set on `self._mask_generator.predictor` (via
199        `precompute_image_embeddings` or `set_precomputed`). We temporarily neutralize the
200        predictor's `set_image`, which the native mask generator calls once per crop, so that it
201        reuses the precomputed embeddings instead of recomputing them. This is only valid for the
202        single-crop case (`crop_n_layers=0`, the default). `shape` is the (Y, X) size the mask
203        generator should assume (the full image, or a single tile).
204        """
205        predictor = self._mask_generator.predictor
206        dummy = np.zeros((*shape, 3), dtype="uint8")
207        original_set_image = predictor.set_image
208        predictor.set_image = lambda *args, **kwargs: None
209        try:
210            masks = self._mask_generator.generate(dummy)
211        finally:
212            predictor.set_image = original_set_image
213        # Decoded only when read, so not every mask is held at full resolution.
214        return [_LazyRLEMask(mask) for mask in masks]
215
216    @torch.no_grad()
217    def initialize(
218        self,
219        image: np.ndarray,
220        image_embeddings: Optional[dict] = None,
221        i: Optional[int] = None,
222        save_path: Optional[str] = None,
223        verbose: bool = False,
224        pbar_init: Optional[callable] = None,
225        pbar_update: Optional[callable] = None,
226        **kwargs,
227    ) -> None:
228        """Run the grid-based mask prediction and store the resulting masks.
229
230        The image embeddings are computed (and cached if `save_path` is given) via
231        `micro_sam.v2.util.precompute_image_embeddings`, or taken from `image_embeddings` if
232        provided (e.g. by the GUI), and set on the predictor with `set_precomputed`. The grid
233        prediction then reuses these embeddings instead of recomputing them.
234
235        Args:
236            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). When `image_embeddings` is
237                given the image content is not used (only the precomputed embeddings are).
238            image_embeddings: Optional precomputed image embeddings. See `precompute_image_embeddings`.
239            i: Index for the image data. Only relevant for externally precomputed embeddings; for
240                a single 2d image (the per-slice case) it must be None.
241            save_path: Optional path to cache the computed embeddings in a zarr container.
242            verbose: Verbosity flag. By default 'False'.
243            pbar_init: Callback to initialize an external progress bar.
244            pbar_update: Callback to update an external progress bar.
245            kwargs: Additional arguments, ignored. Kept for interface compatibility.
246        """
247        predictor = self._mask_generator.predictor
248        if image_embeddings is None:
249            # Computes (or loads from save_path) the embeddings and sets them on the predictor.
250            precompute_image_embeddings(
251                predictor, image, save_path=save_path, ndim=2, verbose=verbose,
252                pbar_init=pbar_init, pbar_update=pbar_update,
253            )
254        elif "fpn" in image_embeddings and i is not None:
255            # Reconstruct slice 'i' from the 3d embeddings, without re-running the encoder.
256            _set_image_predictor_from_3d_embeddings(predictor, image_embeddings, i)
257        else:
258            set_precomputed(predictor, image_embeddings, i=i)
259
260        self._original_size = tuple(int(s) for s in predictor._orig_hw[0])
261        self._masks = self._generate_masks_for_shape(self._original_size)
262        self._is_initialized = True
263
264    def generate(
265        self,
266        min_object_size: int = 0,
267        max_object_size: Optional[int] = None,
268        with_background: bool = True,
269        output_mode: str = "instance_segmentation",
270    ) -> Union[List[Dict[str, Any]], np.ndarray]:
271        """Convert the predicted masks into an instance segmentation.
272
273        Args:
274            min_object_size: The minimal size of an object in pixels. By default '0'.
275            max_object_size: The maximal size of an object in pixels. By default 'None'.
276            with_background: Whether to remove the largest object, which often covers the
277                background for AMG. By default 'True'.
278            output_mode: The form masks are returned in. Either 'instance_segmentation' to return
279                a single label array, or 'binary_mask' to return the list of mask dictionaries.
280                By default 'instance_segmentation'.
281
282        Returns:
283            The instance segmentation as a uint32 array, or the list of mask dictionaries.
284        """
285        if not self._is_initialized:
286            raise RuntimeError(
287                "AutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
288            )
289        if output_mode != "instance_segmentation":
290            return self._masks
291        if len(self._masks) == 0:  # No masks were found.
292            return np.zeros(self._original_size, dtype="uint32")
293        # Smaller masks paint over larger ones, as in micro-sam v1 AMG. With exclusive merging, the mask that
294        # covers the whole image, which AMG always predicts, claims every pixel before the objects in it.
295        return mask_data_to_segmentation(
296            masks=self._masks,
297            shape=self._original_size,
298            min_object_size=min_object_size,
299            max_object_size=max_object_size,
300            with_background=with_background,
301            merge_exclusively=False,
302        )
303
304    def get_state(self) -> Dict[str, Any]:
305        """Return the cached mask-generation state so it can be serialized and later restored.
306
307        The state holds the predicted masks (as compact RLE dicts), the image size and the
308        parameters the masks were generated with (used to validate a reused state). Restore it
309        with `set_state` to skip the expensive grid prediction in `initialize`.
310        """
311        if not self._is_initialized:
312            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
313        return {
314            "masks": [dict(mask) for mask in self._masks],
315            "original_size": self._original_size,
316            "params": dict(self._amg_params),
317        }
318
319    def set_state(self, state: Dict[str, Any]) -> None:
320        """Restore the state produced by `get_state`, marking the segmenter initialized.
321
322        The masks are re-wrapped in `_LazyRLEMask` so `generate` decodes them lazily as before.
323        """
324        self._masks = [_LazyRLEMask(mask) for mask in state["masks"]]
325        self._original_size = tuple(int(s) for s in state["original_size"])
326        self._is_initialized = True
327
328    def clear_state(self) -> None:
329        """Clear the cached masks."""
330        self._masks = None
331        self._original_size = None
332        self._is_initialized = False

Generates an instance segmentation for the SAM2 model using grid-based prompting (AMG).

Wraps the native sam2.automatic_mask_generator.SAM2AutomaticMaskGenerator and exposes the same initialize / generate interface as the micro-sam v1 AutomaticMaskGenerator, so it can be used both for single 2d images and, via amg_3d_segmentation, for 3d volumes.

The parameters that control the (expensive) mask prediction, e.g. points_per_side and the quality thresholds, are passed to the constructor. The (cheap) conversion of the predicted masks into an instance segmentation is controlled via generate.

The image embeddings are computed and cached via micro_sam.v2.util.precompute_image_embeddings (or taken from precomputed embeddings passed to initialize, e.g. by the GUI) and set on the predictor with set_precomputed, so the grid prediction reuses them instead of recomputing.

Use this class as follows:

segmenter = AutomaticMaskGenerationSegmenter(model)
segmenter.initialize(image)  # Run the grid prediction, this is the expensive computation.
masks = segmenter.generate(min_object_size=50)  # Convert to an instance segmentation, fast.
Arguments:
  • model: The SAM2 model, loaded via micro_sam.v2.util.get_sam2_model.
  • model_type: The SAM2 model type, e.g. 'hvit_t'. Used to tag cached embeddings; only needed when caching embeddings via save_path.
  • points_per_side: The number of points sampled along one side of the image. By default '32'.
  • points_per_batch: The number of points run simultaneously by the model. By default '64'.
  • pred_iou_thresh: Filter threshold in [0, 1] using the model's predicted mask quality. By default '0.8'.
  • stability_score_thresh: Filter threshold in [0, 1] using the stability of the mask under changes to the binarization cutoff. By default '0.9'. This is lower than SAM2's native default of '0.95' because the embeddings here come from micro-sam's percentile-normalized inputs, under which masks score marginally lower in stability.
  • kwargs: Additional keyword arguments forwarded to SAM2AutomaticMaskGenerator.
AutomaticMaskGenerationSegmenter( model: torch.nn.modules.module.Module, model_type: Optional[str] = None, points_per_side: Optional[int] = 32, points_per_batch: int = 32, pred_iou_thresh: float = 0.8, stability_score_thresh: float = 0.9, **kwargs)
154    def __init__(
155        self,
156        model: torch.nn.Module,
157        model_type: Optional[str] = None,
158        points_per_side: Optional[int] = 32,
159        points_per_batch: int = 32,
160        pred_iou_thresh: float = 0.8,
161        stability_score_thresh: float = 0.9,
162        **kwargs,
163    ) -> None:
164        from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
165
166        # RLE masks, decoded one at a time by '_LazyRLEMask': holding every mask at full resolution
167        # runs a large image out of memory.
168        self._mask_generator = SAM2AutomaticMaskGenerator(
169            model=model,
170            points_per_side=points_per_side,
171            points_per_batch=points_per_batch,
172            pred_iou_thresh=pred_iou_thresh,
173            stability_score_thresh=stability_score_thresh,
174            output_mode="uncompressed_rle",
175            **kwargs,
176        )
177        # Use the shared resize-longest transform for AMG.
178        from micro_sam.v2.util import configure_image_predictor
179        configure_image_predictor(self._mask_generator.predictor)
180        # The embedding signature is keyed on these, which an image predictor does not carry itself.
181        predictor = self._mask_generator.predictor
182        predictor.model_type = model_type or getattr(model, "model_type", None) or "hvit"
183        predictor.model_name = model_type or getattr(model, "model_name", None) or predictor.model_type
184        # Baked into the masks by 'initialize', so a reused state can be validated against them.
185        self._amg_params = {
186            "points_per_side": points_per_side,
187            "pred_iou_thresh": pred_iou_thresh,
188            "stability_score_thresh": stability_score_thresh,
189            "model_type": predictor.model_type,
190        }
191        self._masks = None
192        self._original_size = None
193        self._is_initialized = False
@torch.no_grad()
def initialize( self, image: numpy.ndarray, image_embeddings: Optional[dict] = None, i: Optional[int] = None, save_path: Optional[str] = None, verbose: bool = False, pbar_init: Optional[<built-in function callable>] = None, pbar_update: Optional[<built-in function callable>] = None, **kwargs) -> None:
216    @torch.no_grad()
217    def initialize(
218        self,
219        image: np.ndarray,
220        image_embeddings: Optional[dict] = None,
221        i: Optional[int] = None,
222        save_path: Optional[str] = None,
223        verbose: bool = False,
224        pbar_init: Optional[callable] = None,
225        pbar_update: Optional[callable] = None,
226        **kwargs,
227    ) -> None:
228        """Run the grid-based mask prediction and store the resulting masks.
229
230        The image embeddings are computed (and cached if `save_path` is given) via
231        `micro_sam.v2.util.precompute_image_embeddings`, or taken from `image_embeddings` if
232        provided (e.g. by the GUI), and set on the predictor with `set_precomputed`. The grid
233        prediction then reuses these embeddings instead of recomputing them.
234
235        Args:
236            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). When `image_embeddings` is
237                given the image content is not used (only the precomputed embeddings are).
238            image_embeddings: Optional precomputed image embeddings. See `precompute_image_embeddings`.
239            i: Index for the image data. Only relevant for externally precomputed embeddings; for
240                a single 2d image (the per-slice case) it must be None.
241            save_path: Optional path to cache the computed embeddings in a zarr container.
242            verbose: Verbosity flag. By default 'False'.
243            pbar_init: Callback to initialize an external progress bar.
244            pbar_update: Callback to update an external progress bar.
245            kwargs: Additional arguments, ignored. Kept for interface compatibility.
246        """
247        predictor = self._mask_generator.predictor
248        if image_embeddings is None:
249            # Computes (or loads from save_path) the embeddings and sets them on the predictor.
250            precompute_image_embeddings(
251                predictor, image, save_path=save_path, ndim=2, verbose=verbose,
252                pbar_init=pbar_init, pbar_update=pbar_update,
253            )
254        elif "fpn" in image_embeddings and i is not None:
255            # Reconstruct slice 'i' from the 3d embeddings, without re-running the encoder.
256            _set_image_predictor_from_3d_embeddings(predictor, image_embeddings, i)
257        else:
258            set_precomputed(predictor, image_embeddings, i=i)
259
260        self._original_size = tuple(int(s) for s in predictor._orig_hw[0])
261        self._masks = self._generate_masks_for_shape(self._original_size)
262        self._is_initialized = True

Run the grid-based mask prediction and store the resulting masks.

The image embeddings are computed (and cached if save_path is given) via micro_sam.v2.util.precompute_image_embeddings, or taken from image_embeddings if provided (e.g. by the GUI), and set on the predictor with set_precomputed. The grid prediction then reuses these embeddings instead of recomputing them.

Arguments:
  • image: The input image, grayscale (Y, X) or RGB (Y, X, 3). When image_embeddings is given the image content is not used (only the precomputed embeddings are).
  • image_embeddings: Optional precomputed image embeddings. See precompute_image_embeddings.
  • i: Index for the image data. Only relevant for externally precomputed embeddings; for a single 2d image (the per-slice case) it must be None.
  • save_path: Optional path to cache the computed embeddings in a zarr container.
  • verbose: Verbosity flag. By default 'False'.
  • pbar_init: Callback to initialize an external progress bar.
  • pbar_update: Callback to update an external progress bar.
  • kwargs: Additional arguments, ignored. Kept for interface compatibility.
def generate( self, min_object_size: int = 0, max_object_size: Optional[int] = None, with_background: bool = True, output_mode: str = 'instance_segmentation') -> Union[List[Dict[str, Any]], numpy.ndarray]:
264    def generate(
265        self,
266        min_object_size: int = 0,
267        max_object_size: Optional[int] = None,
268        with_background: bool = True,
269        output_mode: str = "instance_segmentation",
270    ) -> Union[List[Dict[str, Any]], np.ndarray]:
271        """Convert the predicted masks into an instance segmentation.
272
273        Args:
274            min_object_size: The minimal size of an object in pixels. By default '0'.
275            max_object_size: The maximal size of an object in pixels. By default 'None'.
276            with_background: Whether to remove the largest object, which often covers the
277                background for AMG. By default 'True'.
278            output_mode: The form masks are returned in. Either 'instance_segmentation' to return
279                a single label array, or 'binary_mask' to return the list of mask dictionaries.
280                By default 'instance_segmentation'.
281
282        Returns:
283            The instance segmentation as a uint32 array, or the list of mask dictionaries.
284        """
285        if not self._is_initialized:
286            raise RuntimeError(
287                "AutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
288            )
289        if output_mode != "instance_segmentation":
290            return self._masks
291        if len(self._masks) == 0:  # No masks were found.
292            return np.zeros(self._original_size, dtype="uint32")
293        # Smaller masks paint over larger ones, as in micro-sam v1 AMG. With exclusive merging, the mask that
294        # covers the whole image, which AMG always predicts, claims every pixel before the objects in it.
295        return mask_data_to_segmentation(
296            masks=self._masks,
297            shape=self._original_size,
298            min_object_size=min_object_size,
299            max_object_size=max_object_size,
300            with_background=with_background,
301            merge_exclusively=False,
302        )

Convert the predicted masks into an instance segmentation.

Arguments:
  • min_object_size: The minimal size of an object in pixels. By default '0'.
  • max_object_size: The maximal size of an object in pixels. By default 'None'.
  • with_background: Whether to remove the largest object, which often covers the background for AMG. By default 'True'.
  • output_mode: The form masks are returned in. Either 'instance_segmentation' to return a single label array, or 'binary_mask' to return the list of mask dictionaries. By default 'instance_segmentation'.
Returns:

The instance segmentation as a uint32 array, or the list of mask dictionaries.

def get_state(self) -> Dict[str, Any]:
304    def get_state(self) -> Dict[str, Any]:
305        """Return the cached mask-generation state so it can be serialized and later restored.
306
307        The state holds the predicted masks (as compact RLE dicts), the image size and the
308        parameters the masks were generated with (used to validate a reused state). Restore it
309        with `set_state` to skip the expensive grid prediction in `initialize`.
310        """
311        if not self._is_initialized:
312            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
313        return {
314            "masks": [dict(mask) for mask in self._masks],
315            "original_size": self._original_size,
316            "params": dict(self._amg_params),
317        }

Return the cached mask-generation state so it can be serialized and later restored.

The state holds the predicted masks (as compact RLE dicts), the image size and the parameters the masks were generated with (used to validate a reused state). Restore it with set_state to skip the expensive grid prediction in initialize.

def set_state(self, state: Dict[str, Any]) -> None:
319    def set_state(self, state: Dict[str, Any]) -> None:
320        """Restore the state produced by `get_state`, marking the segmenter initialized.
321
322        The masks are re-wrapped in `_LazyRLEMask` so `generate` decodes them lazily as before.
323        """
324        self._masks = [_LazyRLEMask(mask) for mask in state["masks"]]
325        self._original_size = tuple(int(s) for s in state["original_size"])
326        self._is_initialized = True

Restore the state produced by get_state, marking the segmenter initialized.

The masks are re-wrapped in _LazyRLEMask so generate decodes them lazily as before.

def clear_state(self) -> None:
328    def clear_state(self) -> None:
329        """Clear the cached masks."""
330        self._masks = None
331        self._original_size = None
332        self._is_initialized = False

Clear the cached masks.

class TiledAutomaticMaskGenerationSegmenter(AutomaticMaskGenerationSegmenter):
335class TiledAutomaticMaskGenerationSegmenter(AutomaticMaskGenerationSegmenter):
336    """Generates a tiled instance segmentation for the SAM2 model using grid-based prompting (AMG).
337
338    Implements the same functionality as `AutomaticMaskGenerationSegmenter`, but the image is split
339    into tiles with a halo, AMG is run on each tile, and the per-tile instance segmentations are
340    stitched back into a single segmentation. This is the tiled backend used for large images (and
341    by the GUI). The `initialize` / `generate` interface matches the micro-sam v1
342    `TiledAutomaticMaskGenerator`.
343
344    Args:
345        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
346        kwargs: Additional keyword arguments for `AutomaticMaskGenerationSegmenter`.
347    """
348
349    @torch.no_grad()
350    def initialize(
351        self,
352        image: np.ndarray,
353        tile_shape: Optional[Tuple[int, int]] = None,
354        halo: Optional[Tuple[int, int]] = None,
355        image_embeddings: Optional[dict] = None,
356        i: Optional[int] = None,
357        save_path: Optional[str] = None,
358        verbose: bool = False,
359        pbar_init: Optional[callable] = None,
360        pbar_update: Optional[callable] = None,
361        **kwargs,
362    ) -> None:
363        """Run the grid-based mask prediction tile-by-tile and store the per-tile masks.
364
365        The tiled image embeddings are computed (and cached if `save_path` is given) via
366        `precompute_image_embeddings`, or taken from `image_embeddings` if provided (e.g. by the
367        GUI). The per-tile embeddings are then set on the predictor with `set_precomputed` and the
368        grid prediction reuses them. When embeddings are provided the tiling is taken from them.
369
370        Args:
371            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). Content unused when
372                `image_embeddings` is given.
373            tile_shape: The tile shape for the tiled prediction, (y, x). Taken from the embeddings
374                when `image_embeddings` is given.
375            halo: The overlap between the tiles, (y, x). Taken from the embeddings when given.
376            image_embeddings: Optional precomputed tiled image embeddings.
377            i: Index of the slice to segment if `image` has three spatial dimensions.
378            save_path: Optional path to cache the computed embeddings in a zarr container.
379            verbose: Verbosity flag. By default 'False'.
380            kwargs: Additional arguments, ignored. Kept for interface compatibility.
381        """
382        predictor = self._mask_generator.predictor
383        # Reconstruct slice 'i' per tile from the 3d embeddings, without re-running the encoder.
384        if image_embeddings is not None and "fpn" in image_embeddings and i is not None:
385            self._initialize_slice_from_3d_embeddings(image_embeddings, i)
386            return
387
388        temporary_embedding_path = None
389        self._is_initialized = False
390        try:
391            if image_embeddings is None:
392                if tile_shape is None or halo is None:
393                    raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled segmenter.")
394                if image.ndim == 3 and image.shape[-1] != 3 and i is not None:
395                    image = image[i]
396                effective_save_path = save_path
397                if effective_save_path is None:
398                    temporary_embedding_path = make_temp_embedding_path()
399                    effective_save_path = temporary_embedding_path
400                image_embeddings = precompute_image_embeddings(
401                    predictor, image, save_path=effective_save_path, ndim=2, tile_shape=tile_shape, halo=halo,
402                    verbose=verbose, lazy_loading=True,
403                )
404
405            self._initialize_from_tiled_embeddings(
406                predictor, image_embeddings, verbose, pbar_init, pbar_update,
407            )
408        finally:
409            if temporary_embedding_path is not None:
410                try:
411                    if image_embeddings is not None:
412                        image_embeddings.close()
413                finally:
414                    image_embeddings = None
415                    shutil.rmtree(temporary_embedding_path, ignore_errors=True)
416
417    def _initialize_from_tiled_embeddings(
418        self, predictor, image_embeddings, verbose, pbar_init, pbar_update,
419    ) -> None:
420        """Run per-tile AMG from embeddings that remain valid for the duration of this call."""
421        feats = image_embeddings["features"]
422        tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"])
423        halo = tuple(int(s) for s in feats.attrs["halo"])
424        self._original_size = tuple(int(s) for s in feats.attrs["shape"])
425        self._tile_shape = tile_shape
426        self._tiling = Blocking([0, 0], list(self._original_size), list(tile_shape))
427        self._halo = tuple(halo)
428
429        from micro_sam.util import handle_pbar
430        _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update)
431
432        self._masks = []
433        n_tiles = self._tiling.number_of_blocks
434        pbar_init(n_tiles, "Automatic segmentation (tiles)")
435        try:
436            for tile_id in range(n_tiles):
437                block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
438                set_precomputed(predictor, image_embeddings, tile_id=tile_id)
439                tile_size = tuple(end - begin for begin, end in zip(block.begin, block.end))
440                self._masks.append(self._generate_masks_for_shape(tile_size))
441                pbar_update(1)
442        finally:
443            pbar_close()
444
445        self._is_initialized = True
446
447    def _initialize_slice_from_3d_embeddings(self, image_embeddings, i):
448        """Run the tiled AMG for slice ``i`` reusing precomputed 3d (video-style) tiled embeddings.
449
450        Each tile's image features for slice ``i`` are reconstructed from the per-tile ``fpn``/``pos_enc``
451        (no encoder pass), the grid prediction is run per tile, and the per-tile masks are stitched
452        in-plane by `generate`. The tiling is taken from the embeddings; the z axis is not tiled.
453        """
454        predictor = self._mask_generator.predictor
455        feats = image_embeddings["features"]
456        full_shape = tuple(int(s) for s in feats.attrs["shape"])  # (Z, Y, X)
457        tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"])
458        halo = tuple(int(s) for s in feats.attrs["halo"])
459        self._original_size = full_shape[1:]  # in-plane (Y, X); z is not tiled
460        self._tile_shape = tile_shape
461        self._tiling = Blocking([0, 0], list(self._original_size), list(tile_shape))
462        self._halo = halo
463
464        self._masks = []
465        for tile_id in range(self._tiling.number_of_blocks):
466            block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
467            # Lazy, so only slice 'i' is read rather than the tile's whole z-stack on every slice.
468            fpn_tile = _load_list_datasets(image_embeddings["fpn"], str(tile_id), lazy_loading=True)
469            pos_tile = _load_list_datasets(image_embeddings["pos_enc"], str(tile_id), lazy_loading=True)
470            original_size = feats[str(tile_id)].attrs["original_size"]
471            _set_image_predictor_from_backbone(
472                predictor, fpn_tile, pos_tile, feats[str(tile_id)], original_size, i
473            )
474            tile_size = tuple(end - begin for begin, end in zip(block.begin, block.end))
475            self._masks.append(self._generate_masks_for_shape(tile_size))
476
477        self._is_initialized = True
478
479    def generate(
480        self,
481        min_object_size: int = 0,
482        max_object_size: Optional[int] = None,
483        with_background: bool = True,
484        output_mode: str = "instance_segmentation",
485    ) -> np.ndarray:
486        """Convert the per-tile masks into an instance segmentation and stitch the tiles.
487
488        Args:
489            min_object_size: The minimal size of an object in pixels. By default '0'.
490            max_object_size: The maximal size of an object in pixels. By default 'None'.
491            with_background: Whether to remove the largest object per tile. By default 'True'.
492            output_mode: The form masks are returned in. Only 'instance_segmentation' is supported
493                for the tiled segmenter. By default 'instance_segmentation'.
494
495        Returns:
496            The stitched instance segmentation as a uint32 array.
497        """
498        if not self._is_initialized:
499            raise RuntimeError(
500                "TiledAutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
501            )
502        if output_mode != "instance_segmentation":
503            raise ValueError("The tiled segmenter only supports output_mode='instance_segmentation'.")
504
505        segmentation = np.zeros(self._original_size, dtype="uint32")
506        offset = 0
507        for tile_id, masks in enumerate(self._masks):
508            block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
509            bb = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end))
510            tile_shape = tuple(end - begin for begin, end in zip(block.begin, block.end))
511
512            if len(masks) == 0:
513                continue
514            this_seg = mask_data_to_segmentation(
515                masks=masks,
516                shape=tile_shape,
517                min_object_size=min_object_size,
518                max_object_size=max_object_size,
519                with_background=with_background,
520                merge_exclusively=False,
521            )
522
523            # Offset the per-tile instance ids so that they stay unique across tiles.
524            max_id = int(this_seg.max())
525            if max_id == 0:
526                continue
527            this_seg[this_seg != 0] += offset
528            offset += max_id
529
530            if tile_id == 0:
531                segmentation[bb] = this_seg
532            else:
533                segmentation[bb] = _merge_segmentations(this_seg, segmentation[bb])
534
535        return segmentation
536
537    def get_state(self) -> Dict[str, Any]:
538        """Return the cached per-tile mask state, plus the tiling needed to restore it."""
539        if not self._is_initialized:
540            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
541        return {
542            "masks": [[dict(mask) for mask in tile_masks] for tile_masks in self._masks],
543            "original_size": self._original_size,
544            "tile_shape": self._tile_shape,
545            "halo": self._halo,
546            "params": dict(self._amg_params),
547        }
548
549    def set_state(self, state: Dict[str, Any]) -> None:
550        """Restore the per-tile masks and rebuild the tiling from `get_state`."""
551        self._masks = [[_LazyRLEMask(mask) for mask in tile_masks] for tile_masks in state["masks"]]
552        self._original_size = tuple(int(s) for s in state["original_size"])
553        self._tile_shape = tuple(int(s) for s in state["tile_shape"])
554        self._halo = tuple(int(s) for s in state["halo"])
555        self._tiling = Blocking([0, 0], list(self._original_size), list(self._tile_shape))
556        self._is_initialized = True

Generates a tiled instance segmentation for the SAM2 model using grid-based prompting (AMG).

Implements the same functionality as AutomaticMaskGenerationSegmenter, but the image is split into tiles with a halo, AMG is run on each tile, and the per-tile instance segmentations are stitched back into a single segmentation. This is the tiled backend used for large images (and by the GUI). The initialize / generate interface matches the micro-sam v1 TiledAutomaticMaskGenerator.

Arguments:
@torch.no_grad()
def initialize( self, image: numpy.ndarray, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, image_embeddings: Optional[dict] = None, i: Optional[int] = None, save_path: Optional[str] = None, verbose: bool = False, pbar_init: Optional[<built-in function callable>] = None, pbar_update: Optional[<built-in function callable>] = None, **kwargs) -> None:
349    @torch.no_grad()
350    def initialize(
351        self,
352        image: np.ndarray,
353        tile_shape: Optional[Tuple[int, int]] = None,
354        halo: Optional[Tuple[int, int]] = None,
355        image_embeddings: Optional[dict] = None,
356        i: Optional[int] = None,
357        save_path: Optional[str] = None,
358        verbose: bool = False,
359        pbar_init: Optional[callable] = None,
360        pbar_update: Optional[callable] = None,
361        **kwargs,
362    ) -> None:
363        """Run the grid-based mask prediction tile-by-tile and store the per-tile masks.
364
365        The tiled image embeddings are computed (and cached if `save_path` is given) via
366        `precompute_image_embeddings`, or taken from `image_embeddings` if provided (e.g. by the
367        GUI). The per-tile embeddings are then set on the predictor with `set_precomputed` and the
368        grid prediction reuses them. When embeddings are provided the tiling is taken from them.
369
370        Args:
371            image: The input image, grayscale (Y, X) or RGB (Y, X, 3). Content unused when
372                `image_embeddings` is given.
373            tile_shape: The tile shape for the tiled prediction, (y, x). Taken from the embeddings
374                when `image_embeddings` is given.
375            halo: The overlap between the tiles, (y, x). Taken from the embeddings when given.
376            image_embeddings: Optional precomputed tiled image embeddings.
377            i: Index of the slice to segment if `image` has three spatial dimensions.
378            save_path: Optional path to cache the computed embeddings in a zarr container.
379            verbose: Verbosity flag. By default 'False'.
380            kwargs: Additional arguments, ignored. Kept for interface compatibility.
381        """
382        predictor = self._mask_generator.predictor
383        # Reconstruct slice 'i' per tile from the 3d embeddings, without re-running the encoder.
384        if image_embeddings is not None and "fpn" in image_embeddings and i is not None:
385            self._initialize_slice_from_3d_embeddings(image_embeddings, i)
386            return
387
388        temporary_embedding_path = None
389        self._is_initialized = False
390        try:
391            if image_embeddings is None:
392                if tile_shape is None or halo is None:
393                    raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled segmenter.")
394                if image.ndim == 3 and image.shape[-1] != 3 and i is not None:
395                    image = image[i]
396                effective_save_path = save_path
397                if effective_save_path is None:
398                    temporary_embedding_path = make_temp_embedding_path()
399                    effective_save_path = temporary_embedding_path
400                image_embeddings = precompute_image_embeddings(
401                    predictor, image, save_path=effective_save_path, ndim=2, tile_shape=tile_shape, halo=halo,
402                    verbose=verbose, lazy_loading=True,
403                )
404
405            self._initialize_from_tiled_embeddings(
406                predictor, image_embeddings, verbose, pbar_init, pbar_update,
407            )
408        finally:
409            if temporary_embedding_path is not None:
410                try:
411                    if image_embeddings is not None:
412                        image_embeddings.close()
413                finally:
414                    image_embeddings = None
415                    shutil.rmtree(temporary_embedding_path, ignore_errors=True)

Run the grid-based mask prediction tile-by-tile and store the per-tile masks.

The tiled image embeddings are computed (and cached if save_path is given) via precompute_image_embeddings, or taken from image_embeddings if provided (e.g. by the GUI). The per-tile embeddings are then set on the predictor with set_precomputed and the grid prediction reuses them. When embeddings are provided the tiling is taken from them.

Arguments:
  • image: The input image, grayscale (Y, X) or RGB (Y, X, 3). Content unused when image_embeddings is given.
  • tile_shape: The tile shape for the tiled prediction, (y, x). Taken from the embeddings when image_embeddings is given.
  • halo: The overlap between the tiles, (y, x). Taken from the embeddings when given.
  • image_embeddings: Optional precomputed tiled image embeddings.
  • i: Index of the slice to segment if image has three spatial dimensions.
  • save_path: Optional path to cache the computed embeddings in a zarr container.
  • verbose: Verbosity flag. By default 'False'.
  • kwargs: Additional arguments, ignored. Kept for interface compatibility.
def generate( self, min_object_size: int = 0, max_object_size: Optional[int] = None, with_background: bool = True, output_mode: str = 'instance_segmentation') -> numpy.ndarray:
479    def generate(
480        self,
481        min_object_size: int = 0,
482        max_object_size: Optional[int] = None,
483        with_background: bool = True,
484        output_mode: str = "instance_segmentation",
485    ) -> np.ndarray:
486        """Convert the per-tile masks into an instance segmentation and stitch the tiles.
487
488        Args:
489            min_object_size: The minimal size of an object in pixels. By default '0'.
490            max_object_size: The maximal size of an object in pixels. By default 'None'.
491            with_background: Whether to remove the largest object per tile. By default 'True'.
492            output_mode: The form masks are returned in. Only 'instance_segmentation' is supported
493                for the tiled segmenter. By default 'instance_segmentation'.
494
495        Returns:
496            The stitched instance segmentation as a uint32 array.
497        """
498        if not self._is_initialized:
499            raise RuntimeError(
500                "TiledAutomaticMaskGenerationSegmenter has not been initialized. Call initialize first."
501            )
502        if output_mode != "instance_segmentation":
503            raise ValueError("The tiled segmenter only supports output_mode='instance_segmentation'.")
504
505        segmentation = np.zeros(self._original_size, dtype="uint32")
506        offset = 0
507        for tile_id, masks in enumerate(self._masks):
508            block = self._tiling.get_block_with_halo(tile_id, list(self._halo)).outer_block
509            bb = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end))
510            tile_shape = tuple(end - begin for begin, end in zip(block.begin, block.end))
511
512            if len(masks) == 0:
513                continue
514            this_seg = mask_data_to_segmentation(
515                masks=masks,
516                shape=tile_shape,
517                min_object_size=min_object_size,
518                max_object_size=max_object_size,
519                with_background=with_background,
520                merge_exclusively=False,
521            )
522
523            # Offset the per-tile instance ids so that they stay unique across tiles.
524            max_id = int(this_seg.max())
525            if max_id == 0:
526                continue
527            this_seg[this_seg != 0] += offset
528            offset += max_id
529
530            if tile_id == 0:
531                segmentation[bb] = this_seg
532            else:
533                segmentation[bb] = _merge_segmentations(this_seg, segmentation[bb])
534
535        return segmentation

Convert the per-tile masks into an instance segmentation and stitch the tiles.

Arguments:
  • min_object_size: The minimal size of an object in pixels. By default '0'.
  • max_object_size: The maximal size of an object in pixels. By default 'None'.
  • with_background: Whether to remove the largest object per tile. By default 'True'.
  • output_mode: The form masks are returned in. Only 'instance_segmentation' is supported for the tiled segmenter. By default 'instance_segmentation'.
Returns:

The stitched instance segmentation as a uint32 array.

def get_state(self) -> Dict[str, Any]:
537    def get_state(self) -> Dict[str, Any]:
538        """Return the cached per-tile mask state, plus the tiling needed to restore it."""
539        if not self._is_initialized:
540            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
541        return {
542            "masks": [[dict(mask) for mask in tile_masks] for tile_masks in self._masks],
543            "original_size": self._original_size,
544            "tile_shape": self._tile_shape,
545            "halo": self._halo,
546            "params": dict(self._amg_params),
547        }

Return the cached per-tile mask state, plus the tiling needed to restore it.

def set_state(self, state: Dict[str, Any]) -> None:
549    def set_state(self, state: Dict[str, Any]) -> None:
550        """Restore the per-tile masks and rebuild the tiling from `get_state`."""
551        self._masks = [[_LazyRLEMask(mask) for mask in tile_masks] for tile_masks in state["masks"]]
552        self._original_size = tuple(int(s) for s in state["original_size"])
553        self._tile_shape = tuple(int(s) for s in state["tile_shape"])
554        self._halo = tuple(int(s) for s in state["halo"])
555        self._tiling = Blocking([0, 0], list(self._original_size), list(self._tile_shape))
556        self._is_initialized = True

Restore the per-tile masks and rebuild the tiling from get_state.

def get_amg_segmenter( model: torch.nn.modules.module.Module, is_tiled: bool = False, **kwargs) -> AutomaticMaskGenerationSegmenter:
559def get_amg_segmenter(
560    model: torch.nn.Module, is_tiled: bool = False, **kwargs
561) -> AutomaticMaskGenerationSegmenter:
562    """Get the SAM2 automatic mask generation segmenter.
563
564    Args:
565        model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`.
566        is_tiled: Whether to use the tiled segmenter for large images. By default 'False'.
567        kwargs: Additional keyword arguments for the segmenter.
568
569    Returns:
570        The automatic mask generation segmenter, either `TiledAutomaticMaskGenerationSegmenter`
571        (if tiled) or `AutomaticMaskGenerationSegmenter`.
572    """
573    if is_tiled:
574        return TiledAutomaticMaskGenerationSegmenter(model, **kwargs)
575    return AutomaticMaskGenerationSegmenter(model, **kwargs)

Get the SAM2 automatic mask generation segmenter.

Arguments:
  • model: The SAM2 model, loaded via micro_sam.v2.util.get_sam2_model.
  • is_tiled: Whether to use the tiled segmenter for large images. By default 'False'.
  • kwargs: Additional keyword arguments for the segmenter.
Returns:

The automatic mask generation segmenter, either TiledAutomaticMaskGenerationSegmenter (if tiled) or AutomaticMaskGenerationSegmenter.

def amg_3d_segmentation( volume: numpy.ndarray, segmenter: AutomaticMaskGenerationSegmenter, with_background: bool = True, gap_closing: Optional[int] = None, min_z_extent: Optional[int] = None, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, image_embeddings: Optional[dict] = None, state_save_path: Optional[str] = None, verbose: bool = True, pbar_init: Optional[<built-in function callable>] = None, pbar_update: Optional[<built-in function callable>] = None, **kwargs) -> numpy.ndarray:
578def amg_3d_segmentation(
579    volume: np.ndarray,
580    segmenter: AutomaticMaskGenerationSegmenter,
581    with_background: bool = True,
582    gap_closing: Optional[int] = None,
583    min_z_extent: Optional[int] = None,
584    tile_shape: Optional[Tuple[int, int]] = None,
585    halo: Optional[Tuple[int, int]] = None,
586    image_embeddings: Optional[dict] = None,
587    state_save_path: Optional[str] = None,
588    verbose: bool = True,
589    pbar_init: Optional[callable] = None,
590    pbar_update: Optional[callable] = None,
591    **kwargs,
592) -> np.ndarray:
593    """Automatically segment objects in a volume with the SAM2 mask generator.
594
595    Segments each slice individually in 2d with AMG and then merges the slices across z based on
596    the overlap of objects between adjacent slices, using the multi-dimensional segmentation
597    stitching (`merge_instance_segmentation_3d`). When `tile_shape` and `halo` are given, the
598    per-slice AMG is run with the tiled segmenter.
599
600    Args:
601        volume: The input volume, shape (Z, Y, X), or (Z, Y, X, C) with a trailing channel axis.
602        segmenter: The automatic mask generation segmenter. Use a
603            `TiledAutomaticMaskGenerationSegmenter` together with `tile_shape` and `halo`.
604        with_background: Whether the segmentation has background. By default 'True'.
605        gap_closing: If given, gaps in the segmentation are closed with a binary closing operation.
606            The value is the number of iterations for the closing. By default 'None'.
607        min_z_extent: Require a minimal extent in z for the segmented objects. This can help to
608            prevent segmentation artifacts. By default 'None'.
609        tile_shape: The tile shape for the tiled per-slice prediction, (y, x). By default 'None'.
610        halo: The overlap between the tiles, (y, x). By default 'None'.
611        image_embeddings: Optional precomputed 3d (video-style) embeddings for the volume. When given
612            (and not tiled), each slice's AMG reuses the precomputed features instead of re-encoding.
613        state_save_path: Optional path to the embedding Zarr in which to cache the per-slice
614            grid-prediction state. When set, a slice reuses its cached state instead of re-running
615            the grid prediction; freshly computed slices are written back.
616        verbose: Verbosity flag. By default 'True'.
617        pbar_init: Callback to initialize an external progress bar, called with the number of slices.
618        pbar_update: Callback to update an external progress bar, called once per segmented slice.
619        kwargs: Keyword arguments for the 'generate' method of the segmenter.
620
621    Returns:
622        The 3d instance segmentation, uint32 array of shape (Z, Y, X).
623    """
624    if volume.ndim not in (3, 4):
625        raise ValueError(f"Expected a 3d volume of shape (Z, Y, X) or (Z, Y, X, C), got shape {volume.shape}.")
626
627    init_kwargs = {}
628    if tile_shape is not None and halo is not None:
629        init_kwargs = {"tile_shape": tile_shape, "halo": halo}
630    # The segmenter reconstructs each slice's features from the 3d embeddings, so nothing re-encodes.
631    reuse_embeddings = image_embeddings is not None
632
633    from micro_sam.util import handle_pbar
634    _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update)
635    pbar_init(volume.shape[0], "Automatic segmentation (slices)")
636
637    def init_slice(i):
638        if reuse_embeddings:
639            segmenter.initialize(volume[i], image_embeddings=image_embeddings, i=i, verbose=False, **init_kwargs)
640        else:
641            segmenter.initialize(volume[i], verbose=False, **init_kwargs)
642
643    if state_save_path is not None:
644        from micro_sam.precompute_state import _cache_amg_slice, _embedding_signature
645        state_signature = _embedding_signature(state_save_path)
646
647    segmentation = np.zeros(volume.shape[:3], dtype="uint32")
648    offset = 0
649    for i in range(volume.shape[0]):
650        if state_save_path is not None:
651            _cache_amg_slice(segmenter, state_save_path, i, init_slice, embedding_signature=state_signature)
652        else:
653            init_slice(i)
654        seg = segmenter.generate(**kwargs)
655
656        # Offset the per-slice instance ids so that they are unique across the whole volume.
657        max_z = int(seg.max())
658        if max_z != 0:
659            seg[seg != 0] += offset
660            offset += max_z
661            segmentation[i] = seg
662        pbar_update(1)
663    pbar_close()
664
665    segmentation = merge_instance_segmentation_3d(
666        segmentation,
667        beta=0.5,
668        with_background=with_background,
669        gap_closing=gap_closing,
670        min_z_extent=min_z_extent,
671        verbose=verbose,
672    )
673    return segmentation

Automatically segment objects in a volume with the SAM2 mask generator.

Segments each slice individually in 2d with AMG and then merges the slices across z based on the overlap of objects between adjacent slices, using the multi-dimensional segmentation stitching (merge_instance_segmentation_3d). When tile_shape and halo are given, the per-slice AMG is run with the tiled segmenter.

Arguments:
  • volume: The input volume, shape (Z, Y, X), or (Z, Y, X, C) with a trailing channel axis.
  • segmenter: The automatic mask generation segmenter. Use a TiledAutomaticMaskGenerationSegmenter together with tile_shape and halo.
  • with_background: Whether the segmentation has background. By default 'True'.
  • gap_closing: If given, gaps in the segmentation are closed with a binary closing operation. The value is the number of iterations for the closing. By default 'None'.
  • min_z_extent: Require a minimal extent in z for the segmented objects. This can help to prevent segmentation artifacts. By default 'None'.
  • tile_shape: The tile shape for the tiled per-slice prediction, (y, x). By default 'None'.
  • halo: The overlap between the tiles, (y, x). By default 'None'.
  • image_embeddings: Optional precomputed 3d (video-style) embeddings for the volume. When given (and not tiled), each slice's AMG reuses the precomputed features instead of re-encoding.
  • state_save_path: Optional path to the embedding Zarr in which to cache the per-slice grid-prediction state. When set, a slice reuses its cached state instead of re-running the grid prediction; freshly computed slices are written back.
  • verbose: Verbosity flag. By default 'True'.
  • pbar_init: Callback to initialize an external progress bar, called with the number of slices.
  • pbar_update: Callback to update an external progress bar, called once per segmented slice.
  • kwargs: Keyword arguments for the 'generate' method of the segmenter.
Returns:

The 3d instance segmentation, uint32 array of shape (Z, Y, X).

CONFIGURABLE_DECODER_WIDTH_VERSION = '0.10.3'
class NoDecoderError(builtins.ValueError):
739class NoDecoderError(ValueError):
740    """The checkpoint has no decoder, because the model was trained for interactive segmentation only."""
741
742    def __init__(self, checkpoint_path):
743        super().__init__(
744            f"The checkpoint '{checkpoint_path}' has no decoder for automatic segmentation, because the model was "
745            "trained for interactive segmentation only. Automatic segmentation is not available with it. "
746            "Train the model with 'train_automatic' or with joint training to get a decoder."
747        )

The checkpoint has no decoder, because the model was trained for interactive segmentation only.

NoDecoderError(checkpoint_path)
742    def __init__(self, checkpoint_path):
743        super().__init__(
744            f"The checkpoint '{checkpoint_path}' has no decoder for automatic segmentation, because the model was "
745            "trained for interactive segmentation only. Automatic segmentation is not available with it. "
746            "Train the model with 'train_automatic' or with joint training to get a decoder."
747        )
def find_decoder_checkpoint(checkpoint_path):
750def find_decoder_checkpoint(checkpoint_path):
751    """Find the decoder file that belongs to a model file.
752
753    The decoder file is next to the model file and has the name of the model file with '_decoder' added,
754    for example 'hvit_t_cells_decoder.pt' for 'hvit_t_cells.pt' or 'hvit_t_cells_decoder' for 'hvit_t_cells'.
755
756    Args:
757        checkpoint_path: The path of the model file.
758
759    Returns:
760        The path of the decoder file, or None if there is no decoder file.
761    """
762    path = Path(checkpoint_path)
763    candidates = [path.with_name(f"{path.stem}_decoder{path.suffix}"), path.with_name(f"{path.stem}_decoder.pt")]
764    if path.suffix:
765        candidates.append(path.with_name(f"{path.stem}_decoder"))
766    return next((str(candidate) for candidate in candidates if candidate.is_file()), None)

Find the decoder file that belongs to a model file.

The decoder file is next to the model file and has the name of the model file with '_decoder' added, for example 'hvit_t_cells_decoder.pt' for 'hvit_t_cells.pt' or 'hvit_t_cells_decoder' for 'hvit_t_cells'.

Arguments:
  • checkpoint_path: The path of the model file.
Returns:

The path of the decoder file, or None if there is no decoder file.

def get_unisam2_model( checkpoint_path, device=None, encoder='hvit_t', peft_kwargs=None, encoder_model_type=None):
769def get_unisam2_model(
770    checkpoint_path, device=None, encoder=DEFAULT_BASE_MODEL, peft_kwargs=None, encoder_model_type=None
771):
772    """Load a UniSAM2 model for automatic segmentation from a checkpoint.
773
774    Args:
775        checkpoint_path: Path to the UniSAM2 checkpoint.
776        device: The device to load the model onto.
777        encoder: The SAM2 encoder to build the decoder on. Either the backbone name to build from
778            scratch, e.g. 'hvit_t', or a prebuilt SAM2 image-encoder module to reuse (which avoids
779            rebuilding / downloading the base backbone). Its weights are (re)defined by the checkpoint.
780        peft_kwargs: The arguments for `PEFT_Sam2`. The function uses the saved arguments by default.
781        encoder_model_type: The SAM2 model type for a prebuilt PEFT encoder. You must set this argument for modules.
782
783    Returns:
784        The UniSAM2 model in eval mode.
785
786    Raises:
787        NoDecoderError: If the checkpoint has no decoder, because it was trained for interactive segmentation only.
788    """
789    from micro_sam.v2.models.util import UniSAM2, read_unisam2_state
790
791    # Captured before 'encoder' is reassigned to the built PEFT module below.
792    resolved_model_type = encoder if isinstance(encoder, str) else encoder_model_type
793
794    device = "cpu" if device is None else device
795    state = load_checkpoint(checkpoint_path, map_location=device)
796    model_state = read_unisam2_state(state)
797    if model_state is None:
798        raise NoDecoderError(checkpoint_path)
799
800    if peft_kwargs is None and isinstance(state, dict) and state.get("peft_kwargs") is not None:
801        from micro_sam.v2.models.peft_sam2 import PEFT_MODULES
802        from micro_sam.models.peft import deserialize_peft_kwargs
803
804        peft_kwargs = deserialize_peft_kwargs(state["peft_kwargs"], PEFT_MODULES)
805
806    is_qlora = bool(peft_kwargs and peft_kwargs.get("quantize", False))
807    # A prebuilt encoder with the PEFT layers of the checkpoint is reused, so that no base backbone is built.
808    if peft_kwargs and not is_qlora and isinstance(encoder, torch.nn.Module):
809        encoder_keys = {"encoder.inner." + k for k in encoder.state_dict()}
810        if encoder_keys == {k for k in model_state if k.startswith("encoder.inner.")}:
811            peft_kwargs = None
812    if peft_kwargs:
813        from micro_sam.v2.util import get_sam2_model
814        from micro_sam.v2.models.peft_sam2 import PEFT_Sam2
815
816        peft_kwargs = {k: v for k, v in peft_kwargs.items() if k != "quantize"}
817        base_model_type = encoder if isinstance(encoder, str) else encoder_model_type
818        if base_model_type is None:
819            raise ValueError("Set 'encoder_model_type' when you pass a prebuilt PEFT encoder.")
820        sam2_model = get_sam2_model(model_type=base_model_type, input_type="images", device=device)
821        sam2_model = PEFT_Sam2(sam2_model, **peft_kwargs).sam
822        encoder = sam2_model.image_encoder
823
824    # Neither the decoder width nor the channel count is recorded in the checkpoint, so read both off 'out_conv'.
825    output_channels, initial_features = model_state["out_conv.weight"].shape[:2]
826    if output_channels != UNISAM2_OUTPUT_CHANNELS:
827        raise ValueError(
828            f"The decoder predicts {output_channels} channels, but only decoders with {UNISAM2_OUTPUT_CHANNELS} "
829            "output channels (foreground, three directed distances, boundary) are supported."
830        )
831
832    model = UniSAM2(encoder=encoder, output_channels=output_channels, initial_features=initial_features, device=device)
833    _check_decoder_width(model, initial_features)
834    if peft_kwargs and is_qlora:
835        model_state = _convert_automatic_qlora_state(model, model_state)
836    model.load_state_dict(model_state)
837
838    model.eval()
839    model.model_type = resolved_model_type
840    return model

Load a UniSAM2 model for automatic segmentation from a checkpoint.

Arguments:
  • checkpoint_path: Path to the UniSAM2 checkpoint.
  • device: The device to load the model onto.
  • encoder: The SAM2 encoder to build the decoder on. Either the backbone name to build from scratch, e.g. 'hvit_t', or a prebuilt SAM2 image-encoder module to reuse (which avoids rebuilding / downloading the base backbone). Its weights are (re)defined by the checkpoint.
  • peft_kwargs: The arguments for PEFT_Sam2. The function uses the saved arguments by default.
  • encoder_model_type: The SAM2 model type for a prebuilt PEFT encoder. You must set this argument for modules.
Returns:

The UniSAM2 model in eval mode.

Raises:
  • NoDecoderError: If the checkpoint has no decoder, because it was trained for interactive segmentation only.
def get_decoder(model_type, checkpoint=None, device=None, encoder=None):
843def get_decoder(model_type, checkpoint=None, device=None, encoder=None):
844    """Resolve and load the UniSAM2 decoder for a SAM2 model.
845
846    The decoder is provided either by an explicit `checkpoint` or by a finetuned model with a
847    registered decoder (e.g. 'hvit_t_cells'). Mirrors the micro-sam v1 `get_decoder`.
848    If `checkpoint` has no decoder, the decoder file next to it is used, see `find_decoder_checkpoint`.
849
850    Args:
851        model_type: The SAM2 model. A finetuned model with a registered decoder, or a base backbone
852            combined with `checkpoint`.
853        checkpoint: Optional path to a decoder checkpoint to build the UniSAM2 decoder from. This can also be
854            a joint checkpoint, or a model file with its decoder file next to it.
855        device: The device to load the decoder onto.
856        encoder: Optional prebuilt SAM2 image-encoder module to build the decoder on, reused instead
857            of rebuilding the base backbone (its weights are redefined by the checkpoint's strict
858            load). By default the base backbone name (first 6 chars of `model_type`) is used.
859
860    Returns:
861        The UniSAM2 decoder model.
862
863    Raises:
864        NoDecoderError: If `checkpoint` has no decoder and there is no decoder file next to it.
865    """
866    from micro_sam.v2.util import FINETUNED_MODELS, has_registered_decoder, _download_finetuned_sam2_model
867
868    # Without a prebuilt encoder, build on the base backbone name, e.g. 'hvit_t_cells' -> 'hvit_t'.
869    if encoder is None:
870        encoder = model_type[:6]
871    if checkpoint is not None:
872        decoder_source = checkpoint
873    elif model_type in FINETUNED_MODELS and has_registered_decoder(model_type):
874        _, _, decoder_source = _download_finetuned_sam2_model(model_type)
875    else:
876        raise ValueError(
877            f"Automatic segmentation with SAM2 requires a finetuned model with a registered decoder "
878            f"or a decoder checkpoint. '{model_type}' provides neither."
879        )
880
881    def _load(source):
882        return get_unisam2_model(source, device=device, encoder=encoder, encoder_model_type=model_type[:6])
883
884    try:
885        decoder = _load(decoder_source)
886    except NoDecoderError:
887        decoder_source = None if checkpoint is None else find_decoder_checkpoint(checkpoint)
888        if decoder_source is None:
889            raise
890        decoder = _load(decoder_source)
891    # The defaults are looked up by the family of the full name.
892    decoder.model_type = model_type
893    return decoder

Resolve and load the UniSAM2 decoder for a SAM2 model.

The decoder is provided either by an explicit checkpoint or by a finetuned model with a registered decoder (e.g. 'hvit_t_cells'). Mirrors the micro-sam v1 get_decoder. If checkpoint has no decoder, the decoder file next to it is used, see find_decoder_checkpoint.

Arguments:
  • model_type: The SAM2 model. A finetuned model with a registered decoder, or a base backbone combined with checkpoint.
  • checkpoint: Optional path to a decoder checkpoint to build the UniSAM2 decoder from. This can also be a joint checkpoint, or a model file with its decoder file next to it.
  • device: The device to load the decoder onto.
  • encoder: Optional prebuilt SAM2 image-encoder module to build the decoder on, reused instead of rebuilding the base backbone (its weights are redefined by the checkpoint's strict load). By default the base backbone name (first 6 chars of model_type) is used.
Returns:

The UniSAM2 decoder model.

Raises:
  • NoDecoderError: If checkpoint has no decoder and there is no decoder file next to it.
class ResizeLongestSideWrapper(torch.nn.modules.module.Module):
904class ResizeLongestSideWrapper(torch.nn.Module):
905    """Run UniSAM2 with resize-longest and bottom/right padding."""
906
907    def __init__(self, model: torch.nn.Module, img_size: int) -> None:
908        super().__init__()
909        self.model = model
910        self.img_size = img_size
911
912    def forward(self, x: torch.Tensor) -> torch.Tensor:
913        from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_tensor
914
915        spatial = x.shape[-2:]
916        x, resized = resize_longest_side_and_pad_tensor(x, self.img_size)
917        out = self.model(x)
918        out = out[..., :resized[0], :resized[1]]
919        return _resize_spatial(out, spatial)

Run UniSAM2 with resize-longest and bottom/right padding.

ResizeLongestSideWrapper(model: torch.nn.modules.module.Module, img_size: int)
907    def __init__(self, model: torch.nn.Module, img_size: int) -> None:
908        super().__init__()
909        self.model = model
910        self.img_size = img_size

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

model
img_size
def forward(self, x: torch.Tensor) -> torch.Tensor:
912    def forward(self, x: torch.Tensor) -> torch.Tensor:
913        from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_tensor
914
915        spatial = x.shape[-2:]
916        x, resized = resize_longest_side_and_pad_tensor(x, self.img_size)
917        out = self.model(x)
918        out = out[..., :resized[0], :resized[1]]
919        return _resize_spatial(out, spatial)

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.

class UniSAM2InstanceSegmentation(micro_sam.util.AutoSegBase):
1115class UniSAM2InstanceSegmentation(AutoSegBase):
1116    """Generates an instance segmentation with the UniSAM2 decoder (AIS).
1117
1118    A concrete `AutoSegBase` (like `AutomaticMaskGenerationSegmenter`), but predicts the segmentation
1119    with the UniSAM2 decoder instead of grid prompts. All UniSAM2 inference is encapsulated here (the
1120    only way to run it). Use it as follows:
1121    ```python
1122    segmenter = UniSAM2InstanceSegmentation(model)
1123    segmenter.initialize(image, ndim=2)  # Run the UniSAM2 inference.
1124    masks = segmenter.generate(mode="sparse", foreground_threshold=0.6)  # Post-process.
1125    ```
1126
1127    Args:
1128        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
1129        device: The device the model lives on (used for the non-tiled 2d decoder).
1130        inference_device: The device intent used as the `devices=None` fallback. Defaults to the
1131            model device (single GPU); pass None to fan out over all visible GPUs, or a device / list.
1132    """
1133
1134    _is_decoder_based = True
1135    _precompute_embeddings_in_frontend = True
1136
1137    def __init__(
1138        self,
1139        model: torch.nn.Module,
1140        device: Optional[Union[str, torch.device]] = None,
1141        inference_device: Devices = USE_MODEL_DEVICE,
1142    ) -> None:
1143        self._model = model
1144        # 'model_type' can be unset on a manually assembled module; the postprocessing defaults need
1145        # a concrete backbone to look up, so fall back to the single-source default rather than None.
1146        self._model_type = getattr(model, "model_type", None) or DEFAULT_BASE_MODEL
1147        self._device = device
1148        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
1149        self._prediction = None
1150        self._is_initialized = False
1151
1152    def _inference_devices(self, devices: Devices) -> Devices:
1153        """Resolve the inference devices, falling back to the configured device intent."""
1154        return devices if devices is not None else self._inference_device
1155
1156    def _run_full_inference(
1157        self, raw, ndim, tile_shape=None, halo=None, pbar_init=None, pbar_update=None,
1158        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1159        normalization=None,
1160    ):
1161        """Run queued, batched UniSAM2 encoder and decoder inference.
1162
1163        Tiled reads and preprocessing, GPU inference, and output writes overlap through the torch-em
1164        prediction pipeline. If `batch_size` is None, candidate sizes are benchmarked and a
1165        throughput-efficient batch is selected independently on every CUDA device. `normalization`
1166        overrides the per-block input normalization, which defaults to the 2nd / 98th percentile.
1167        """
1168        from torch_em.util.prediction import predict_with_halo_pipelined
1169        from micro_sam.v2.normalization import normalize_raw
1170        from micro_sam.v2.batched_inference import (
1171            _compute_auto_batch_sizes, _prepare_models, _release_model_replicas, _resolve_devices,
1172        )
1173
1174        def _normalize(crop):
1175            if normalization is None:
1176                return normalize_raw(crop, axis=(-2, -1))
1177            return normalization(crop)
1178
1179        def _preprocess(crop):
1180            return np.concatenate([_normalize(crop)] * 3, axis=0)
1181
1182        def _predict(this_model, inputs):
1183            # The pipeline writes numpy blocks, which have no bfloat16.
1184            with autocast(inputs.device):
1185                return to_float32(this_model(inputs))
1186
1187        def _predict_probe(this_model, inputs):
1188            return _predict(this_model, inputs.clamp(0.0, 1.0))
1189
1190        is_3d = ndim == 3
1191        block_shape, block_halo = _block_shape_and_halo(tuple(raw.shape), ndim, tile_shape, halo)
1192        n_blocks = _n_blocks(tuple(raw.shape), ndim, block_shape)
1193        if pbar_init is not None:
1194            desc = "Automatic segmentation (volume)" if is_3d else "Automatic segmentation"
1195            pbar_init(n_blocks, desc)
1196
1197        if is_3d:
1198            input_ = raw[np.newaxis].astype("float32")
1199            output = np.zeros((UNISAM2_OUTPUT_CHANNELS, *raw.shape), dtype="float32")
1200        else:
1201            input_ = raw[np.newaxis, np.newaxis].astype("float32")
1202            output = np.zeros((UNISAM2_OUTPUT_CHANNELS, 1, *raw.shape), dtype="float32")
1203
1204        img_size = getattr(getattr(self._model, "encoder", None), "img_size", 1024)
1205        resize_model = ResizeLongestSideWrapper(self._model, img_size)
1206        resolved_devices = _resolve_devices(resize_model, self._inference_devices(devices))
1207
1208        if batch_size is None:
1209            model_devices = _prepare_models(resize_model, resolved_devices)
1210            patch_shape = tuple(block + 2 * overlap for block, overlap in zip(block_shape, block_halo))
1211            try:
1212                batch_sizes = _compute_auto_batch_sizes(
1213                    model_devices=model_devices,
1214                    n_jobs=n_blocks,
1215                    patch_shape=patch_shape,
1216                    in_channels=3,
1217                    # The synthetic input bypasses `_preprocess`, so clamp it into the asserted range.
1218                    prediction_function=_predict_probe,
1219                )
1220                batch_size = min(batch_sizes)
1221            finally:
1222                _release_model_replicas(model_devices)
1223        elif int(batch_size) < 1:
1224            raise ValueError(f"batch_size must be positive or None, got {batch_size}.")
1225
1226        with _bridge_halo_progress(pbar_update):
1227            output = predict_with_halo_pipelined(
1228                input_=input_,
1229                model=resize_model,
1230                block_shape=block_shape,
1231                halo=block_halo,
1232                preprocess=_preprocess,
1233                prediction_function=_predict,
1234                gpu_ids=resolved_devices,
1235                output=output,
1236                with_channels=True,
1237                batch_size=int(batch_size),
1238                num_prefetch_workers=num_prefetch_workers,
1239                num_write_workers=num_write_workers,
1240                disable_tqdm=pbar_update is not None,
1241            )
1242        if not is_3d:
1243            output = output[:, 0]
1244        return output
1245
1246    @torch.no_grad()
1247    def _run_decoder_2d(self, image_embeddings):
1248        """Run only the UniSAM2 decoder on precomputed 2d image embeddings (no encoder pass).
1249
1250        Reuses resize-longest 2d embeddings produced by `precompute_image_embeddings`. Returns the
1251        predictions stacked along the channel axis, shape (5, Y, X).
1252        """
1253        features = np.asarray(image_embeddings["features"])
1254        # A slice of 3d embeddings keeps a singleton batch axis: (1, 1, C, h, w) rather than (1, C, h, w).
1255        if features.ndim == 5 and features.shape[1] == 1:
1256            features = features[:, 0]
1257        if features.ndim != 4:
1258            raise ValueError(
1259                f"Decoder-from-embeddings requires 2d image embeddings (features with ndim 4), got {features.ndim}."
1260            )
1261        feature = torch.as_tensor(features, device=self._device).float()
1262        original_size = tuple(int(s) for s in np.array(image_embeddings["original_size"]).reshape(-1)[:2])
1263
1264        output = _decode_3d_feature_batch(self._model, feature.unsqueeze(1), original_size, self._device)
1265        return output[0, :, 0]
1266
1267    @torch.no_grad()
1268    def _run_decoder_3d(
1269        self, image_embeddings, z_block=None, z_halo=None, pbar_init=None, pbar_update=None,
1270        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1271    ):
1272        """Decode queued z blocks from precomputed 3d embeddings."""
1273        from micro_sam.v2.batched_inference import _decode_volume_embeddings
1274
1275        return _decode_volume_embeddings(
1276            model=self._model,
1277            image_embeddings=image_embeddings,
1278            z_block=z_block,
1279            z_halo=z_halo,
1280            pbar_init=pbar_init,
1281            pbar_update=pbar_update,
1282            batch_size=batch_size,
1283            devices=self._inference_devices(devices),
1284            num_prefetch_workers=num_prefetch_workers,
1285            num_write_workers=num_write_workers,
1286        )
1287
1288    @torch.no_grad()
1289    def initialize(
1290        self,
1291        image: np.ndarray,
1292        ndim: int,
1293        image_embeddings: Optional[dict] = None,
1294        i: Optional[int] = None,
1295        tile_shape: Optional[tuple] = None,
1296        halo: Optional[tuple] = None,
1297        pbar_init: Optional[callable] = None,
1298        pbar_update: Optional[callable] = None,
1299        batch_size: Optional[int] = 1,
1300        devices: Devices = None,
1301        num_prefetch_workers: int = 4,
1302        num_write_workers: int = 2,
1303        normalization: Optional[callable] = None,
1304    ) -> None:
1305        """Run the UniSAM2 inference and store foreground and distance predictions.
1306
1307        Args:
1308            image: The input image, shape (Y, X) for 2d or (Z, Y, X) for 3d.
1309            ndim: The number of spatial dimensions (2 or 3).
1310            image_embeddings: Optional precomputed image embeddings. If given, only the decoder runs.
1311            i: Index for the image data. Unused here, kept for interface compatibility.
1312            tile_shape: Unused for a 2d segmenter. For a 3d one, this segmenter is not itself tiled,
1313                but a volume is still chunked along z for memory - None for the default z chunk, or
1314                the full (z, y, x) to set it explicitly (the y, x entries are ignored: there is no
1315                in-plane tiling here).
1316            halo: Unused for a 2d segmenter; for a 3d one, matches `tile_shape` - only its z entry is
1317                used, as the halo of the z chunk above.
1318            normalization: Overrides the input normalization, which defaults to the 2nd / 98th percentile.
1319            pbar_init: Callback to initialize an external progress bar.
1320            pbar_update: Callback to update an external progress bar.
1321            batch_size: The batch size used when running inference for multiple z-blocks and / or tiles.
1322                Defaults to one; pass None for throughput-based automatic selection.
1323            devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA.
1324            num_prefetch_workers: Number of input reading and preprocessing threads.
1325            num_write_workers: Number of output writing threads.
1326        """
1327        if image_embeddings is not None and ndim == 3:
1328            n_slices = int(image_embeddings["features"].shape[0])
1329            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1330            self._prediction = self._run_decoder_3d(
1331                image_embeddings,
1332                z_block=z_block,
1333                z_halo=z_halo,
1334                pbar_init=pbar_init,
1335                pbar_update=pbar_update,
1336                batch_size=batch_size,
1337                devices=devices,
1338                num_prefetch_workers=num_prefetch_workers,
1339                num_write_workers=num_write_workers,
1340            )
1341        elif image_embeddings is not None:
1342            if pbar_init is not None:
1343                pbar_init(1, "Automatic segmentation")
1344            self._prediction = self._run_decoder_2d(image_embeddings)
1345            if pbar_update is not None:
1346                pbar_update(1)
1347        else:
1348            self._prediction = self._run_full_inference(
1349                image,
1350                ndim,
1351                pbar_init=pbar_init,
1352                pbar_update=pbar_update,
1353                batch_size=batch_size,
1354                devices=devices,
1355                num_prefetch_workers=num_prefetch_workers,
1356                num_write_workers=num_write_workers,
1357                normalization=normalization,
1358            )
1359        self._is_initialized = True
1360
1361    def generate(self, mode: str = "sparse", **kwargs) -> np.ndarray:
1362        """Convert the stored predictions into an instance segmentation.
1363
1364        Args:
1365            mode: The segmentation mode, 'sparse' (flow) or 'dense' (multicut).
1366            kwargs: Additional parameters forwarded to the postprocessing.
1367
1368        Returns:
1369            The instance segmentation, uint32 array.
1370        """
1371        if not self._is_initialized:
1372            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1373        kwargs.setdefault("model_type", self._model_type)
1374        return _segment_from_predictions(self._prediction, mode=mode, **kwargs)
1375
1376    def get_state(self) -> dict:
1377        """Return the cached decoder predictions so they can be serialized and later restored.
1378
1379        The state holds the (5, *spatial) foreground, directed-distance and boundary predictions. Restore it
1380        with `set_state` to skip the expensive decoder inference in `initialize`. It is independent
1381        of the post-processing parameters (those are applied in `generate`), so it is always reusable.
1382        """
1383        if not self._is_initialized:
1384            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
1385        return {"prediction": self._prediction}
1386
1387    def set_state(self, state: dict) -> None:
1388        """Restore the state produced by `get_state`, marking the segmenter initialized."""
1389        self._prediction = np.asarray(state["prediction"])
1390        self._is_initialized = True
1391
1392    def clear_state(self) -> None:
1393        """Clear the cached decoder predictions."""
1394        self._prediction = None
1395        self._is_initialized = False

Generates an instance segmentation with the UniSAM2 decoder (AIS).

A concrete AutoSegBase (like AutomaticMaskGenerationSegmenter), but predicts the segmentation with the UniSAM2 decoder instead of grid prompts. All UniSAM2 inference is encapsulated here (the only way to run it). Use it as follows:

segmenter = UniSAM2InstanceSegmentation(model)
segmenter.initialize(image, ndim=2)  # Run the UniSAM2 inference.
masks = segmenter.generate(mode="sparse", foreground_threshold=0.6)  # Post-process.
Arguments:
  • model: The UniSAM2 model (see get_unisam2_model / get_decoder).
  • device: The device the model lives on (used for the non-tiled 2d decoder).
  • inference_device: The device intent used as the devices=None fallback. Defaults to the model device (single GPU); pass None to fan out over all visible GPUs, or a device / list.
UniSAM2InstanceSegmentation( model: torch.nn.modules.module.Module, device: Union[str, torch.device, NoneType] = None, inference_device: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = <object object>)
1137    def __init__(
1138        self,
1139        model: torch.nn.Module,
1140        device: Optional[Union[str, torch.device]] = None,
1141        inference_device: Devices = USE_MODEL_DEVICE,
1142    ) -> None:
1143        self._model = model
1144        # 'model_type' can be unset on a manually assembled module; the postprocessing defaults need
1145        # a concrete backbone to look up, so fall back to the single-source default rather than None.
1146        self._model_type = getattr(model, "model_type", None) or DEFAULT_BASE_MODEL
1147        self._device = device
1148        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
1149        self._prediction = None
1150        self._is_initialized = False
@torch.no_grad()
def initialize( self, image: numpy.ndarray, ndim: int, image_embeddings: Optional[dict] = None, i: Optional[int] = None, tile_shape: Optional[tuple] = None, halo: Optional[tuple] = None, pbar_init: Optional[<built-in function callable>] = None, pbar_update: Optional[<built-in function callable>] = None, batch_size: Optional[int] = 1, devices: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = None, num_prefetch_workers: int = 4, num_write_workers: int = 2, normalization: Optional[<built-in function callable>] = None) -> None:
1288    @torch.no_grad()
1289    def initialize(
1290        self,
1291        image: np.ndarray,
1292        ndim: int,
1293        image_embeddings: Optional[dict] = None,
1294        i: Optional[int] = None,
1295        tile_shape: Optional[tuple] = None,
1296        halo: Optional[tuple] = None,
1297        pbar_init: Optional[callable] = None,
1298        pbar_update: Optional[callable] = None,
1299        batch_size: Optional[int] = 1,
1300        devices: Devices = None,
1301        num_prefetch_workers: int = 4,
1302        num_write_workers: int = 2,
1303        normalization: Optional[callable] = None,
1304    ) -> None:
1305        """Run the UniSAM2 inference and store foreground and distance predictions.
1306
1307        Args:
1308            image: The input image, shape (Y, X) for 2d or (Z, Y, X) for 3d.
1309            ndim: The number of spatial dimensions (2 or 3).
1310            image_embeddings: Optional precomputed image embeddings. If given, only the decoder runs.
1311            i: Index for the image data. Unused here, kept for interface compatibility.
1312            tile_shape: Unused for a 2d segmenter. For a 3d one, this segmenter is not itself tiled,
1313                but a volume is still chunked along z for memory - None for the default z chunk, or
1314                the full (z, y, x) to set it explicitly (the y, x entries are ignored: there is no
1315                in-plane tiling here).
1316            halo: Unused for a 2d segmenter; for a 3d one, matches `tile_shape` - only its z entry is
1317                used, as the halo of the z chunk above.
1318            normalization: Overrides the input normalization, which defaults to the 2nd / 98th percentile.
1319            pbar_init: Callback to initialize an external progress bar.
1320            pbar_update: Callback to update an external progress bar.
1321            batch_size: The batch size used when running inference for multiple z-blocks and / or tiles.
1322                Defaults to one; pass None for throughput-based automatic selection.
1323            devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA.
1324            num_prefetch_workers: Number of input reading and preprocessing threads.
1325            num_write_workers: Number of output writing threads.
1326        """
1327        if image_embeddings is not None and ndim == 3:
1328            n_slices = int(image_embeddings["features"].shape[0])
1329            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1330            self._prediction = self._run_decoder_3d(
1331                image_embeddings,
1332                z_block=z_block,
1333                z_halo=z_halo,
1334                pbar_init=pbar_init,
1335                pbar_update=pbar_update,
1336                batch_size=batch_size,
1337                devices=devices,
1338                num_prefetch_workers=num_prefetch_workers,
1339                num_write_workers=num_write_workers,
1340            )
1341        elif image_embeddings is not None:
1342            if pbar_init is not None:
1343                pbar_init(1, "Automatic segmentation")
1344            self._prediction = self._run_decoder_2d(image_embeddings)
1345            if pbar_update is not None:
1346                pbar_update(1)
1347        else:
1348            self._prediction = self._run_full_inference(
1349                image,
1350                ndim,
1351                pbar_init=pbar_init,
1352                pbar_update=pbar_update,
1353                batch_size=batch_size,
1354                devices=devices,
1355                num_prefetch_workers=num_prefetch_workers,
1356                num_write_workers=num_write_workers,
1357                normalization=normalization,
1358            )
1359        self._is_initialized = True

Run the UniSAM2 inference and store foreground and distance predictions.

Arguments:
  • image: The input image, shape (Y, X) for 2d or (Z, Y, X) for 3d.
  • ndim: The number of spatial dimensions (2 or 3).
  • image_embeddings: Optional precomputed image embeddings. If given, only the decoder runs.
  • i: Index for the image data. Unused here, kept for interface compatibility.
  • tile_shape: Unused for a 2d segmenter. For a 3d one, this segmenter is not itself tiled, but a volume is still chunked along z for memory - None for the default z chunk, or the full (z, y, x) to set it explicitly (the y, x entries are ignored: there is no in-plane tiling here).
  • halo: Unused for a 2d segmenter; for a 3d one, matches tile_shape - only its z entry is used, as the halo of the z chunk above.
  • normalization: Overrides the input normalization, which defaults to the 2nd / 98th percentile.
  • pbar_init: Callback to initialize an external progress bar.
  • pbar_update: Callback to update an external progress bar.
  • batch_size: The batch size used when running inference for multiple z-blocks and / or tiles. Defaults to one; pass None for throughput-based automatic selection.
  • devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA.
  • num_prefetch_workers: Number of input reading and preprocessing threads.
  • num_write_workers: Number of output writing threads.
def generate(self, mode: str = 'sparse', **kwargs) -> numpy.ndarray:
1361    def generate(self, mode: str = "sparse", **kwargs) -> np.ndarray:
1362        """Convert the stored predictions into an instance segmentation.
1363
1364        Args:
1365            mode: The segmentation mode, 'sparse' (flow) or 'dense' (multicut).
1366            kwargs: Additional parameters forwarded to the postprocessing.
1367
1368        Returns:
1369            The instance segmentation, uint32 array.
1370        """
1371        if not self._is_initialized:
1372            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1373        kwargs.setdefault("model_type", self._model_type)
1374        return _segment_from_predictions(self._prediction, mode=mode, **kwargs)

Convert the stored predictions into an instance segmentation.

Arguments:
  • mode: The segmentation mode, 'sparse' (flow) or 'dense' (multicut).
  • kwargs: Additional parameters forwarded to the postprocessing.
Returns:

The instance segmentation, uint32 array.

def get_state(self) -> dict:
1376    def get_state(self) -> dict:
1377        """Return the cached decoder predictions so they can be serialized and later restored.
1378
1379        The state holds the (5, *spatial) foreground, directed-distance and boundary predictions. Restore it
1380        with `set_state` to skip the expensive decoder inference in `initialize`. It is independent
1381        of the post-processing parameters (those are applied in `generate`), so it is always reusable.
1382        """
1383        if not self._is_initialized:
1384            raise RuntimeError("Cannot get the state before you initialize the segmenter.")
1385        return {"prediction": self._prediction}

Return the cached decoder predictions so they can be serialized and later restored.

The state holds the (5, *spatial) foreground, directed-distance and boundary predictions. Restore it with set_state to skip the expensive decoder inference in initialize. It is independent of the post-processing parameters (those are applied in generate), so it is always reusable.

def set_state(self, state: dict) -> None:
1387    def set_state(self, state: dict) -> None:
1388        """Restore the state produced by `get_state`, marking the segmenter initialized."""
1389        self._prediction = np.asarray(state["prediction"])
1390        self._is_initialized = True

Restore the state produced by get_state, marking the segmenter initialized.

def clear_state(self) -> None:
1392    def clear_state(self) -> None:
1393        """Clear the cached decoder predictions."""
1394        self._prediction = None
1395        self._is_initialized = False

Clear the cached decoder predictions.

class TiledUniSAM2InstanceSegmentation(UniSAM2InstanceSegmentation):
1398class TiledUniSAM2InstanceSegmentation(UniSAM2InstanceSegmentation):
1399    """Generates a tiled instance segmentation with the UniSAM2 decoder (AIS).
1400
1401    Like `UniSAM2InstanceSegmentation`, but the model inference is tiled in-plane (xy) with a halo,
1402    and for a volume also chunked along z (see `initialize`).
1403
1404    Args:
1405        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
1406        device: The device to run inference on.
1407    """
1408
1409    @torch.no_grad()
1410    def _run_decoder_tiled_2d(
1411        self, image_embeddings, pbar_init=None, pbar_update=None,
1412        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1413    ):
1414        """Decode and stitch queued 2d embedding tiles."""
1415        from micro_sam.v2.batched_inference import _decode_tiled_2d_embeddings
1416
1417        return _decode_tiled_2d_embeddings(
1418            model=self._model,
1419            image_embeddings=image_embeddings,
1420            pbar_init=pbar_init,
1421            pbar_update=pbar_update,
1422            batch_size=batch_size,
1423            devices=self._inference_devices(devices),
1424            num_prefetch_workers=num_prefetch_workers,
1425            num_write_workers=num_write_workers,
1426        )
1427
1428    @torch.no_grad()
1429    def _run_decoder_tiled_3d(
1430        self, image_embeddings, pbar_init=None, pbar_update=None, z_block=None, z_halo=None,
1431        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1432    ):
1433        """Decode batches spanning tile columns and z blocks, then stitch them."""
1434        from micro_sam.v2.batched_inference import _decode_tiled_3d_embeddings
1435
1436        return _decode_tiled_3d_embeddings(
1437            model=self._model,
1438            image_embeddings=image_embeddings,
1439            pbar_init=pbar_init,
1440            pbar_update=pbar_update,
1441            z_block=z_block,
1442            z_halo=z_halo,
1443            batch_size=batch_size,
1444            devices=self._inference_devices(devices),
1445            num_prefetch_workers=num_prefetch_workers,
1446            num_write_workers=num_write_workers,
1447        )
1448
1449    @torch.no_grad()
1450    def _run_decoder_tiled_3d_slice(
1451        self, image_embeddings, i, pbar_init=None, pbar_update=None,
1452        batch_size=None, devices: Devices = None, num_prefetch_workers=4, num_write_workers=2,
1453    ):
1454        """Decode one volume slice across all embedding tiles in batches."""
1455        from micro_sam.v2.batched_inference import _decode_tiled_3d_slice
1456
1457        return _decode_tiled_3d_slice(
1458            model=self._model,
1459            image_embeddings=image_embeddings,
1460            index=i,
1461            pbar_init=pbar_init,
1462            pbar_update=pbar_update,
1463            batch_size=batch_size,
1464            devices=self._inference_devices(devices),
1465            num_prefetch_workers=num_prefetch_workers,
1466            num_write_workers=num_write_workers,
1467        )
1468
1469    @torch.no_grad()
1470    def initialize(
1471        self,
1472        image: np.ndarray,
1473        ndim: int,
1474        tile_shape: Optional[tuple] = None,
1475        halo: Optional[tuple] = None,
1476        image_embeddings: Optional[dict] = None,
1477        i: Optional[int] = None,
1478        pbar_init: Optional[callable] = None,
1479        pbar_update: Optional[callable] = None,
1480        batch_size: Optional[int] = 1,
1481        devices: Devices = None,
1482        num_prefetch_workers: int = 4,
1483        num_write_workers: int = 2,
1484        normalization: Optional[callable] = None,
1485    ) -> None:
1486        """Run tiled UniSAM2 inference and store foreground and distance predictions.
1487
1488        `tile_shape`/`halo` are in-plane (y, x) for an image. For a volume they are always the full
1489        (z, y, x) / (z_halo, y_halo, x_halo): a volume is tiled in-plane and chunked along z, and
1490        `tile_shape`'s z entry sets that chunk (None keeps the library default). When precomputed
1491        `image_embeddings` are given, only the z entry is used - the in-plane tiling was fixed when
1492        the embeddings were computed and cannot change at decode time.
1493
1494        `batch_size=None` benchmarks candidate sizes and selects a throughput-efficient batch
1495        independently on each selected CUDA device.
1496        Reads and preprocessing are queued through `num_prefetch_workers`, output writes through
1497        `num_write_workers`. `normalization` overrides the per-tile input normalization, which
1498        defaults to the 2nd / 98th percentile.
1499        """
1500        decoder_kwargs = {
1501            "pbar_init": pbar_init,
1502            "pbar_update": pbar_update,
1503            "batch_size": batch_size,
1504            "devices": devices,
1505            "num_prefetch_workers": num_prefetch_workers,
1506            "num_write_workers": num_write_workers,
1507        }
1508        if image_embeddings is not None and ndim == 2 and "fpn" in image_embeddings and i is not None:
1509            self._prediction = self._run_decoder_tiled_3d_slice(
1510                image_embeddings, i, **decoder_kwargs,
1511            )
1512        elif image_embeddings is not None and ndim == 3:
1513            n_slices = int(np.asarray(image_embeddings["features"].attrs["shape"])[0])
1514            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1515            self._prediction = self._run_decoder_tiled_3d(
1516                image_embeddings, z_block=z_block, z_halo=z_halo, **decoder_kwargs,
1517            )
1518        elif image_embeddings is not None and ndim == 2:
1519            self._prediction = self._run_decoder_tiled_2d(image_embeddings, **decoder_kwargs)
1520        else:
1521            self._prediction = self._run_full_inference(
1522                image,
1523                ndim,
1524                tile_shape=tile_shape,
1525                halo=halo,
1526                pbar_init=pbar_init,
1527                pbar_update=pbar_update,
1528                batch_size=batch_size,
1529                devices=devices,
1530                num_prefetch_workers=num_prefetch_workers,
1531                num_write_workers=num_write_workers,
1532                normalization=normalization,
1533            )
1534        self._is_initialized = True

Generates a tiled instance segmentation with the UniSAM2 decoder (AIS).

Like UniSAM2InstanceSegmentation, but the model inference is tiled in-plane (xy) with a halo, and for a volume also chunked along z (see initialize).

Arguments:
@torch.no_grad()
def initialize( self, image: numpy.ndarray, ndim: int, tile_shape: Optional[tuple] = None, halo: Optional[tuple] = None, image_embeddings: Optional[dict] = None, i: Optional[int] = None, pbar_init: Optional[<built-in function callable>] = None, pbar_update: Optional[<built-in function callable>] = None, batch_size: Optional[int] = 1, devices: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = None, num_prefetch_workers: int = 4, num_write_workers: int = 2, normalization: Optional[<built-in function callable>] = None) -> None:
1469    @torch.no_grad()
1470    def initialize(
1471        self,
1472        image: np.ndarray,
1473        ndim: int,
1474        tile_shape: Optional[tuple] = None,
1475        halo: Optional[tuple] = None,
1476        image_embeddings: Optional[dict] = None,
1477        i: Optional[int] = None,
1478        pbar_init: Optional[callable] = None,
1479        pbar_update: Optional[callable] = None,
1480        batch_size: Optional[int] = 1,
1481        devices: Devices = None,
1482        num_prefetch_workers: int = 4,
1483        num_write_workers: int = 2,
1484        normalization: Optional[callable] = None,
1485    ) -> None:
1486        """Run tiled UniSAM2 inference and store foreground and distance predictions.
1487
1488        `tile_shape`/`halo` are in-plane (y, x) for an image. For a volume they are always the full
1489        (z, y, x) / (z_halo, y_halo, x_halo): a volume is tiled in-plane and chunked along z, and
1490        `tile_shape`'s z entry sets that chunk (None keeps the library default). When precomputed
1491        `image_embeddings` are given, only the z entry is used - the in-plane tiling was fixed when
1492        the embeddings were computed and cannot change at decode time.
1493
1494        `batch_size=None` benchmarks candidate sizes and selects a throughput-efficient batch
1495        independently on each selected CUDA device.
1496        Reads and preprocessing are queued through `num_prefetch_workers`, output writes through
1497        `num_write_workers`. `normalization` overrides the per-tile input normalization, which
1498        defaults to the 2nd / 98th percentile.
1499        """
1500        decoder_kwargs = {
1501            "pbar_init": pbar_init,
1502            "pbar_update": pbar_update,
1503            "batch_size": batch_size,
1504            "devices": devices,
1505            "num_prefetch_workers": num_prefetch_workers,
1506            "num_write_workers": num_write_workers,
1507        }
1508        if image_embeddings is not None and ndim == 2 and "fpn" in image_embeddings and i is not None:
1509            self._prediction = self._run_decoder_tiled_3d_slice(
1510                image_embeddings, i, **decoder_kwargs,
1511            )
1512        elif image_embeddings is not None and ndim == 3:
1513            n_slices = int(np.asarray(image_embeddings["features"].attrs["shape"])[0])
1514            z_block, z_halo = _resolve_z_chunk(tile_shape, halo, n_slices)
1515            self._prediction = self._run_decoder_tiled_3d(
1516                image_embeddings, z_block=z_block, z_halo=z_halo, **decoder_kwargs,
1517            )
1518        elif image_embeddings is not None and ndim == 2:
1519            self._prediction = self._run_decoder_tiled_2d(image_embeddings, **decoder_kwargs)
1520        else:
1521            self._prediction = self._run_full_inference(
1522                image,
1523                ndim,
1524                tile_shape=tile_shape,
1525                halo=halo,
1526                pbar_init=pbar_init,
1527                pbar_update=pbar_update,
1528                batch_size=batch_size,
1529                devices=devices,
1530                num_prefetch_workers=num_prefetch_workers,
1531                num_write_workers=num_write_workers,
1532                normalization=normalization,
1533            )
1534        self._is_initialized = True

Run tiled UniSAM2 inference and store foreground and distance predictions.

tile_shape/halo are in-plane (y, x) for an image. For a volume they are always the full (z, y, x) / (z_halo, y_halo, x_halo): a volume is tiled in-plane and chunked along z, and tile_shape's z entry sets that chunk (None keeps the library default). When precomputed image_embeddings are given, only the z entry is used - the in-plane tiling was fixed when the embeddings were computed and cannot change at decode time.

batch_size=None benchmarks candidate sizes and selects a throughput-efficient batch independently on each selected CUDA device. Reads and preprocessing are queued through num_prefetch_workers, output writes through num_write_workers. normalization overrides the per-tile input normalization, which defaults to the 2nd / 98th percentile.

def get_unisam2_segmentation_generator( model: torch.nn.modules.module.Module, is_tiled: bool = False, device: Union[str, torch.device, NoneType] = None, inference_device: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = <object object>) -> UniSAM2InstanceSegmentation:
1537def get_unisam2_segmentation_generator(
1538    model: torch.nn.Module,
1539    is_tiled: bool = False,
1540    device: Optional[Union[str, torch.device]] = None,
1541    inference_device: Devices = USE_MODEL_DEVICE,
1542) -> UniSAM2InstanceSegmentation:
1543    """Get the UniSAM2 decoder-based (AIS) instance segmentation generator.
1544
1545    Args:
1546        model: The UniSAM2 model.
1547        is_tiled: Whether to use tiled inference.
1548        device: The device the model lives on.
1549        inference_device: The `devices=None` fallback (see `UniSAM2InstanceSegmentation`).
1550
1551    Returns:
1552        The instance segmentation generator, either `TiledUniSAM2InstanceSegmentation` (if tiled)
1553        or `UniSAM2InstanceSegmentation`.
1554    """
1555    cls = TiledUniSAM2InstanceSegmentation if is_tiled else UniSAM2InstanceSegmentation
1556    return cls(model, device=device, inference_device=inference_device)

Get the UniSAM2 decoder-based (AIS) instance segmentation generator.

Arguments:
  • model: The UniSAM2 model.
  • is_tiled: Whether to use tiled inference.
  • device: The device the model lives on.
  • inference_device: The devices=None fallback (see UniSAM2InstanceSegmentation).
Returns:

The instance segmentation generator, either TiledUniSAM2InstanceSegmentation (if tiled) or UniSAM2InstanceSegmentation.

def get_instance_segmentation_generator( model: Optional[torch.nn.modules.module.Module] = None, decoder: Optional[torch.nn.modules.module.Module] = None, is_tiled: bool = False, segmentation_mode: Optional[str] = None, device: Union[str, torch.device, NoneType] = None, inference_device: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = <object object>, ndim: int = 2, **kwargs) -> micro_sam.util.AutoSegBase:
1559def get_instance_segmentation_generator(
1560    model: Optional[torch.nn.Module] = None,
1561    decoder: Optional[torch.nn.Module] = None,
1562    is_tiled: bool = False,
1563    segmentation_mode: Optional[str] = None,
1564    device: Optional[Union[str, torch.device]] = None,
1565    inference_device: Devices = USE_MODEL_DEVICE,
1566    ndim: int = 2,
1567    **kwargs,
1568) -> AutoSegBase:
1569    """Get the automatic instance segmentation generator (AMG, AIS or APG), mirroring the v1 factory.
1570
1571    Args:
1572        model: The SAM2 model, required for the 'amg' and 'apg' modes. For volumetric APG this must
1573            be the SAM2 video predictor, which propagates the derived prompts through the volume.
1574        decoder: The UniSAM2 decoder model, required for the 'ais' and 'apg' modes.
1575        is_tiled: Whether to use the tiled segmenter.
1576        segmentation_mode: One of 'amg', 'ais' or 'apg'. By default 'ais' is used if a decoder is
1577            given, otherwise 'amg'.
1578        device: The device the model lives on ('ais' and 'apg' only).
1579        inference_device: The `devices=None` fallback ('ais' and 'apg' only, see
1580            `UniSAM2InstanceSegmentation`).
1581        ndim: The number of spatial dimensions. Only 'apg' has a separate volumetric segmenter; the
1582            other modes handle a volume in their front-end (see `automatic_instance_segmentation`).
1583        kwargs: Additional keyword arguments for the segmenter, e.g. 'beta' for tiled/blocked APG
1584            (see `TiledAutomaticPromptGenerator`).
1585
1586    Returns:
1587        The segmentation generator instance.
1588    """
1589    if segmentation_mode is None:
1590        segmentation_mode = DEFAULT_SEGMENTATION_MODE_WITH_DECODER if decoder is not None else "amg"
1591
1592    # Record what the generator was built from, so the tiled and non-tiled variants of the same
1593    # engine can be swapped without reloading the weights (see `retile_instance_segmentation_generator`).
1594    config = dict(
1595        model=model, decoder=decoder, is_tiled=is_tiled, segmentation_mode=segmentation_mode,
1596        device=device, inference_device=inference_device, ndim=ndim, **kwargs,
1597    )
1598    segmenter = _build_instance_segmentation_generator(
1599        model, decoder, is_tiled, segmentation_mode, device, inference_device, ndim, **kwargs
1600    )
1601    try:
1602        segmenter._generator_config = config
1603    except AttributeError:  # A generator that takes no attributes simply cannot be swapped.
1604        pass
1605    return segmenter

Get the automatic instance segmentation generator (AMG, AIS or APG), mirroring the v1 factory.

Arguments:
  • model: The SAM2 model, required for the 'amg' and 'apg' modes. For volumetric APG this must be the SAM2 video predictor, which propagates the derived prompts through the volume.
  • decoder: The UniSAM2 decoder model, required for the 'ais' and 'apg' modes.
  • is_tiled: Whether to use the tiled segmenter.
  • segmentation_mode: One of 'amg', 'ais' or 'apg'. By default 'ais' is used if a decoder is given, otherwise 'amg'.
  • device: The device the model lives on ('ais' and 'apg' only).
  • inference_device: The devices=None fallback ('ais' and 'apg' only, see UniSAM2InstanceSegmentation).
  • ndim: The number of spatial dimensions. Only 'apg' has a separate volumetric segmenter; the other modes handle a volume in their front-end (see automatic_instance_segmentation).
  • kwargs: Additional keyword arguments for the segmenter, e.g. 'beta' for tiled/blocked APG (see TiledAutomaticPromptGenerator).
Returns:

The segmentation generator instance.

def retile_instance_segmentation_generator( segmenter: micro_sam.util.AutoSegBase, is_tiled: bool) -> micro_sam.util.AutoSegBase:
1608def retile_instance_segmentation_generator(segmenter: AutoSegBase, is_tiled: bool) -> AutoSegBase:
1609    """Return the same generator, or the other tiling variant of it, rebuilt from its build config.
1610
1611    The tiled and non-tiled generators are different classes, so a front-end that decides on tiling
1612    only once it has seen the image (see `micro_sam.v2.automatic_segmentation`) has to be able to
1613    swap them. The swap reuses the already loaded model and decoder, so it costs nothing but the
1614    wrapper, and the counterpart is cached on both objects so repeated swaps are free. A generator
1615    built by hand (without a config) is returned unchanged.
1616
1617    Args:
1618        segmenter: The automatic instance segmentation generator.
1619        is_tiled: Whether the returned generator should be the tiled one.
1620
1621    Returns:
1622        The generator matching `is_tiled`.
1623    """
1624    config = getattr(segmenter, "_generator_config", None)
1625    if config is None or bool(config["is_tiled"]) == bool(is_tiled):
1626        return segmenter
1627
1628    counterpart = getattr(segmenter, "_retiled_counterpart", None)
1629    if counterpart is None:
1630        counterpart = get_instance_segmentation_generator(**{**config, "is_tiled": is_tiled})
1631        segmenter._retiled_counterpart = counterpart
1632        counterpart._retiled_counterpart = segmenter
1633    return counterpart

Return the same generator, or the other tiling variant of it, rebuilt from its build config.

The tiled and non-tiled generators are different classes, so a front-end that decides on tiling only once it has seen the image (see micro_sam.v2.automatic_segmentation) has to be able to swap them. The swap reuses the already loaded model and decoder, so it costs nothing but the wrapper, and the counterpart is cached on both objects so repeated swaps are free. A generator built by hand (without a config) is returned unchanged.

Arguments:
  • segmenter: The automatic instance segmentation generator.
  • is_tiled: Whether the returned generator should be the tiled one.
Returns:

The generator matching is_tiled.