micro_sam.v2.automatic_prompt_generation

Automatic prompt generation (APG) for UniSAM2: propose seeds generously, let the model judge them.

The flow post-processing thresholds the decoder's convergence density to get instances. APG proposes candidates below that threshold, prompts the interactive branch with each one, and keeps the masks it scores highly, so the model does the discrimination that thresholding cannot.

A volume works the same way, with the SAM2 video predictor in place of the image predictor: the flow is integrated in 3d so a density component is a whole object, each is scored in 2d on the slice it converges on, and the survivors are propagated through the volume. The optional 'refinement' re-prompts each instance on its anchor slice before the propagation.

The measurements behind these choices are in finetuning/v2/evaluation/optimization/notes/APG_2D_OPTIMIZATION.md and APG_3D_OPTIMIZATION.md.

   1"""Automatic prompt generation (APG) for UniSAM2: propose seeds generously, let the model judge them.
   2
   3The flow post-processing thresholds the decoder's convergence density to get instances. APG proposes
   4candidates *below* that threshold, prompts the interactive branch with each one, and keeps the masks it
   5scores highly, so the model does the discrimination that thresholding cannot.
   6
   7A volume works the same way, with the SAM2 video predictor in place of the image predictor: the flow
   8is integrated in 3d so a density component is a whole object, each is scored in 2d on the slice it
   9converges on, and the survivors are propagated through the volume. The optional 'refinement' re-prompts
  10each instance on its anchor slice before the propagation.
  11
  12The measurements behind these choices are in finetuning/v2/evaluation/optimization/notes/APG_2D_OPTIMIZATION.md
  13and APG_3D_OPTIMIZATION.md.
  14"""
  15
  16import copy
  17import queue
  18import shutil
  19import contextlib
  20import multiprocessing as mp
  21from concurrent.futures import ThreadPoolExecutor
  22from typing import Any, Callable, Dict, List, Optional, Sequence, Union
  23
  24import numpy as np
  25from tqdm import tqdm
  26from scipy.ndimage import find_objects
  27
  28import torch
  29
  30from sam2.utils.amg import calculate_stability_score
  31
  32from bioimage_cpp.utils import Blocking
  33from bioimage_cpp.segmentation import label
  34from bioimage_cpp.distance import distance_transform
  35
  36# Only the tiled stitching uses it, so a missing 'bioimage_py' must not break the import of this module.
  37try:
  38    import bioimage_py as bp
  39except ImportError:
  40    bp = None
  41
  42from .normalization import to_image
  43from .transforms.resize import resize_longest_side_and_pad_tensor
  44from ..util import make_temp_embedding_path
  45from .postprocessing import _compute_flow_density
  46from .._model_settings import DEFAULT_PROMPT_GENERATION_PARAMETERS
  47from .batched_inference import _resolve_devices, _volume_normalization_bounds
  48from .prompt_based_segmentation import (
  49    ReplicatedPromptableSegmentation3D, map_jobs_over_devices, _crop_to_original_shape,
  50)
  51from .util import (
  52    DEFAULT_MODEL, autocast, configure_image_predictor, encode_image, get_sam2_image_predictor,
  53    parameter_family, precompute_image_embeddings, set_precomputed, _load_list_datasets,
  54)
  55from .instance_segmentation import (
  56    UniSAM2InstanceSegmentation, USE_MODEL_DEVICE, Devices, _set_image_predictor_from_3d_embeddings,
  57)
  58
  59
  60def _run_with_progress(function, pbar_update):
  61    """Relay parallel work's progress to the calling thread, where GUI callbacks can repaint."""
  62    if pbar_update is None:
  63        return function(None)
  64    updates = queue.Queue()
  65    grad_enabled = torch.is_grad_enabled()
  66
  67    def run():
  68        with torch.set_grad_enabled(grad_enabled):
  69            return function(updates.put)
  70
  71    with ThreadPoolExecutor(max_workers=1) as pool:
  72        task = pool.submit(run)
  73        while not task.done() or not updates.empty():
  74            try:
  75                increment = updates.get(timeout=0.05)
  76            except queue.Empty:
  77                continue
  78            pbar_update(increment)
  79        return task.result()
  80
  81
  82# Only enters the merge order, never a cutoff, so it is a constant.
  83STABILITY_SCORE_OFFSET = 1.0
  84
  85# The multicut boundary bias `TiledAutomaticPromptGenerator` stitches tiles/blocks with by default.
  86DEFAULT_STITCHING_BETA = 0.5
  87
  88
  89def default_prompt_generation(model_type: str = DEFAULT_MODEL, is_volume: bool = False) -> dict:
  90    """The default APG parameters for one model and dimensionality.
  91
  92    Args:
  93        model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which
  94            uses the 'cells' defaults. Its family and backbone select the table, see `parameter_family`.
  95        is_volume: Whether to use the 3D table (`derive_volume_prompts`) or the 2D one
  96            (`derive_point_prompts`). A volume prompts once per object rather than once per slice, so
  97            the two are swept and tuned independently.
  98
  99    Returns:
 100        The default parameter dict for that model and dimensionality.
 101    """
 102    family, backbone = parameter_family(model_type), model_type[:6]
 103    params = DEFAULT_PROMPT_GENERATION_PARAMETERS.get(family, {}).get(backbone)
 104    if params is None:
 105        raise ValueError(
 106            f"No default prompt generation parameters for model type '{model_type}'. They exist for "
 107            + ", ".join(f"{name}: {sorted(table)}" for name, table in DEFAULT_PROMPT_GENERATION_PARAMETERS.items())
 108            + "."
 109        )
 110    return params["3d" if is_volume else "2d"]
 111
 112
 113# Enough jobs per device that none idles at the end, and enough passes per job to pay for its state.
 114PROPAGATION_JOBS_PER_DEVICE = 4
 115MIN_PASSES_PER_PROPAGATION_JOB = 4
 116
 117DEFAULT_PROMPT_GENERATION = {
 118    "multimasking": True,
 119    # Resolves to the mode of 'default_prompt_generation'; pass None to run no second round.
 120    "refinement": "default",
 121    "refinement_kwargs": None,
 122    # Volumes only. Trades device memory against the pass count.
 123    "n_objects_per_pass": 16,
 124    # Volumes only. Stop a pass after this many empty slices; None propagates through the whole volume.
 125    "early_stop_patience": 2,
 126    # Tiled volumes only. Rounds the candidates are propagated in, highest scoring first, so that a later round
 127    # drops the candidates that the finished masks already cover. Faster, but not better on every dataset.
 128    "propagation_waves": 1,
 129    # Reject a candidate this many times larger than the median candidate it is merged against, see `merge_by_score`.
 130    "max_size_factor": None,
 131    # Number of image prompts (or refinement boxes) evaluated per forward pass.
 132    "batch_size": 64,
 133    # The step of the flow integration.
 134    "dt": 0.5,
 135    # Throughput only, the density is the same either way.
 136    "n_threads": 8,
 137}
 138
 139# The components a refinement mode can be assembled from, and the keyword arguments each accepts.
 140# A mode is a '+'-joined combination, e.g. 'points', 'boxes' or 'points+boxes': every component
 141# contributes its prompt to one joint re-prompt per instance, so 'points+boxes' conditions on both.
 142REFINEMENT_COMPONENTS = ("points", "boxes", "masks")
 143REFINEMENT_KWARGS = {
 144    "shared": ("policy", "multimasking", "min_consistency", "max_foreign_overlap"),
 145    "points": ("n_positives", "n_negatives", "max_negative_distance", "negative_source", "min_negative_distance"),
 146    "boxes": ("box_extension",),
 147    "masks": (),
 148}
 149DEFAULT_REFINEMENT = {
 150    # 'replace' repaints every instance from its second-round mask; 'keep-if-better' keeps the
 151    # first-round mask unless the second round scores higher.
 152    "policy": "replace",
 153    # Off by default: a multi-prompt re-prompt is not ambiguous the way a single point is.
 154    "multimasking": False,
 155    # Accept a second-round mask only if its IoU with the first-round mask reaches this. None accepts any.
 156    "min_consistency": 0.7,
 157    # Keep the first-round mask when more than this fraction of the second-round mask lies on other
 158    # instances. None allows any.
 159    "max_foreign_overlap": 0.15,
 160    # Extra positives from the prompts grouped onto an instance hurt.
 161    "n_positives": 1,
 162    # Negative points per instance, taken from the prompts of the nearest other instances.
 163    "n_negatives": 6,
 164    # Only prompts within this distance (in pixels) of an instance's bounding box can be its
 165    # negatives. None takes the nearest ones regardless of distance.
 166    "max_negative_distance": None,
 167    # Where an instance's negatives come from: the other instances' first-round 'prompts', or the
 168    # deepest 'interior' point of each other instance's mask, which sits away from shared borders.
 169    "negative_source": "prompts",
 170    # Exclude negatives closer than this (in pixels) to the instance's own first-round mask.
 171    "min_negative_distance": 0,
 172    # Number of pixels every box prompt is grown by.
 173    "box_extension": 0,
 174}
 175
 176# A volume refines its anchor slices before the propagation, since a prompt on a propagated slice
 177# replaces its mask. 'conditioning' is the one addition to the 2d components.
 178CONDITIONING_MODES = ("prompts", "prompts-grouped", "prompts-joint", "mask")
 179REFINEMENT_KWARGS_3D = {
 180    "shared": REFINEMENT_KWARGS["shared"] + ("conditioning",),
 181    "points": REFINEMENT_KWARGS["points"],
 182    "boxes": REFINEMENT_KWARGS["boxes"],
 183    "masks": REFINEMENT_KWARGS["masks"],
 184}
 185DEFAULT_REFINEMENT_3D = dict(DEFAULT_REFINEMENT)
 186# The counters a volume's refinement reports, summed over the anchor slices.
 187REFINEMENT_STATS_3D = (
 188    "refined_candidates", "replaced_candidates", "gated_consistency", "gated_foreign",
 189    "refinement_negatives",
 190)
 191DEFAULT_REFINEMENT_3D.update({
 192    "n_negatives": 4,
 193    # Tighter than in 2d, since an accepted re-prompt conditions a whole track.
 194    "min_consistency": 0.85,
 195    # How an accepted re-prompt is pushed onto the anchor frame. Each push re-runs the mask decoder, so more
 196    # pushes refine the anchor more: 'prompts' pushes the box, then each point; 'prompts-grouped' the box, then
 197    # all points; 'prompts-joint' the box and all points at once; 'mask' the refined mask itself.
 198    "conditioning": "prompts",
 199})
 200
 201
 202def _parse_refinement(
 203    refinement: str, refinement_kwargs: Optional[Dict[str, Any]], is_volume: bool = False,
 204) -> tuple:
 205    """Parse a refinement mode into its components and resolve its keyword arguments.
 206
 207    Args:
 208        refinement: The mode, a '+'-joined combination of `REFINEMENT_COMPONENTS`.
 209        refinement_kwargs: The mode's keyword arguments. Only keys that one of the mode's
 210            components (or every mode) accepts are allowed.
 211        is_volume: Whether the mode is resolved for a volume, which accepts and defaults its
 212            keyword arguments differently, see `REFINEMENT_KWARGS_3D` and `DEFAULT_REFINEMENT_3D`.
 213
 214    Returns:
 215        The components as a tuple, and the resolved keyword arguments with the defaults filled in.
 216    """
 217    accepted = REFINEMENT_KWARGS_3D if is_volume else REFINEMENT_KWARGS
 218    defaults = DEFAULT_REFINEMENT_3D if is_volume else DEFAULT_REFINEMENT
 219    components = tuple(refinement.split("+"))
 220    unknown = [component for component in components if component not in REFINEMENT_COMPONENTS]
 221    if unknown or len(set(components)) != len(components):
 222        raise ValueError(
 223            f"Invalid refinement mode {refinement!r}: expected a '+'-joined combination of "
 224            f"{', '.join(REFINEMENT_COMPONENTS)} without repetition."
 225        )
 226    if components == ("masks",):
 227        raise ValueError(
 228            "A mask prompt can only condition a re-prompt, not drive one alone: SAM2 is not trained "
 229            "for dense-only prompting. Combine it, e.g. 'points+masks' or 'boxes+masks'."
 230        )
 231
 232    allowed = set(accepted["shared"])
 233    for component in components:
 234        allowed.update(accepted[component])
 235    refinement_kwargs = refinement_kwargs or {}
 236    unknown = sorted(set(refinement_kwargs) - allowed)
 237    if unknown:
 238        raise ValueError(
 239            f"Invalid refinement_kwargs for mode {refinement!r}: {', '.join(unknown)}. "
 240            f"Allowed: {', '.join(sorted(allowed))}."
 241        )
 242
 243    resolved = {key: defaults[key] for key in allowed}
 244    resolved.update(refinement_kwargs)
 245    if resolved["policy"] not in ("replace", "keep-if-better"):
 246        raise ValueError(f"Invalid refinement policy {resolved['policy']!r}: expected 'replace' or 'keep-if-better'.")
 247    if resolved.get("negative_source", "prompts") not in ("prompts", "interior"):
 248        raise ValueError(
 249            f"Invalid negative_source {resolved['negative_source']!r}: expected 'prompts' or 'interior'."
 250        )
 251    if resolved.get("conditioning", "prompts") not in CONDITIONING_MODES:
 252        raise ValueError(
 253            f"Invalid conditioning {resolved['conditioning']!r}: expected one of "
 254            f"{', '.join(CONDITIONING_MODES)}."
 255        )
 256    return components, resolved
 257
 258
 259def mask_to_logits(mask: np.ndarray, eps: float = 1e-3) -> np.ndarray:
 260    """Turn a binary mask into the low-resolution logit prompt SAM2 expects.
 261
 262    The image predictor preserves the aspect ratio and pads the bottom or right side. The mask uses
 263    the same frame, so it stays aligned with the image features and other prompts.
 264
 265    Args:
 266        mask: The binary mask, shape (Y, X).
 267        eps: Probability assigned to the background, from which the logit magnitude follows.
 268
 269    Returns:
 270        The logits, shape (1, 256, 256), float32.
 271    """
 272    binary = torch.from_numpy(np.asarray(mask, dtype="float32"))[None, None]
 273    resized, _ = resize_longest_side_and_pad_tensor(binary, target_length=256)
 274    logit = float(np.log((1.0 - eps) / eps))
 275    return np.where(resized[0].numpy() > 0.5, logit, -logit).astype("float32")
 276
 277
 278def _assign_points_to_instances(segmentation: np.ndarray, points: np.ndarray) -> np.ndarray:
 279    """The instance id under every point, 0 where a point lies on the background.
 280
 281    Args:
 282        segmentation: The instance segmentation.
 283        points: The points as (N, 2) in XY, following the prompt convention.
 284
 285    Returns:
 286        The instance ids as (N,), int64.
 287    """
 288    if len(points) == 0:
 289        return np.zeros(0, dtype="int64")
 290    coordinates = np.round(points[:, ::-1]).astype("int64")  # XY to YX.
 291    coordinates = np.clip(coordinates, 0, np.array(segmentation.shape) - 1)
 292    return segmentation[tuple(coordinates.T)].astype("int64")
 293
 294
 295def _subsample_positives(anchor: np.ndarray, candidates: np.ndarray, n_positives: int) -> np.ndarray:
 296    """The anchor plus up to 'n_positives - 1' candidates, chosen greedily for spatial coverage.
 297
 298    Farthest-point subsampling: each step adds the candidate farthest from everything selected so
 299    far, so the kept positives spread over the instance instead of clustering. Deterministic, with
 300    ties broken by candidate order.
 301
 302    Args:
 303        anchor: The point that is always kept, shape (2,).
 304        candidates: The candidate points, shape (M, 2).
 305        n_positives: The total number of positives to keep, including the anchor.
 306
 307    Returns:
 308        The selected points, shape (min(n_positives, M + 1), 2).
 309    """
 310    selected = [np.asarray(anchor, dtype="float32")]
 311    remaining = [np.asarray(candidate, dtype="float32") for candidate in candidates]
 312    while remaining and len(selected) < n_positives:
 313        distances = [min(float(np.linalg.norm(candidate - point)) for point in selected) for candidate in remaining]
 314        selected.append(remaining.pop(int(np.argmax(distances))))
 315    return np.stack(selected)
 316
 317
 318def _select_negatives(
 319    candidates: np.ndarray, bounding_box: tuple, n_negatives: int, max_negative_distance: Optional[float],
 320) -> np.ndarray:
 321    """The candidates nearest to the instance, which are the ones the model could confuse with it.
 322
 323    Nearness is the distance to the instance's bounding box, which is zero inside it; ties are
 324    broken by the distance to the box's center and then by candidate order, so the selection is
 325    deterministic.
 326
 327    Args:
 328        candidates: The candidate points as (M, 2) in XY.
 329        bounding_box: The instance's bounding box as a (y_slice, x_slice) tuple.
 330        n_negatives: Number of negatives to select.
 331        max_negative_distance: Discard candidates farther than this from the bounding box.
 332
 333    Returns:
 334        The selected points, shape (min(n_negatives, M'), 2).
 335    """
 336    if len(candidates) == 0 or n_negatives <= 0:
 337        return np.zeros((0, 2), dtype="float32")
 338    y_slice, x_slice = bounding_box
 339    low = np.array([x_slice.start, y_slice.start], dtype="float32")
 340    high = np.array([x_slice.stop - 1, y_slice.stop - 1], dtype="float32")
 341
 342    outside = np.maximum(np.maximum(low - candidates, candidates - high), 0.0)
 343    distances = np.linalg.norm(outside, axis=1)
 344    center_distances = np.linalg.norm(candidates - (low + high) / 2.0, axis=1)
 345    order = np.lexsort((np.arange(len(candidates)), center_distances, distances))
 346    if max_negative_distance is not None:
 347        order = order[distances[order] <= max_negative_distance]
 348    return candidates[order[:n_negatives]].astype("float32")
 349
 350
 351def _distances_to_mask(
 352    segmentation: np.ndarray, instance_id: int, bounding_box: tuple, candidates: np.ndarray, reach: float,
 353) -> np.ndarray:
 354    """The Euclidean distance of every candidate point to the instance's mask, exact up to 'reach'.
 355
 356    The transform runs on the instance's bounding box grown by 'reach', so a candidate outside that
 357    crop is farther than 'reach' and reported as infinity, which the caller's threshold treats the
 358    same way.
 359
 360    Args:
 361        segmentation: The instance segmentation.
 362        instance_id: The instance whose mask is measured to.
 363        bounding_box: The instance's bounding box, as a (y_slice, x_slice) tuple.
 364        candidates: The candidate points as (M, 2) in XY.
 365        reach: The distance up to which the measurement has to be exact.
 366
 367    Returns:
 368        The distances as (M,), float32, with infinity beyond 'reach'.
 369    """
 370    margin = int(np.ceil(reach)) + 1
 371    y_slice, x_slice = bounding_box
 372    y0, y1 = max(0, y_slice.start - margin), min(segmentation.shape[0], y_slice.stop + margin)
 373    x0, x1 = max(0, x_slice.start - margin), min(segmentation.shape[1], x_slice.stop + margin)
 374    distances_in_crop = distance_transform(segmentation[y0:y1, x0:x1] != instance_id)
 375
 376    distances = np.full(len(candidates), np.inf, dtype="float32")
 377    for position, (x, y) in enumerate(np.round(candidates).astype("int64")):
 378        if y0 <= y < y1 and x0 <= x < x1:
 379            distances[position] = distances_in_crop[y - y0, x - x0]
 380    return distances
 381
 382
 383def derive_refinement_prompts(
 384    segmentation: np.ndarray,
 385    points: np.ndarray,
 386    surviving_points: Dict[int, tuple],
 387    n_positives: int = DEFAULT_REFINEMENT["n_positives"],
 388    n_negatives: int = DEFAULT_REFINEMENT["n_negatives"],
 389    max_negative_distance: Optional[float] = DEFAULT_REFINEMENT["max_negative_distance"],
 390    negative_source: str = DEFAULT_REFINEMENT["negative_source"],
 391    min_negative_distance: float = DEFAULT_REFINEMENT["min_negative_distance"],
 392) -> Dict[int, Dict[str, np.ndarray]]:
 393    """Group the first round's prompts onto the instances they landed in and derive re-prompts.
 394
 395    An instance's positives are the prompt that made it plus the suppressed prompts inside it: each
 396    marks a spot the decoder proposed an object at, so together they cover the instance in a way a
 397    single point cannot. Its negatives are nearby points belonging to other instances, which tell
 398    the model where the instance ends.
 399
 400    Args:
 401        segmentation: The instance segmentation of the first round.
 402        points: All first-round prompt points as (N, 2) in XY, including the suppressed ones.
 403        surviving_points: The prompt that made each instance, as {instance_id: (x, y)}.
 404        n_positives: Number of positive points per instance, including the surviving prompt. The
 405            surplus is subsampled farthest-point-first, for spatial coverage.
 406        n_negatives: Number of negative points per instance. The surplus is dropped farthest-first,
 407            measured to the instance's bounding box.
 408        max_negative_distance: Only points within this distance of an instance's bounding box can
 409            be its negatives. None takes the nearest ones regardless of distance.
 410        negative_source: Where the negatives come from: the other instances' first-round 'prompts',
 411            or the deepest 'interior' point of each other instance's mask, which sits away from any
 412            border the two instances share.
 413        min_negative_distance: Exclude negatives closer than this to the instance's own mask. A
 414            negative that touches the instance's true extent cuts into the object instead of
 415            bounding it, which is the suspected failure on densely packed data.
 416
 417    Returns:
 418        The prompts per instance, as {instance_id: {'points': (M, 2) XY, 'point_labels': (M,),
 419        'n_grouped': int}}, where 'n_grouped' counts the suppressed prompts grouped onto the
 420        instance before any subsampling - the supply signal an adaptive re-prompt keys on.
 421    """
 422    points = np.asarray(points, dtype="float32").reshape(-1, 2)
 423    assignment = _assign_points_to_instances(segmentation, points)
 424
 425    if negative_source == "interior":
 426        # One deep interior point per instance, ordered by ascending instance id; converted to XY.
 427        interior = interior_points(segmentation)[:, ::-1].astype("float32")
 428        present = np.array(sorted(surviving_points), dtype="int64")
 429        negative_points, negative_owners = interior, present
 430    elif negative_source == "prompts":
 431        foreign = assignment > 0
 432        negative_points, negative_owners = points[foreign], assignment[foreign]
 433    else:
 434        raise ValueError(f"Invalid negative_source {negative_source!r}: expected 'prompts' or 'interior'.")
 435
 436    prompts = {}
 437    for index, bounding_box in enumerate(find_objects(segmentation), start=1):
 438        if bounding_box is None:
 439            continue
 440        anchor = np.asarray(surviving_points[index], dtype="float32")
 441        grouped = points[assignment == index]
 442        # The anchor is one of the grouped points; keep it once, as the seed of the subsampling.
 443        grouped = grouped[np.linalg.norm(grouped - anchor, axis=1) > 0]
 444        positives = _subsample_positives(anchor, grouped, n_positives)
 445
 446        allowed = negative_owners != index
 447        candidates = negative_points[allowed]
 448        if min_negative_distance > 0 and len(candidates) and n_negatives > 0:
 449            distances = _distances_to_mask(segmentation, index, bounding_box, candidates, min_negative_distance)
 450            candidates = candidates[distances >= min_negative_distance]
 451        negatives = _select_negatives(candidates, bounding_box, n_negatives, max_negative_distance)
 452
 453        prompts[index] = {
 454            "points": np.concatenate([positives, negatives]).astype("float32"),
 455            "point_labels": np.concatenate([
 456                np.ones(len(positives), dtype="int32"), np.zeros(len(negatives), dtype="int32"),
 457            ]),
 458            "n_grouped": int(len(grouped)),
 459        }
 460    return prompts
 461
 462
 463def _shift_box(bounding_box: tuple, offset: tuple) -> tuple:
 464    """Translate a bounding box by a per-axis offset, returning it unchanged for a zero offset."""
 465    if not any(offset):
 466        return bounding_box
 467    return tuple(slice(box.start + shift, box.stop + shift) for box, shift in zip(bounding_box, offset))
 468
 469
 470def _localize_prompts(prompt: Dict[str, Any], origin: tuple, extent: tuple) -> tuple:
 471    """Translate one instance's re-prompt into a region's frame, dropping the negatives outside it.
 472
 473    The instance's own mask lies inside the region it is re-prompted in, so its positives are only
 474    clamped onto the border pixel they round to. A negative comes from a neighbouring instance and
 475    can lie outside the region - beyond a tile's halo - and has to go, because the predictor
 476    normalises the prompt against the region's own shape.
 477
 478    Args:
 479        prompt: The instance's prompt, as `derive_refinement_prompts` returns it.
 480        origin: The region's (y, x) origin in the full image.
 481        extent: The region's (y, x) shape.
 482
 483    Returns:
 484        The translated prompt, and the number of negatives dropped.
 485    """
 486    origin_xy = np.array([origin[1], origin[0]], dtype="float32")
 487    high_xy = np.array([extent[1] - 1, extent[0] - 1], dtype="float32")
 488    points = np.asarray(prompt["points"], dtype="float32") - origin_xy
 489    labels = np.asarray(prompt["point_labels"])
 490
 491    # A point that rounds onto one of the region's pixels is inside it. Positives are never dropped.
 492    inside = np.all((points >= -0.5) & (points <= high_xy + 0.5), axis=1)
 493    keep = inside | (labels == 1)
 494    localized = {
 495        "points": np.clip(points[keep], 0.0, high_xy),
 496        "point_labels": labels[keep],
 497        "n_grouped": prompt["n_grouped"],
 498    }
 499    return localized, int(np.count_nonzero(~keep))
 500
 501
 502def _prompt_box(bounding_box: tuple, shape: tuple, box_extension: int) -> tuple:
 503    """An instance's bounding box as the XYXY box prompt SAM2 takes, grown and clipped to 'shape'.
 504
 505    Args:
 506        bounding_box: The instance's bounding box, as a (y_slice, x_slice) tuple.
 507        shape: The (Y, X) shape the grown box is clipped to.
 508        box_extension: Number of pixels the box is grown by on every side.
 509
 510    Returns:
 511        The box as (x0, y0, x1, y1).
 512    """
 513    y_slice, x_slice = bounding_box
 514    return (
 515        max(0, x_slice.start - box_extension), max(0, y_slice.start - box_extension),
 516        min(shape[1], x_slice.stop + box_extension), min(shape[0], y_slice.stop + box_extension),
 517    )
 518
 519
 520def interior_points(labels: np.ndarray) -> np.ndarray:
 521    """The deepest interior point of every labelled component, in ascending label order.
 522
 523    The v1 counterpart transforms a `find_boundaries` image, whose 'outer' mode marks a thin
 524    component's own pixels as boundary. Its maximum then falls on the bounding box's first pixel,
 525    which need not lie in the component at all.
 526
 527    Args:
 528        labels: A labelled image or volume.
 529
 530    Returns:
 531        The points as (N, ndim), one per component, in the array's own axis order.
 532    """
 533    points = []
 534    for index, bounding_box in enumerate(find_objects(labels), start=1):
 535        if bounding_box is None:
 536            continue
 537        # Padded, so a component reaching the border is measured from that border too.
 538        distances = distance_transform(np.pad(labels[bounding_box] == index, 1))
 539        coordinates = np.unravel_index(int(np.argmax(distances)), distances.shape)
 540        points.append(tuple(int(c) + box.start - 1 for c, box in zip(coordinates, bounding_box)))
 541    return np.array(points, dtype="int64").reshape(-1, labels.ndim)
 542
 543
 544def derive_point_prompts(
 545    foreground: np.ndarray,
 546    directed_distances: np.ndarray,
 547    model_type: str = DEFAULT_MODEL,
 548    candidate_threshold: Optional[float] = None,
 549    foreground_threshold: Optional[float] = None,
 550    n_iter: Optional[int] = None,
 551    dt: Optional[float] = None,
 552    sigma: Optional[float] = None,
 553    min_candidate_size: Optional[int] = None,
 554    n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
 555) -> Optional[Dict[str, np.ndarray]]:
 556    """Derive one positive point prompt per convergence-density component.
 557
 558    The v1 counterpart intersects thresholded centre and boundary distances; UniSAM2 predicts directed
 559    distances instead, so the candidates come from the flow-convergence density that the sparse
 560    post-processing also seeds from, thresholded lower.
 561
 562    Args:
 563        foreground: Foreground probability map, shape (Y, X).
 564        directed_distances: Distance channels stacked along axis 0. A leading z-channel is dropped, so
 565            `prediction[1:4]` can be passed regardless of dimensionality.
 566        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
 567            for any of the tunable parameters below left as None, see `default_prompt_generation`.
 568        candidate_threshold: Density threshold for proposing candidates. Lower proposes more. The density
 569            of a component scales with the object's area, so this is coupled to object size.
 570        foreground_threshold: Foreground binarisation threshold, which bounds the pixels that can be
 571            proposed from.
 572        n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a pixel is
 573            advected, which has to be enough to reach the object's centre.
 574        dt: Integration step size. Mostly only the product with 'n_iter' matters.
 575        sigma: Gaussian sigma for smoothing the convergence-density map.
 576        min_candidate_size: Discard components smaller than this, which are noise rather than objects.
 577        n_threads: Number of threads for the flow computation.
 578
 579    Returns:
 580        The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1)}, or None if none were found.
 581    """
 582    defaults = default_prompt_generation(model_type, is_volume=False)
 583    if candidate_threshold is None:
 584        candidate_threshold = defaults["candidate_threshold"]
 585    if foreground_threshold is None:
 586        foreground_threshold = defaults["foreground_threshold"]
 587    if n_iter is None:
 588        n_iter = defaults["n_iter"]
 589    if dt is None:
 590        dt = DEFAULT_PROMPT_GENERATION["dt"]
 591    if sigma is None:
 592        sigma = defaults["sigma"]
 593    if min_candidate_size is None:
 594        min_candidate_size = defaults["min_candidate_size"]
 595
 596    if directed_distances.shape[0] > foreground.ndim:
 597        directed_distances = directed_distances[-foreground.ndim:]
 598
 599    fg_mask = foreground > foreground_threshold
 600    density = _compute_flow_density(
 601        directed_distances, fg_mask, n_iter=int(n_iter), dt=dt, sigma=sigma, n_threads=n_threads,
 602    )
 603    candidates = label(density > candidate_threshold)
 604
 605    if min_candidate_size > 0:
 606        ids, sizes = np.unique(candidates, return_counts=True)
 607        discard = ids[(sizes < min_candidate_size) & (ids > 0)]
 608        if discard.size:
 609            candidates[np.isin(candidates, discard)] = 0
 610    if candidates.max() == 0:
 611        return None
 612
 613    # The interior point rather than the centroid, which can lie outside a curved object.
 614    centers = interior_points(candidates)
 615    if len(centers) == 0:
 616        return None
 617
 618    return {
 619        "points": np.ascontiguousarray(centers[:, ::-1], dtype="float32")[:, None, :],  # SAM2 wants XY
 620        "point_labels": np.ones((len(centers), 1), dtype="int32"),
 621    }
 622
 623
 624def derive_volume_prompts(
 625    foreground: np.ndarray,
 626    directed_distances: np.ndarray,
 627    model_type: str = DEFAULT_MODEL,
 628    candidate_threshold: Optional[Union[float, Sequence[float]]] = None,
 629    foreground_threshold: Optional[float] = None,
 630    n_iter: Optional[int] = None,
 631    dt: Optional[float] = None,
 632    sigma: Optional[float] = None,
 633    spacing: Optional[tuple] = None,
 634    min_candidate_size: Optional[int] = None,
 635    n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
 636) -> Optional[Dict[str, np.ndarray]]:
 637    """Derive one positive point prompt, on one slice, per volumetric convergence-density component.
 638
 639    The volumetric counterpart of `derive_point_prompts`. The flow is integrated in 3d, so a component
 640    of the resulting density is a whole object rather than one of its cross-sections, and each object
 641    is prompted once instead of once per slice. The prompt is placed on the slice where the component
 642    converges most, which is the slice the video predictor propagates away from in both directions.
 643
 644    Args:
 645        foreground: Foreground probability map, shape (Z, Y, X).
 646        directed_distances: Distance channels stacked along axis 0, shape (3, Z, Y, X).
 647        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
 648            for any of the tunable parameters below left as None, see `default_prompt_generation`.
 649        candidate_threshold: Density threshold for proposing candidates, or several of them. Lower
 650            proposes more, but also merges the peaks of touching objects into one component, so a
 651            ladder recovers what a single threshold cannot separate.
 652        foreground_threshold: Foreground binarisation threshold, which bounds the voxels that can be
 653            proposed from.
 654        n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a voxel is
 655            advected, which has to be enough to reach the object's centre.
 656        dt: Integration step size. Mostly only the product with 'n_iter' matters.
 657        sigma: Gaussian sigma for smoothing the convergence-density map.
 658        spacing: Anisotropic voxel spacing, e.g. (4, 1, 1), for physically isotropic smoothing.
 659        min_candidate_size: Discard components smaller than this, which are noise rather than objects.
 660        n_threads: Number of threads for the flow computation.
 661
 662    Returns:
 663        The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1), 'frames': (N,) slice
 664        indices}, or None if no candidate was found.
 665    """
 666    if foreground.ndim != 3:
 667        raise ValueError(f"Volumetric prompt generation expects a (Z, Y, X) foreground map, got {foreground.shape}.")
 668    if directed_distances.shape[0] != 3:
 669        raise ValueError(f"Expected 3 distance channels, got {directed_distances.shape[0]}.")
 670
 671    defaults = default_prompt_generation(model_type, is_volume=True)
 672    if candidate_threshold is None:
 673        candidate_threshold = defaults["candidate_threshold"]
 674    if foreground_threshold is None:
 675        foreground_threshold = defaults["foreground_threshold"]
 676    if n_iter is None:
 677        n_iter = defaults["n_iter"]
 678    if dt is None:
 679        dt = DEFAULT_PROMPT_GENERATION["dt"]
 680    if sigma is None:
 681        sigma = defaults["sigma"]
 682    if min_candidate_size is None:
 683        min_candidate_size = defaults["min_candidate_size"]
 684
 685    fg_mask = foreground > foreground_threshold
 686    density = _compute_flow_density(
 687        directed_distances, fg_mask, n_iter=int(n_iter), dt=dt, sigma=sigma, spacing=spacing,
 688        n_threads=n_threads,
 689    )
 690
 691    levels = sorted(np.atleast_1d(np.asarray(candidate_threshold, dtype="float32")).tolist(), reverse=True)
 692    points, frames, seen = [], [], set()
 693    # Descending, so that the peaks a lower threshold merges into one component are proposed first.
 694    for threshold in levels:
 695        candidates = label(density > threshold)
 696        if min_candidate_size > 0:
 697            ids, sizes = np.unique(candidates, return_counts=True)
 698            discard = ids[(sizes < min_candidate_size) & (ids > 0)]
 699            if discard.size:
 700                candidates[np.isin(candidates, discard)] = 0
 701
 702        for index, bounding_box in enumerate(find_objects(candidates)):
 703            if bounding_box is None:
 704                continue
 705            component = candidates[bounding_box] == (index + 1)
 706            component_density = np.where(component, density[bounding_box], 0.0)
 707            # The most converged slice, i.e. the one closest to the object's centre.
 708            z = int(np.argmax(component_density.sum(axis=(1, 2))))
 709            plane = component_density[z]
 710            # The density peak: it is inside the component and the least ambiguous prompt.
 711            y, x = np.unravel_index(int(np.argmax(plane)), plane.shape)
 712            anchor = (bounding_box[0].start + z, bounding_box[1].start + y, bounding_box[2].start + x)
 713            # A component that no lower threshold has merged peaks at the same voxel at every level.
 714            if anchor in seen:
 715                continue
 716            seen.add(anchor)
 717            frames.append(anchor[0])
 718            points.append((anchor[2], anchor[1]))  # SAM2 wants XY.
 719
 720    if not points:
 721        return None
 722
 723    return {
 724        "points": np.array(points, dtype="float32")[:, None, :],
 725        "point_labels": np.ones((len(points), 1), dtype="int32"),
 726        "frames": np.array(frames, dtype="int64"),
 727    }
 728
 729
 730def _record_mask(record: Dict[str, Any]) -> np.ndarray:
 731    """The record's mask as a plain numpy array, whatever tensor type it arrived in."""
 732    mask = record["segmentation"]
 733    return mask.numpy() if hasattr(mask, "numpy") else np.asarray(mask)
 734
 735
 736def _largest_component(mask: np.ndarray) -> np.ndarray:
 737    """The largest connected component of a binary mask, with diagonal neighbours connected."""
 738    components = label(mask, connectivity=mask.ndim)
 739    sizes = np.bincount(components.ravel().astype("int64"))[1:]
 740    if len(sizes) < 2:
 741        return mask
 742    return components == (sizes.argmax() + 1)
 743
 744
 745def merge_by_score(
 746    records: List[Dict[str, Any]], shape: tuple, max_overlap: float = 0.3, min_size: int = 50,
 747    max_size_factor: Optional[float] = None, keep_largest_component: bool = False,
 748    return_matches: bool = False, return_reasons: bool = False,
 749) -> Union[np.ndarray, tuple]:
 750    """Merge prediction records in descending score order, each claiming only unclaimed pixels.
 751
 752    Linear in the number of candidates, where `micro_sam.util.apply_nms` is quadratic, and marginally
 753    better on livecell: truncating a later mask preserves the better-scoring instance's boundary.
 754
 755    A record carries a 'bounding_box' (a tuple of slices) and its mask is only the crop inside that
 756    box, so both the merge and the records themselves scale with the objects rather than with the
 757    image. A volumetric mask per object would otherwise make the 3d generator run out of memory.
 758
 759    Args:
 760        records: The prediction records, as produced by `AutomaticPromptGenerator._apply_prompts`.
 761        shape: The spatial shape of the output.
 762        max_overlap: Reject a candidate when more than this fraction of it is already claimed. This is
 763            the duplicate suppression of the merge.
 764        min_size: Minimum object size to keep.
 765        max_size_factor: Reject a candidate larger than this multiple of the median record size.
 766            Catches propagation drift: a track that grows onto background instead of ending produces
 767            an occasional candidate many times larger than every real object, most easily seen next
 768            to the rest of the same call's candidates rather than by any fixed size. None (the
 769            default) applies no such cap.
 770        keep_largest_component: Whether to paint only the largest connected component of a
 771            candidate's unclaimed pixels. Truncating a mask by the better-scoring ones around it
 772            leaves specks and slivers where their boundaries disagree by a pixel or two, which
 773            would otherwise stay part of the instance, detached from it. Dropping them keeps every
 774            instance in one piece; on the 2d benchmark it never lowered mSA and gains up to 0.002.
 775        return_matches: Whether to also return which record made each instance.
 776        return_reasons: Whether to also return why each record was kept or dropped. A candidate is
 777            'too small', 'too large', a 'duplicate' when a better-scoring mask already claims more
 778            than 'max_overlap' of it, 'truncated below min size' when too few of its pixels are free,
 779            or 'kept'. This is what the merge does, reported rather than recomputed.
 780
 781    Returns:
 782        The instance segmentation, uint32 array. If `return_matches`, additionally a mapping from
 783        every instance id to the index of the record that made it. If `return_reasons`, additionally
 784        the reason per record, in the order the records were given.
 785    """
 786    out = np.zeros(shape, dtype="uint32")
 787    next_id = 1
 788    scores = np.array([record["predicted_iou"] * record["stability_score"] for record in records])
 789    if not np.isfinite(scores).all():
 790        raise ValueError("Every merge score must be finite.")
 791    max_size = None
 792    if max_size_factor is not None and records:
 793        areas = np.array([int(_record_mask(record).sum()) for record in records])
 794        max_size = max_size_factor * np.median(areas)
 795    full_box = tuple(slice(None) for _ in shape)
 796    matches = {}
 797    reasons = ["" for _ in records]
 798    for index in sorted(range(len(records)), key=lambda candidate: (-scores[candidate], candidate)):
 799        record = records[index]
 800        mask = _record_mask(record)
 801        area = int(mask.sum())
 802        if area < min_size:
 803            reasons[index] = "too small"
 804            continue
 805        if max_size is not None and area > max_size:
 806            reasons[index] = "too large"
 807            continue
 808        # A view, so painting the fresh pixels below writes straight into the output.
 809        box = record.get("bounding_box", full_box)
 810        target = out[box]
 811        claimed = target[mask]
 812        n_claimed = int(np.count_nonzero(claimed))
 813        if n_claimed / area > max_overlap:
 814            reasons[index] = "duplicate"
 815            continue
 816        fresh = mask & (target == 0)
 817        if keep_largest_component:
 818            fresh = _largest_component(fresh)
 819        n_gained = int(fresh.sum())
 820        if n_gained < min_size:
 821            reasons[index] = "truncated below min size"
 822            continue
 823        target[fresh] = next_id
 824        reasons[index] = "kept"
 825        matches[next_id] = int(index)
 826        next_id += 1
 827
 828    result = (out,)
 829    if return_matches:
 830        result += (matches,)
 831    if return_reasons:
 832        result += (reasons,)
 833    return result[0] if len(result) == 1 else result
 834
 835
 836def _records_shape(records: List[Dict[str, Any]]) -> tuple:
 837    """The smallest canvas that holds every record, which is all a merge of cropped masks needs."""
 838    boxes = [record["bounding_box"] for record in records]
 839    return tuple(max(box[axis].stop for box in boxes) for axis in range(len(boxes[0])))
 840
 841
 842def _volume_records(
 843    video_segments: Dict[int, Dict[int, np.ndarray]], candidates: List[dict], shape: tuple,
 844) -> List[Dict[str, Any]]:
 845    """Assemble one volumetric mask record per propagated object, cropped to its bounding box.
 846
 847    The propagation yields its masks slice by slice. Holding one full-volume mask per object would
 848    scale with the object count times the volume, so each object is kept as its bounding-box crop,
 849    which scales with the objects themselves. `merge_by_score` paints from those crops.
 850
 851    Args:
 852        video_segments: The propagation result, {frame: {object_id: mask}}, as returned by
 853            `PromptableSegmentation3D.propagate_prompts`.
 854        candidates: The candidates of this pass, in the order their object ids were assigned.
 855        shape: The shape of the volume, (Z, Y, X).
 856
 857    Returns:
 858        The records, carrying the anchor-slice scores of their candidate for the merge.
 859    """
 860    per_object = {}
 861    for frame, masks in sorted(video_segments.items()):
 862        for object_id, mask in masks.items():
 863            mask = _crop_to_original_shape(np.asarray(mask).squeeze(), shape[-2:])
 864            # Two reductions rather than an np.nonzero per mask, which materializes every index: this
 865            # runs once per object and slice, so it is a real share of a volume's time.
 866            rows_any, columns_any = mask.any(axis=1), mask.any(axis=0)
 867            if not rows_any.any():
 868                continue
 869            y0, y1 = int(rows_any.argmax()), len(rows_any) - int(rows_any[::-1].argmax())
 870            x0, x1 = int(columns_any.argmax()), len(columns_any) - int(columns_any[::-1].argmax())
 871            per_object.setdefault(object_id, []).append(
 872                (int(frame), y0, y1, x0, x1, mask[y0:y1, x0:x1].copy())
 873            )
 874
 875    records = []
 876    for object_id, entries in per_object.items():
 877        candidate = candidates[object_id - 1]
 878        # The frames are in ascending order, so the first and last entry bound the object in z.
 879        z0, z1 = entries[0][0], entries[-1][0] + 1
 880        y0, x0 = min(entry[1] for entry in entries), min(entry[3] for entry in entries)
 881        y1, x1 = max(entry[2] for entry in entries), max(entry[4] for entry in entries)
 882
 883        local = np.zeros((z1 - z0, y1 - y0, x1 - x0), dtype=bool)
 884        for frame, from_y, to_y, from_x, to_x, mask in entries:
 885            local[frame - z0, from_y - y0:to_y - y0, from_x - x0:to_x - x0] = mask
 886
 887        records.append({
 888            "segmentation": local,
 889            "bounding_box": (slice(z0, z1), slice(y0, y1), slice(x0, x1)),
 890            "predicted_iou": candidate["score"],
 891            "stability_score": candidate["stability"],
 892        })
 893    return records
 894
 895
 896class AutomaticPromptGenerator(UniSAM2InstanceSegmentation):
 897    """Generates an instance segmentation automatically, from prompts derived from the UniSAM2 decoder.
 898
 899    Used in the same way as `UniSAM2InstanceSegmentation`, and the counterpart of
 900    `micro_sam.v1.instance_segmentation.AutomaticPromptGenerator`:
 901    ```python
 902    segmenter = AutomaticPromptGenerator(model, predictor)
 903    segmenter.initialize(image, ndim=2)  # Encode the image, then run the decoder on the encoding.
 904    masks = segmenter.generate(score_threshold=0.6)  # Prompt, then merge the masks.
 905    ```
 906
 907    Volumes are segmented by passing the SAM2 video predictor instead of an image predictor:
 908    ```python
 909    segmenter = AutomaticPromptGenerator(model, video_predictor)
 910    segmenter.initialize(volume, ndim=3)
 911    masks = segmenter.generate()  # Prompt one slice per object, propagate, then merge the masks.
 912    ```
 913    The decoder finds the objects and the interactive branch segments them either way. What differs is
 914    that an object's mask comes from propagating one prompt through the volume rather than from a
 915    single forward pass, and that the candidates are scored in 2d on the slice they are prompted on,
 916    which drops the weak and the duplicate ones before the propagation - which is where the cost is.
 917    The decoder and the video predictor read the same 3d embeddings, so the volume is encoded once.
 918
 919    Args:
 920        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
 921        predictor: The SAM2 image predictor for the interactive branch of the same model, or its
 922            video predictor, which is what a volume is prompted with.
 923        device: The device the model lives on (used for the non-tiled 2d decoder).
 924        inference_device: The device intent used as the `devices=None` fallback. Defaults to the
 925            model device (single GPU); pass None to fan out over all visible GPUs, or a device / list.
 926    """
 927
 928    # Read by `automatic_instance_segmentation` to decide whether to pass the AIS 'mode' argument.
 929    _has_postprocessing_mode = False
 930    _model_type = DEFAULT_MODEL
 931
 932    def __init__(
 933        self,
 934        model: torch.nn.Module,
 935        predictor,
 936        device: Optional[Union[str, torch.device]] = None,
 937        inference_device: Devices = USE_MODEL_DEVICE,
 938    ) -> None:
 939        super().__init__(model, device=device, inference_device=inference_device)
 940        self._video_predictor = predictor if hasattr(predictor, "propagate_in_video") else None
 941        if self._video_predictor is None:
 942            self._predictor = configure_image_predictor(predictor)
 943        else:
 944            # Build the image predictor on the video predictor's weights.
 945            self._predictor = get_sam2_image_predictor(predictor)
 946        predictor = self._predictor
 947
 948        self._image_embeddings = None
 949        self._volume = None
 950        self._propagator = None
 951        self._offload_to_cpu = None
 952        self._max_cached_frames = None
 953        self._temporary_embedding_path = None
 954        self._i = None
 955        self._owns_image_embeddings = False
 956        self._last_generation_stats = {}
 957        # Set by 'TiledAutomaticPromptGenerator' to this block's full spatial halo before propagating,
 958        # so pruning never drops a candidate the halo-overlap multicut might need; None elsewhere.
 959        self._pruning_protected_margin: Optional[tuple] = None
 960        self._scoring_predictor_pool = None
 961        # The embedding cache is keyed on these, which a SAM2 image predictor does not carry itself.
 962        sam2_model = getattr(predictor, "model", None)
 963        if getattr(predictor, "model_type", None) is None:
 964            predictor.model_type = getattr(sam2_model, "model_type", None) or "hvit"
 965        if getattr(predictor, "model_name", None) is None:
 966            predictor.model_name = getattr(sam2_model, "model_name", None) or predictor.model_type
 967
 968    def _encode(self, image: np.ndarray) -> dict:
 969        """Run the image encoder once and return the embeddings that both branches use."""
 970        self._predictor.reset_predictor()
 971        # Preserve each microscopy channel's contrast before SAM2 sees the image.
 972        encode_image(self._predictor, to_image(image))
 973        return {
 974            "features": self._predictor.get_image_embedding().cpu().numpy(),
 975            "high_res_feats": self._predictor._features["high_res_feats"],
 976            "input_size": self._predictor.model.image_size,
 977            "original_size": self._predictor._orig_hw,
 978        }
 979
 980    def _prepare_image_embeddings(self, image_embeddings: dict, i: Optional[int]) -> dict:
 981        """Prepare image embeddings for the interactive branch."""
 982        if i is None:
 983            set_precomputed(self._predictor, image_embeddings)
 984            return image_embeddings
 985
 986        if "fpn" not in image_embeddings:
 987            raise ValueError("A slice index requires video-style embeddings with FPN features.")
 988        _set_image_predictor_from_3d_embeddings(self._predictor, image_embeddings, i)
 989        return {
 990            "features": self._predictor.get_image_embedding().detach().cpu().numpy(),
 991            "high_res_feats": self._predictor._features["high_res_feats"],
 992            "input_size": self._predictor.model.image_size,
 993            "original_size": self._predictor._orig_hw,
 994        }
 995
 996    def initialize(
 997        self,
 998        image: np.ndarray,
 999        ndim: int = 2,
1000        image_embeddings: Optional[dict] = None,
1001        i: Optional[int] = None,
1002        save_path: Optional[str] = None,
1003        verbose: bool = False,
1004        offload_to_cpu: Optional[bool] = None,
1005        cache_all_slices: bool = False,
1006        lazy_embeddings: bool = True,
1007        normalization_bounds: Optional[tuple] = None,
1008        **kwargs,
1009    ) -> None:
1010        """Encode the input, run the decoder on that encoding and leave the predictor ready to be prompted.
1011
1012        Both branches of a joint checkpoint share their image encoder weights, so one pass serves both
1013        and `generate` can be called repeatedly without any further encoding.
1014
1015        Args:
1016            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
1017            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
1018            image_embeddings: Optional precomputed image embeddings. If given, the encoder does not run.
1019            i: The slice index for video-style embeddings. By default the embeddings contain one image.
1020            save_path: Optional path to cache the embeddings of a volume in a zarr container. Without
1021                one an ephemeral store is used, which `clear_state` removes.
1022            verbose: Whether to print progress while the embeddings of a volume are computed.
1023            offload_to_cpu: Whether a volume's tracking state is held on the host rather than on the
1024                device. False propagates the same masks 6-11% faster, for the memory of one pass of
1025                objects across the volume, which is about 17 MB per slice at the default pass size.
1026                None leaves the choice to `PromptableSegmentation3D`, which offloads on cuda.
1027            cache_all_slices: Whether every slice's features stay on the device while a volume is
1028                propagated. A pass walks the whole volume, so a cache shorter than it is never hit
1029                and every slice is fetched again on every pass - which is most of the run on a deep
1030                volume. Costs about 90 MB of device memory per slice.
1031            lazy_embeddings: Whether a volume's embeddings are read from their store slice by slice.
1032                False holds them in host memory instead, which makes the fetch above much cheaper
1033                without spending device memory.
1034            normalization_bounds: Volumes only. Precomputed (lower, upper) percentile bounds (see
1035                `batched_inference._volume_normalization_bounds`), normally computed from `image`
1036                itself. Pass this when `image` is only a tile/block of a larger volume, so it shares
1037                that volume's bounds instead of estimating its own from its own, smaller, biased crop
1038                (see `TiledAutomaticPromptGenerator.generate`).
1039            kwargs: Additional arguments for `UniSAM2InstanceSegmentation.initialize`.
1040        """
1041        if ndim not in (2, 3):
1042            raise ValueError(f"Automatic prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
1043
1044        # A volume leaves a propagator and possibly a temporary embedding store behind. Release both
1045        # before replacing its state, including when the next input is a 2d image.
1046        if self._volume is not None or self._temporary_embedding_path is not None:
1047            self.clear_state()
1048
1049        if ndim == 3:
1050            self._i = None
1051            self._initialize_volume(
1052                image, image_embeddings, save_path, verbose, offload_to_cpu, cache_all_slices,
1053                lazy_embeddings, normalization_bounds=normalization_bounds, **kwargs
1054            )
1055            return
1056
1057        owns_image_embeddings = image_embeddings is None
1058        if image_embeddings is None:
1059            image_embeddings = self._encode(image)
1060        else:
1061            image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1062        super().initialize(image, ndim=ndim, image_embeddings=image_embeddings, **kwargs)
1063        self._image_embeddings = image_embeddings
1064        self._i = None
1065        self._owns_image_embeddings = owns_image_embeddings
1066
1067    def _build_propagator(self, volume, image_embeddings) -> ReplicatedPromptableSegmentation3D:
1068        """The video predictor this volume is propagated with, one state per inference device."""
1069        return ReplicatedPromptableSegmentation3D(
1070            self._video_predictor, volume, image_embeddings, devices=self._inference_devices(None),
1071            offload_state_to_cpu=self._offload_to_cpu, max_cached_frames=self._max_cached_frames,
1072            release_stale_mask_memory=True,
1073        )
1074
1075    def _initialize_volume(
1076        self, volume, image_embeddings, save_path, verbose, offload_to_cpu, cache_all_slices,
1077        lazy_embeddings, normalization_bounds=None, **kwargs
1078    ) -> None:
1079        """Encode the volume, run the decoder on that encoding and initialize the video predictor."""
1080        if self._video_predictor is None:
1081            raise ValueError(
1082                "Volumetric prompt generation prompts the SAM2 video predictor, so it has to be "
1083                "constructed with one instead of an image predictor."
1084            )
1085        if volume.ndim not in (3, 4):
1086            raise ValueError(
1087                f"Volumetric prompt generation expects a (Z, Y, X) or (Z, Y, X, C) volume, got shape {volume.shape}."
1088            )
1089
1090        owns_image_embeddings = image_embeddings is None
1091        if image_embeddings is None:
1092            path = save_path
1093            if path is None:
1094                self._temporary_embedding_path = make_temp_embedding_path()
1095                path = self._temporary_embedding_path
1096            image_embeddings = precompute_image_embeddings(
1097                self._video_predictor, volume, save_path=path, ndim=3, verbose=verbose,
1098                lazy_loading=lazy_embeddings, devices=self._inference_devices(None),
1099                norm_bounds=normalization_bounds,
1100            )
1101
1102        UniSAM2InstanceSegmentation.initialize(self, volume, ndim=3, image_embeddings=image_embeddings, **kwargs)
1103        self._image_embeddings = image_embeddings
1104        self._owns_image_embeddings = owns_image_embeddings
1105        self._volume = volume
1106        self._offload_to_cpu = offload_to_cpu
1107        self._max_cached_frames = int(volume.shape[0]) if cache_all_slices else None
1108        self._propagator = self._build_propagator(volume, image_embeddings)
1109
1110    def get_state(self) -> dict:
1111        """Return the decoder predictions and the image embeddings, so that both branches can be restored.
1112
1113        `generate` also prompts the interactive branch, which needs the encoding of the same input. For
1114        a volume the volume itself is part of the state, because the video predictor is initialized on it.
1115        """
1116        state = super().get_state()
1117        state["image_embeddings"] = self._image_embeddings
1118        if self._volume is not None:
1119            state["volume"] = self._volume
1120        return state
1121
1122    def set_state(self, state: dict) -> None:
1123        """Restore the decoder predictions and the encoding of the input they belong to.
1124
1125        The state must hold either 'image_embeddings' or 'image'. Without one, `generate` would prompt
1126        whatever image the predictor still holds. A volumetric state must also hold 'volume'.
1127
1128        Args:
1129            state: The state, as returned by `get_state`, or a dict with 'prediction' and 'image'.
1130        """
1131        image_embeddings = state.get("image_embeddings")
1132        volume = state.get("volume")
1133        i = state.get("i")
1134
1135        if volume is not None:
1136            if image_embeddings is None:
1137                raise ValueError("A volumetric state must hold the 'image_embeddings' of its volume.")
1138            super().set_state(state)
1139            self._volume = volume
1140            self._propagator = self._build_propagator(volume, image_embeddings)
1141            self._i = None
1142        else:
1143            if image_embeddings is None:
1144                if "image" not in state:
1145                    raise ValueError("The state must hold either 'image_embeddings' or 'image'.")
1146                image_embeddings = self._encode(state["image"])
1147            else:
1148                image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1149            super().set_state(state)
1150            self._i = None
1151        self._image_embeddings = image_embeddings
1152        self._owns_image_embeddings = False
1153
1154    def clear_state(self) -> None:
1155        """Clear the decoder predictions and the input that is set on the predictor."""
1156        owned_embeddings = self._image_embeddings if getattr(self, "_owns_image_embeddings", False) else None
1157        super().clear_state()
1158        self._image_embeddings = None
1159        self._i = None
1160        self._owns_image_embeddings = False
1161        self._predictor.reset_predictor()
1162        self._volume = None
1163        # Built on the propagator's replicas, so it must not outlive them.
1164        self._scoring_predictor_pool = None
1165        if self._propagator is not None:
1166            self._propagator.reset_predictor()
1167            self._propagator = None
1168        try:
1169            close = getattr(owned_embeddings, "close", None)
1170            if close is not None:
1171                close()
1172        finally:
1173            if self._temporary_embedding_path is not None:
1174                shutil.rmtree(self._temporary_embedding_path, ignore_errors=True)
1175                self._temporary_embedding_path = None
1176
1177    @torch.no_grad()
1178    def generate(
1179        self,
1180        candidate_threshold: Optional[Union[float, Sequence[float]]] = None,
1181        foreground_threshold: Optional[float] = None,
1182        n_iter: Optional[int] = None,
1183        dt: Optional[float] = None,
1184        sigma: Optional[float] = None,
1185        spacing: Optional[tuple] = None,
1186        min_candidate_size: Optional[int] = None,
1187        score_threshold: Optional[float] = None,
1188        max_overlap: Optional[float] = None,
1189        min_size: Optional[int] = None,
1190        max_size_factor: Optional[float] = DEFAULT_PROMPT_GENERATION["max_size_factor"],
1191        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1192        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1193        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1194        n_objects_per_pass: int = DEFAULT_PROMPT_GENERATION["n_objects_per_pass"],
1195        early_stop_patience: Optional[int] = DEFAULT_PROMPT_GENERATION["early_stop_patience"],
1196        propagation_waves: int = DEFAULT_PROMPT_GENERATION["propagation_waves"],
1197        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1198        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1199        verbose: bool = False,
1200        pbar_init: Optional[Callable] = None,
1201        pbar_update: Optional[Callable] = None,
1202    ) -> np.ndarray:
1203        """Derive prompts from the stored predictions, apply them and merge the masks.
1204
1205        Args:
1206            candidate_threshold: Density threshold for proposing candidates, or several of them for
1207                a volume. By default resolved per model type and dimensionality, see
1208                `default_prompt_generation`.
1209            foreground_threshold: Foreground binarisation threshold. Here it only limits which pixels can
1210                be proposed from, since the masks come from the interactive branch, so it trades candidate
1211                recall rather than boundary quality.
1212            n_iter: Number of flow-integration steps for the candidate density.
1213            dt: Integration step size. Mostly only the product with 'n_iter' matters, which is the
1214                distance a pixel is advected.
1215            sigma: Gaussian sigma for smoothing the candidate density. Less smoothing leaves more peaks,
1216                which costs precision for the sparse post-processing but buys candidate recall here.
1217            spacing: Anisotropic voxel spacing of a volume, e.g. (4, 1, 1).
1218            min_candidate_size: Discard density components smaller than this.
1219            score_threshold: Discard candidates whose predicted IoU is below this.
1220            max_overlap: Reject a candidate when more than this fraction of it is already claimed. For a
1221                volume this applies on the slice a candidate is prompted on and again on the 3d merge.
1222            min_size: Minimum object size in the result.
1223            max_size_factor: Volumes only. Reject a candidate this many times larger than the median
1224                size among the candidates it is merged against, which catches propagation drift (a
1225                track that grows onto background instead of ending). None (the default) applies no
1226                such cap; see `merge_by_score`.
1227            refinement: Optional second round, a '+'-joined combination of 'points' (the first
1228                round's prompts grouped onto each merged instance, see `derive_refinement_prompts`),
1229                'boxes' (its bounding box) and 'masks' (its mask as a logit prompt). None runs no second
1230                round. 'default' (the default) takes the mode of `default_prompt_generation`. For a
1231                volume the round runs on each candidate's anchor slice, before the propagation, and
1232                produces the conditioning that propagation starts from rather than a finished mask,
1233                see `_refine_anchors`.
1234            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1235                components; see `DEFAULT_REFINEMENT`, or `DEFAULT_REFINEMENT_3D` for a volume, for
1236                the accepted keys and their defaults.
1237            multimasking: Whether to predict several masks per point and keep the best scoring one. A
1238                single point is ambiguous between one object and a cluster, so this is on by default.
1239            n_objects_per_pass: Number of objects propagated together through a volume. The video
1240                predictor runs them as one batch, so this trades device memory against the pass count.
1241            propagation_waves: Tiled volumes only. Rounds the candidates are propagated in, highest
1242                scoring first, dropping between rounds those an already-propagated instance covers by
1243                more than 'max_overlap'. One round propagates every candidate, see
1244                `DEFAULT_PROMPT_GENERATION`.
1245            early_stop_patience: Stop a propagation pass after this many consecutive slices in which
1246                every object of the pass is empty. None propagates through the whole volume. Two by
1247                default: propagating past the end of every object of a pass only reproduces empty
1248                masks, so this saves work without changing the result. Raise it where an object may
1249                disappear and reappear, because a stop that fires mid-object truncates it.
1250            batch_size: Number of prompts per forward pass.
1251            n_threads: Number of threads for the flow integration the candidates come from.
1252            verbose: Whether to show progress over the propagation passes of a volume.
1253            pbar_init: Initialize an external progress stage with its total and description.
1254            pbar_update: Advance the external progress bar after completed work.
1255
1256        Returns:
1257            The instance segmentation, uint32 array with the spatial shape of the prediction.
1258        """
1259        if not self._is_initialized:
1260            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1261
1262        self._last_generation_stats = {}
1263        shape = self._prediction[0].shape
1264        # The prediction carries the dimensionality it was run at: (4, Y, X) or (4, Z, Y, X).
1265        is_volume = self._prediction.ndim == 4
1266        defaults = default_prompt_generation(self._model_type, is_volume=is_volume)
1267        if candidate_threshold is None:
1268            candidate_threshold = defaults["candidate_threshold"]
1269        if score_threshold is None:
1270            score_threshold = defaults["score_threshold"]
1271        if max_overlap is None:
1272            max_overlap = defaults["max_overlap"]
1273        if min_size is None:
1274            min_size = defaults["min_size"]
1275        if refinement == "default":
1276            refinement = defaults["refinement"]
1277
1278        if is_volume:
1279            components = resolved = None
1280            if refinement is not None:
1281                components, resolved = _parse_refinement(refinement, refinement_kwargs, is_volume=True)
1282            if pbar_init is not None:
1283                pbar_init(1, "APG: deriving volume prompts")
1284            prompts = derive_volume_prompts(
1285                self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1286                candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1287                n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing,
1288                min_candidate_size=min_candidate_size, n_threads=n_threads,
1289            )
1290            if pbar_update is not None:
1291                pbar_update(1)
1292            if prompts is None:
1293                self._last_generation_stats = {
1294                    "proposed_candidates": 0,
1295                    "scored_candidates": 0,
1296                    "unique_anchor_slices": 0,
1297                    "propagation_passes": 0,
1298                    "propagated_frame_steps": 0,
1299                    "early_stopped_frame_steps": 0,
1300                }
1301                if components is not None:
1302                    self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1303                return np.zeros(shape, dtype="uint32")
1304            self._last_generation_stats["proposed_candidates"] = len(prompts["points"])
1305            if components is not None:
1306                self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1307            # The refinement's forwards are not wrapped by '_apply_prompts', which has its own.
1308            if components is None:
1309                candidates = self._score_candidates(
1310                    prompts, multimasking=multimasking, batch_size=batch_size,
1311                    score_threshold=score_threshold, max_overlap=max_overlap,
1312                    components=components, refinement_kwargs=resolved,
1313                    pbar_init=pbar_init, pbar_update=pbar_update,
1314                )
1315            else:
1316                with autocast(self._predictor.device):
1317                    candidates = self._score_candidates(
1318                        prompts, multimasking=multimasking, batch_size=batch_size,
1319                        score_threshold=score_threshold, max_overlap=max_overlap,
1320                        components=components, refinement_kwargs=resolved,
1321                        pbar_init=pbar_init, pbar_update=pbar_update,
1322                    )
1323            self._last_generation_stats["scored_candidates"] = len(candidates)
1324            records = self._propagate_candidates(
1325                candidates, n_objects_per_pass=n_objects_per_pass,
1326                early_stop_patience=early_stop_patience, verbose=verbose, max_overlap=max_overlap,
1327                propagation_waves=propagation_waves, pbar_init=pbar_init, pbar_update=pbar_update,
1328            )
1329            # Tiled records arrive grouped by tile and need their halo overlaps resolved, which
1330            # '_merge' does polymorphically; an untiled volume merges them flat.
1331            if pbar_init is not None:
1332                pbar_init(1, "APG: merging volume masks")
1333            segmentation, _ = self._merge(
1334                records, shape, score_threshold=score_threshold, max_overlap=max_overlap,
1335                min_size=min_size, max_size_factor=max_size_factor,
1336            )
1337            if pbar_update is not None:
1338                pbar_update(1)
1339            return segmentation
1340
1341        proposals = self.propose(
1342            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1343            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size,
1344            multimasking=multimasking, batch_size=batch_size, n_threads=n_threads,
1345            pbar_init=pbar_init, pbar_update=pbar_update,
1346        )
1347        return self.select(
1348            proposals, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1349            refinement=refinement, refinement_kwargs=refinement_kwargs, batch_size=batch_size,
1350        )
1351
1352    @torch.no_grad()
1353    def propose(
1354        self,
1355        candidate_threshold: Optional[float] = None,
1356        foreground_threshold: Optional[float] = None,
1357        n_iter: Optional[int] = None,
1358        dt: Optional[float] = None,
1359        sigma: Optional[float] = None,
1360        min_candidate_size: Optional[int] = None,
1361        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1362        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1363        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1364        pbar_init: Optional[Callable] = None,
1365        pbar_update: Optional[Callable] = None,
1366    ) -> list:
1367        """Derive the prompts and turn them into scored mask proposals, without selecting any of them.
1368
1369        This is the half of `generate` that needs the model. Splitting it off lets a parameter sweep
1370        reuse one set of proposals across every value of 'score_threshold', 'max_overlap' and
1371        'min_size', which only filter and merge. Images only: a volume gates its propagation on the
1372        score, so its proposals depend on those parameters too.
1373
1374        Args:
1375            candidate_threshold: Density threshold for proposing candidates, see `derive_point_prompts`.
1376            foreground_threshold: Foreground binarisation threshold.
1377            n_iter: Number of flow-integration steps for the candidate density.
1378            dt: Integration step size.
1379            sigma: Gaussian sigma for smoothing the candidate density.
1380            min_candidate_size: Discard density components smaller than this.
1381            multimasking: Whether to predict several masks per point and keep the best scoring one.
1382            batch_size: Number of prompts per forward pass.
1383            n_threads: Number of threads for the flow integration the candidates come from.
1384            pbar_init: Initialize each progress stage with its total and description.
1385            pbar_update: Advance progress after deriving prompts and each prediction batch.
1386
1387        Returns:
1388            The proposals, to be passed to `select`. Their layout is an implementation detail of the
1389            generator that produced them.
1390        """
1391        if not self._is_initialized:
1392            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1393        if self._prediction.ndim == 4:
1394            raise ValueError("Proposals can only be reused for an image, because a volume gates its propagation.")
1395
1396        if pbar_init is not None:
1397            pbar_init(1, "APG: deriving prompts")
1398        prompts = derive_point_prompts(
1399            self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1400            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1401            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size, n_threads=n_threads,
1402        )
1403        if pbar_update is not None:
1404            pbar_update(1)
1405        if prompts is None:
1406            return []
1407        if pbar_init is not None:
1408            pbar_init((len(prompts["points"]) + batch_size - 1) // batch_size, "APG: prompting batches")
1409        return self._apply(
1410            prompts, multimasking=multimasking, batch_size=batch_size, pbar_update=pbar_update,
1411        )
1412
1413    def select(
1414        self,
1415        proposals: list,
1416        score_threshold: Optional[float] = None,
1417        max_overlap: Optional[float] = None,
1418        min_size: Optional[int] = None,
1419        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1420        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1421        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1422    ) -> np.ndarray:
1423        """Merge the proposals of `propose` into an instance segmentation.
1424
1425        Args:
1426            proposals: The proposals, as returned by `propose` on the same generator.
1427            score_threshold: Discard proposals whose predicted IoU is below this.
1428            max_overlap: Reject a proposal when more than this fraction of it is already claimed.
1429            min_size: Minimum object size in the result.
1430            refinement: Optional second round, a '+'-joined combination of 'points', 'boxes',
1431                and 'masks', or 'default' for the mode of `default_prompt_generation`; see `generate`.
1432            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1433                components; see `DEFAULT_REFINEMENT` for the accepted keys and their defaults.
1434            batch_size: Number of prompts per forward pass of the refinement.
1435
1436        Returns:
1437            The instance segmentation, uint32 array with the spatial shape of the prediction.
1438        """
1439        defaults = default_prompt_generation(self._model_type, is_volume=False)
1440        if score_threshold is None:
1441            score_threshold = defaults["score_threshold"]
1442        if max_overlap is None:
1443            max_overlap = defaults["max_overlap"]
1444        if min_size is None:
1445            min_size = defaults["min_size"]
1446        if refinement == "default":
1447            refinement = defaults["refinement"]
1448
1449        components = resolved = None
1450        if refinement is not None:
1451            components, resolved = _parse_refinement(refinement, refinement_kwargs)
1452
1453        shape = self._prediction[0].shape
1454        if not proposals:
1455            return np.zeros(shape, dtype="uint32")
1456
1457        segmentation, context = self._merge(
1458            proposals, shape, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1459            return_context=components is not None,
1460        )
1461        if components is not None and segmentation.max() > 0:
1462            segmentation = self._refine(segmentation, context, components, resolved, batch_size)
1463        return segmentation
1464
1465    def _region_of(self, context: dict, record_index: int):
1466        """The region a record's instance is re-prompted in, keyed however the generator likes.
1467
1468        A refinement runs region by region, because a tiled generator has to point its predictor at
1469        one tile at a time. Here the whole image is one region, so every record shares the key None.
1470        """
1471        return None
1472
1473    def _region_box(self, key) -> tuple:
1474        """The region's bounding box, as a slice tuple into the segmentation."""
1475        return (slice(None), slice(None))
1476
1477    def _set_region(self, key) -> None:
1478        """Point the predictor at the region. Its image is already set for a single one."""
1479
1480    def _apply(self, prompts: dict, multimasking: bool, batch_size: int, pbar_update=None) -> list:
1481        """Turn the prompts into mask proposals."""
1482        return self._apply_prompts(
1483            self._predictor, prompts, multimasking=multimasking, batch_size=batch_size, pbar_update=pbar_update,
1484        )
1485
1486    def _merge(
1487        self, proposals: list, shape: tuple, score_threshold: float, max_overlap: float, min_size: int,
1488        max_size_factor: Optional[float] = None, return_context: bool = False,
1489    ) -> tuple:
1490        """Merge the mask proposals into an instance segmentation.
1491
1492        Returns:
1493            The segmentation, and the refinement context: the score-filtered records and the mapping
1494            from every instance id to the record that made it. Without `return_context` the context
1495            is None, so the matches are not computed for nothing.
1496        """
1497        records = [record for record in proposals if record["predicted_iou"] >= score_threshold]
1498        if not records:
1499            return np.zeros(shape, dtype="uint32"), None
1500        # Images only: a volume's track may leave its object and come back across slices, and that
1501        # merge is not measured with it.
1502        merge_kwargs = {
1503            "max_overlap": max_overlap, "min_size": min_size, "max_size_factor": max_size_factor,
1504            "keep_largest_component": len(shape) == 2,
1505        }
1506        if not return_context:
1507            return merge_by_score(records, shape, **merge_kwargs), None
1508        segmentation, matches, reasons = merge_by_score(
1509            records, shape, return_matches=True, return_reasons=True, **merge_kwargs,
1510        )
1511        self._last_generation_stats.update({
1512            "proposed_candidates": len(proposals),
1513            "scored_candidates": len(records),
1514            "merge_reasons": {reason: reasons.count(reason) for reason in sorted(set(reasons))},
1515        })
1516        return segmentation, {"proposals": proposals, "records": records, "matches": matches}
1517
1518    def _refine(
1519        self, segmentation: np.ndarray, context: dict, components: tuple, refinement_kwargs: dict,
1520        batch_size: int,
1521    ) -> np.ndarray:
1522        """Re-prompt the accepted instances with the requested refinement components."""
1523        with autocast(self._predictor.device):
1524            return self._reprompt_instances(
1525                segmentation, context, components, refinement_kwargs, batch_size,
1526            )
1527
1528    def _reprompt_instances(
1529        self, segmentation: np.ndarray, context: dict, components: tuple, refinement_kwargs: dict,
1530        batch_size: int,
1531    ) -> np.ndarray:
1532        """Predict one second-round mask per instance from the assembled prompts and repaint.
1533
1534        Every requested component contributes to one joint re-prompt per instance, evaluated in
1535        batches. The 'policy' decides what the second round is allowed to do: 'replace' repaints
1536        every instance from its new mask (the most confident painted last, so it wins contested
1537        pixels), 'keep-if-better' keeps the first-round mask unless the new one scores higher. The
1538        geometric gates then veto independently of either policy: a second-round mask that is
1539        inconsistent with the first round ('min_consistency') or grows into a neighbour
1540        ('max_foreign_overlap') is discarded, because the model's own score cannot arbitrate across
1541        prompt types. An instance whose re-prompt comes back empty keeps its first-round mask.
1542
1543        The instances are grouped by the region they are re-prompted in and every region is set up
1544        once, since a tiled generator pays for each switch. Within a region everything runs on its
1545        crop of the segmentation, which is the frame the predictor works in; only the repaint at
1546        the end is global, so the score order arbitrates across regions as well as within them.
1547        """
1548        shape = segmentation.shape
1549        instances = [
1550            (index + 1, bounding_box)
1551            for index, bounding_box in enumerate(find_objects(segmentation))
1552            if bounding_box is not None
1553        ]
1554
1555        point_prompts = None
1556        if "points" in components:
1557            all_points = np.array([record["point"] for record in context["proposals"]], dtype="float32")
1558            surviving_points = {
1559                instance_id: context["records"][record_index]["point"]
1560                for instance_id, record_index in context["matches"].items()
1561            }
1562            point_prompts = derive_refinement_prompts(
1563                segmentation, all_points, surviving_points,
1564                n_positives=refinement_kwargs["n_positives"], n_negatives=refinement_kwargs["n_negatives"],
1565                max_negative_distance=refinement_kwargs["max_negative_distance"],
1566                negative_source=refinement_kwargs["negative_source"],
1567                min_negative_distance=refinement_kwargs["min_negative_distance"],
1568            )
1569
1570        n_negatives_used = 0
1571        if point_prompts is not None:
1572            n_negatives_used = sum(
1573                int(np.count_nonzero(point_prompts[instance_id]["point_labels"] == 0)) for instance_id, _ in instances
1574            )
1575        self._last_generation_stats.update({
1576            "refinement_eligible_instances": len(instances),
1577            "refinement_negatives": n_negatives_used,
1578        })
1579        if not instances:
1580            self._last_generation_stats.update({
1581                "refined_instances": 0, "replaced_instances": 0, "dropped_negatives": 0,
1582                "gated_consistency": 0, "gated_foreign": 0,
1583            })
1584            return segmentation
1585
1586        # Every instance needs the record that made it, for its first-round score.
1587        groups = {}
1588        for instance_id, bounding_box in instances:
1589            if instance_id not in context["matches"]:
1590                raise RuntimeError(
1591                    f"Instance {instance_id} is in the segmentation but not in the merge context. The "
1592                    "refinement cannot score it against its first round."
1593                )
1594            key = self._region_of(context, context["matches"][instance_id])
1595            groups.setdefault(key, []).append((instance_id, bounding_box))
1596
1597        min_consistency = refinement_kwargs["min_consistency"]
1598        max_foreign_overlap = refinement_kwargs["max_foreign_overlap"]
1599        keep_if_better = refinement_kwargs["policy"] == "keep-if-better"
1600        chosen, replaced, dropped = [], 0, 0
1601        gated = {"gated_consistency": 0, "gated_foreign": 0}
1602        for key in sorted(groups):
1603            self._set_region(key)
1604            region_box = self._region_box(key)
1605            crop = segmentation[region_box]
1606            origin = tuple(box.start or 0 for box in region_box)
1607            members = groups[key]
1608
1609            region_prompts = point_prompts
1610            if point_prompts is not None and (any(origin) or crop.shape != shape):
1611                region_prompts = {}
1612                for instance_id, _ in members:
1613                    region_prompts[instance_id], region_dropped = _localize_prompts(
1614                        point_prompts[instance_id], origin, crop.shape
1615                    )
1616                    dropped += region_dropped
1617
1618            def accept(instance_id: int, bounding_box: tuple, mask: np.ndarray, score: float) -> None:
1619                """Decide between the second-round mask and the first round, and queue the repaint."""
1620                nonlocal replaced
1621                record = context["records"][context["matches"][instance_id]]
1622                first_round_score = record["predicted_iou"] * record["stability_score"]
1623                take_second = mask.any() and (not keep_if_better or score > first_round_score)
1624                if take_second and min_consistency is not None:
1625                    first_round_mask = crop == instance_id
1626                    union = int(np.count_nonzero(mask | first_round_mask))
1627                    iou = int(np.count_nonzero(mask & first_round_mask)) / union if union else 0.0
1628                    if iou < min_consistency:
1629                        take_second = False
1630                        gated["gated_consistency"] += 1
1631                if take_second and max_foreign_overlap is not None:
1632                    on_mask = crop[mask]
1633                    foreign = int(np.count_nonzero((on_mask != 0) & (on_mask != instance_id)))
1634                    if foreign / int(mask.sum()) > max_foreign_overlap:
1635                        take_second = False
1636                        gated["gated_foreign"] += 1
1637                if take_second:
1638                    replaced += 1
1639                    rows, columns = np.nonzero(mask)
1640                    box = (
1641                        slice(int(rows.min()), int(rows.max()) + 1), slice(int(columns.min()), int(columns.max()) + 1)
1642                    )
1643                    chosen.append((score, instance_id, _shift_box(box, origin), mask[box]))
1644                else:
1645                    chosen.append((
1646                        first_round_score, instance_id, _shift_box(bounding_box, origin),
1647                        crop[bounding_box] == instance_id,
1648                    ))
1649
1650            region_instances = [
1651                (instance_id, _shift_box(bounding_box, tuple(-shift for shift in origin)))
1652                for instance_id, bounding_box in members
1653            ]
1654            for start in range(0, len(region_instances), batch_size):
1655                batch = region_instances[start:start + batch_size]
1656                predictions = self._predict_refinement_batch(
1657                    crop, batch, components, region_prompts, refinement_kwargs,
1658                )
1659                for (instance_id, bounding_box), (mask, score) in zip(batch, predictions):
1660                    accept(instance_id, bounding_box, mask, score)
1661
1662        self._last_generation_stats.update({
1663            "refined_instances": len(instances), "replaced_instances": replaced, "dropped_negatives": dropped, **gated,
1664        })
1665        # Ascending score, so that the most confident instance is painted last and wins contested pixels.
1666        refined = np.zeros(shape, dtype="uint32")
1667        for score, instance_id, bounding_box, mask in sorted(chosen, key=lambda entry: (entry[0], entry[1])):
1668            refined[bounding_box][mask] = instance_id
1669        return refined
1670
1671    def _predict_refinement_batch(
1672        self, segmentation: np.ndarray, batch: list, components: tuple,
1673        point_prompts: Optional[dict], refinement_kwargs: dict,
1674    ) -> list:
1675        """Return one (mask, combined score) pair per instance in ``batch``."""
1676        shape = segmentation.shape
1677        box_extension = refinement_kwargs.get("box_extension", 0)
1678        points = labels = boxes = mask_logits = None
1679
1680        if "points" in components:
1681            per_instance = [point_prompts[instance_id] for instance_id, _ in batch]
1682            width = max(len(prompt["points"]) for prompt in per_instance)
1683            points = np.zeros((len(batch), width, 2), dtype="float32")
1684            labels = np.full((len(batch), width), -1, dtype="int32")
1685            for row, prompt in enumerate(per_instance):
1686                points[row, :len(prompt["points"])] = prompt["points"]
1687                labels[row, :len(prompt["points"])] = prompt["point_labels"]
1688        if "boxes" in components:
1689            boxes = np.array([
1690                _prompt_box(bounding_box, shape, box_extension) for _, bounding_box in batch
1691            ], dtype="float32")
1692        if "masks" in components:
1693            mask_logits = np.stack([mask_to_logits(segmentation == instance_id) for instance_id, _ in batch])
1694
1695        return self._predict_prompt_batch(
1696            points, labels, boxes, mask_logits, refinement_kwargs["multimasking"],
1697        )
1698
1699    def _predict_prompt_batch(
1700        self,
1701        points: Optional[np.ndarray],
1702        labels: Optional[np.ndarray],
1703        boxes: Optional[np.ndarray],
1704        mask_logits: Optional[np.ndarray],
1705        multimasking: bool,
1706    ) -> list:
1707        """One batched forward pass over assembled prompts, returning (mask, combined score) pairs.
1708
1709        The point counts may differ between the batch's prompts, so the coordinate arrays are padded
1710        to the longest with the label -1, which the SAM2 prompt encoder treats as 'not a point'.
1711        """
1712        n_prompts = len(points) if points is not None else len(boxes if boxes is not None else mask_logits)
1713        mask_input, coords, point_labels, box_input = self._predictor._prep_prompts(
1714            points, labels, boxes, mask_logits, True,
1715        )
1716        logits, scores, _ = self._predictor._predict(
1717            coords, point_labels, box_input, mask_input, multimasking, return_logits=True,
1718        )
1719        logits = logits.reshape(n_prompts, -1, *logits.shape[-2:])
1720        scores = scores.reshape(n_prompts, -1)
1721        index = torch.arange(n_prompts, device=scores.device)
1722        best = scores.argmax(dim=1)
1723        logits, scores = logits[index, best], scores[index, best]
1724
1725        mask_threshold = getattr(self._predictor, "mask_threshold", 0.0)
1726        stability = calculate_stability_score(logits, mask_threshold, STABILITY_SCORE_OFFSET)
1727        masks = (logits > mask_threshold).cpu().numpy()
1728        combined = (scores.float() * stability.float()).cpu().numpy()
1729        return [(mask, float(score)) for mask, score in zip(masks, combined)]
1730
1731    def _apply_prompts(
1732        self, predictor, prompts, multimasking: bool, batch_size: int, pbar_update=None,
1733    ) -> List[Dict[str, Any]]:
1734        """Prompt the interactive branch in batches, returning records for the merge.
1735
1736        Takes the predictor rather than reading `self._predictor`, so the volumetric scoring can hand
1737        every worker the replica on its own device.
1738        """
1739        points, point_labels = prompts["points"], prompts["point_labels"]
1740        mask_threshold = getattr(predictor, "mask_threshold", 0.0)
1741
1742        records = []
1743        for start in range(0, len(points), batch_size):
1744            stop = start + batch_size
1745            batch_points, batch_labels = points[start:stop], point_labels[start:stop]
1746            n_prompts = len(batch_points)
1747            # Reduced on the device, so only the kept mask is transferred rather than every proposal.
1748            mask_input, coords, labels, _ = predictor._prep_prompts(batch_points, batch_labels, None, None, True)
1749            with autocast(predictor.device):
1750                logits, scores, _ = predictor._predict(
1751                    coords, labels, None, mask_input, multimasking, return_logits=True,
1752                )
1753            logits = logits.reshape(n_prompts, -1, *logits.shape[-2:])
1754            scores = scores.reshape(n_prompts, -1)
1755            index = torch.arange(n_prompts, device=scores.device)
1756            best = scores.argmax(dim=1)
1757            logits, scores = logits[index, best], scores[index, best]
1758
1759            stability = calculate_stability_score(logits, mask_threshold, STABILITY_SCORE_OFFSET)
1760            binary = logits > mask_threshold
1761            # Two reductions on the device: an np.nonzero per mask costs more than the rest of the loop.
1762            rows_any = binary.any(dim=2).cpu().numpy()
1763            columns_any = binary.any(dim=1).cpu().numpy()
1764            masks = binary.cpu().numpy()
1765            scores = scores.float().cpu().numpy()
1766            stability = stability.float().cpu().numpy()
1767            for offset, (mask, row_any, column_any, score, stable) in enumerate(
1768                zip(masks, rows_any, columns_any, scores, stability)
1769            ):
1770                if not row_any.any():
1771                    continue
1772                y0, y1 = int(row_any.argmax()), len(row_any) - int(row_any[::-1].argmax())
1773                x0, x1 = int(column_any.argmax()), len(column_any) - int(column_any[::-1].argmax())
1774                records.append({
1775                    # The crop rather than the full mask: the merge is linear in the mask's size.
1776                    "segmentation": mask[y0:y1, x0:x1].copy(),
1777                    "bounding_box": (slice(y0, y1), slice(x0, x1)),
1778                    "predicted_iou": float(score),
1779                    "stability_score": float(stable),
1780                    # Empty masks are dropped, so the record order does not track the prompts.
1781                    "prompt_index": start + offset,
1782                    # The prompt as (x, y); the refinement groups the first round's prompts by it.
1783                    "point": (float(batch_points[offset, 0, 0]), float(batch_points[offset, 0, 1])),
1784                })
1785            if pbar_update is not None:
1786                pbar_update(1)
1787        return records
1788
1789    def _score_candidates(
1790        self, prompts: dict, multimasking: bool, batch_size: int, score_threshold: float,
1791        max_overlap: float, components: Optional[tuple] = None, refinement_kwargs: Optional[dict] = None,
1792        pbar_init=None, pbar_update=None,
1793    ) -> List[dict]:
1794        """Prompt every candidate in 2d on its anchor slice, and keep the strong, non-duplicate ones.
1795
1796        This runs before the propagation, which is where the cost is: a candidate the model scores
1797        poorly, or that a better-scoring one already covers on that slice, is never propagated. It
1798        also gives every surviving candidate the predicted IoU that orders the volumetric merge.
1799
1800        A refinement runs here too, slice by slice, while the predictor is still pointed at that
1801        slice: re-reading a slice's features costs more than the re-prompt itself does.
1802
1803        Args:
1804            prompts: The volumetric prompts, as `derive_volume_prompts` returns them.
1805            multimasking: Whether to predict several masks per point and keep the best scoring one.
1806            batch_size: Number of prompts per forward pass.
1807            score_threshold: Discard candidates whose predicted IoU is below this.
1808            max_overlap: Reject a candidate when more than this fraction of it is already claimed.
1809            components: The refinement components, or None to run no second round.
1810            refinement_kwargs: The resolved refinement keyword arguments.
1811
1812        Returns:
1813            The surviving candidates, each with the prompt it will be propagated with and its global
1814            'prompt_index' into the prompts.
1815        """
1816        points, point_labels, frames = prompts["points"], prompts["point_labels"], prompts["frames"]
1817        slice_shape = self._prediction[0].shape[-2:]
1818        min_size = default_prompt_generation(self._model_type, is_volume=False)["min_size"]
1819        # A refinement round re-prompts through 'self._predictor', so those slices keep to it and to
1820        # this process. Without one a slice is scored independently and the slices spread over the
1821        # devices, each worker prompting the replica on its own.
1822        refining = components is not None
1823        devices = [self._predictor.device] if refining else self._scoring_devices()
1824
1825        def score_frame(worker_id, frame):
1826            predictor = self._predictor if refining else self._scoring_predictors()[worker_id]
1827            indices = np.where(frames == frame)[0]
1828            # Reads the slice's features out of the volume's embeddings, so nothing is re-encoded.
1829            _set_image_predictor_from_3d_embeddings(predictor, self._image_embeddings, int(frame))
1830            frame_prompts = {"points": points[indices], "point_labels": point_labels[indices]}
1831            records = self._apply_prompts(
1832                predictor, frame_prompts, multimasking=multimasking, batch_size=batch_size,
1833            )
1834            records = [record for record in records if record["predicted_iou"] >= score_threshold]
1835            if not records:
1836                return []
1837
1838            def finish(candidate, record):
1839                candidate["prompt_index"] = int(indices[int(record["prompt_index"])])
1840                return candidate
1841
1842            if not refining:
1843                _, kept = merge_by_score(
1844                    records, _records_shape(records), max_overlap=max_overlap,
1845                    min_size=min_size, return_matches=True,
1846                )
1847                return [
1848                    finish(self._anchor_candidate(int(frame), records[record_index]), records[record_index])
1849                    for record_index in kept.values()
1850                ]
1851
1852            # On the slice's own canvas rather than the records' bounding one, because a refinement
1853            # looks instance ids up by position: for the foreign-overlap gate and for the negatives.
1854            segmentation, matches = merge_by_score(
1855                records, slice_shape, max_overlap=max_overlap,
1856                min_size=min_size,
1857                return_matches=True,
1858            )
1859            context = {
1860                "frame": int(frame), "segmentation": segmentation, "records": records,
1861                "matches": matches, "points": points[indices][:, 0, :],
1862            }
1863            with autocast(predictor.device):
1864                refined = self._refine_anchors(context, components, refinement_kwargs, batch_size)
1865            return [
1866                finish(candidate, records[record_index])
1867                for candidate, record_index in zip(refined, matches.values())
1868            ]
1869
1870        anchor_frames = np.unique(frames)
1871        if pbar_init is not None:
1872            pbar_init(len(anchor_frames), "APG: scoring anchor slices")
1873        per_frame = _run_with_progress(
1874            lambda update: map_jobs_over_devices(devices, anchor_frames, score_frame, update_progress=update),
1875            pbar_update,
1876        )
1877        return [candidate for frame_candidates in per_frame for candidate in frame_candidates]
1878
1879    def _scoring_predictors(self) -> list:
1880        """One image predictor per inference device, built on the video predictor's own replicas.
1881
1882        The volumetric scoring reads one slice's features per job and prompts the interactive branch
1883        with them, which is independent per job, so the jobs spread over the devices exactly like the
1884        propagation. Built lazily and only once, because a replica is a full model.
1885        """
1886        if self._propagator is None:
1887            return [self._predictor]
1888        if self._scoring_predictor_pool is None:
1889            self._scoring_predictor_pool = [
1890                get_sam2_image_predictor(predictor) for predictor, _ in self._propagator.predictor_devices
1891            ]
1892        return self._scoring_predictor_pool
1893
1894    def _scoring_devices(self) -> list:
1895        """The devices the volumetric scoring spreads its jobs over, or the one it has."""
1896        if self._propagator is None:
1897            return [self._predictor.device]
1898        return [device for _, device in self._propagator.predictor_devices]
1899
1900    def _anchor_candidate(self, frame: int, record: dict) -> dict:
1901        """One propagation candidate: the prompt that made the anchor mask, and the merge's score."""
1902        return {
1903            "frame": int(frame),
1904            "point": record["point"],
1905            "score": record["predicted_iou"],
1906            "stability": record["stability_score"],
1907            # The mask on the anchor slice, which the pruning between propagation rounds measures
1908            # the claimed overlap of.
1909            "mask": record["segmentation"],
1910            "mask_box": record["bounding_box"],
1911        }
1912
1913    def _refine_anchors(
1914        self, context: dict, components: tuple, refinement_kwargs: dict, batch_size: int,
1915    ) -> List[dict]:
1916        """Re-prompt every scored candidate of one anchor slice, and return what to propagate.
1917
1918        The volumetric counterpart of `_reprompt_instances`, and the only place a volume can refine
1919        at all: a prompt on an already propagated slice would turn it into a conditioning frame and
1920        replace the mask there with a single-point one. So the second round runs on the anchor slice,
1921        before the propagation, and what it produces is not a mask - the propagation still makes that
1922        - but the conditioning the propagation starts from and the score that orders the 3d merge.
1923
1924        The prompts, the batched forward and both gates are the 2d ones, applied in-plane on the
1925        anchor slice: `derive_refinement_prompts` groups that slice's suppressed prompts onto their
1926        candidate and takes the neighbouring ones as negatives, 'min_consistency' keeps a re-prompt
1927        from reshaping the anchor rather than polishing it, and 'max_foreign_overlap' keeps it out of
1928        a neighbour. A candidate whose re-prompt comes back empty or gated keeps its first round.
1929
1930        Returns:
1931            The slice's candidates in first-round score order. An accepted re-prompt carries its
1932            conditioning under 'conditioning'; a rejected one has no such key and is propagated from
1933            its first-round point, exactly as without a refinement.
1934        """
1935        segmentation, records = context["segmentation"], context["records"]
1936        frame, frame_points = context["frame"], context["points"]
1937        candidates = {
1938            instance_id: self._anchor_candidate(frame, records[record_index])
1939            for instance_id, record_index in context["matches"].items()
1940        }
1941
1942        point_prompts = None
1943        if "points" in components:
1944            point_prompts = derive_refinement_prompts(
1945                segmentation, frame_points,
1946                {instance_id: candidate["point"] for instance_id, candidate in candidates.items()},
1947                n_positives=refinement_kwargs["n_positives"],
1948                n_negatives=refinement_kwargs["n_negatives"],
1949                max_negative_distance=refinement_kwargs["max_negative_distance"],
1950                negative_source=refinement_kwargs["negative_source"],
1951                min_negative_distance=refinement_kwargs["min_negative_distance"],
1952            )
1953
1954        boxes = {
1955            index + 1: bounding_box
1956            for index, bounding_box in enumerate(find_objects(segmentation))
1957            if bounding_box is not None
1958        }
1959        instances = [(instance_id, boxes[instance_id]) for instance_id in candidates]
1960        min_consistency = refinement_kwargs["min_consistency"]
1961        max_foreign_overlap = refinement_kwargs["max_foreign_overlap"]
1962        keep_if_better = refinement_kwargs["policy"] == "keep-if-better"
1963        stats = self._last_generation_stats
1964        stats["refined_candidates"] += len(instances)
1965        if point_prompts is not None:
1966            # A volume takes negatives only from the candidates on the same slice, so it reports how many it got.
1967            stats["refinement_negatives"] += sum(
1968                int(np.count_nonzero(point_prompts[instance_id]["point_labels"] == 0))
1969                for instance_id, _ in instances
1970            )
1971
1972        for start in range(0, len(instances), batch_size):
1973            batch = instances[start:start + batch_size]
1974            predictions = self._predict_refinement_batch(
1975                segmentation, batch, components, point_prompts, refinement_kwargs,
1976            )
1977            for (instance_id, bounding_box), (mask, score) in zip(batch, predictions):
1978                candidate = candidates[instance_id]
1979                first_round_score = candidate["score"] * candidate["stability"]
1980                take_second = mask.any() and (not keep_if_better or score > first_round_score)
1981                if take_second and min_consistency is not None:
1982                    first_round_mask = segmentation == instance_id
1983                    union = int(np.count_nonzero(mask | first_round_mask))
1984                    iou = int(np.count_nonzero(mask & first_round_mask)) / union if union else 0.0
1985                    if iou < min_consistency:
1986                        take_second = False
1987                        stats["gated_consistency"] += 1
1988                if take_second and max_foreign_overlap is not None:
1989                    on_mask = segmentation[mask]
1990                    foreign = int(np.count_nonzero((on_mask != 0) & (on_mask != instance_id)))
1991                    if foreign / int(mask.sum()) > max_foreign_overlap:
1992                        take_second = False
1993                        stats["gated_foreign"] += 1
1994                if not take_second:
1995                    continue
1996                stats["replaced_candidates"] += 1
1997                # The merge only reads the product of the two, and the second round reports it as one
1998                # combined score, so it goes in whole rather than being split back up arbitrarily.
1999                candidate["score"], candidate["stability"] = float(score), 1.0
2000                candidate["conditioning"] = self._anchor_conditioning(
2001                    mask, bounding_box, segmentation.shape, components,
2002                    point_prompts, instance_id, refinement_kwargs,
2003                )
2004        return list(candidates.values())
2005
2006    def _anchor_conditioning(
2007        self, mask: np.ndarray, bounding_box: tuple, shape: tuple, components: tuple,
2008        point_prompts: Optional[dict], instance_id: int, refinement_kwargs: dict,
2009    ) -> dict:
2010        """What the propagation conditions the anchor frame on, once a second round is accepted.
2011
2012        'conditioning="mask"' hands the video predictor the refined mask, so the anchor frame is
2013        exactly the mask the gates accepted, but its decoder never sees the prompt that produced it.
2014        'prompts' pushes that prompt instead - the same box and points the second round used - and
2015        lets the decoder rebuild the mask, which is what the interactive branch does everywhere else.
2016        """
2017        if refinement_kwargs["conditioning"] == "mask":
2018            return {"mask": mask}
2019        conditioning = {"mode": refinement_kwargs["conditioning"]}
2020        if "boxes" in components:
2021            conditioning["box"] = _prompt_box(bounding_box, shape, refinement_kwargs["box_extension"])
2022        if "points" in components:
2023            conditioning["points"] = point_prompts[instance_id]["points"]
2024            conditioning["point_labels"] = point_prompts[instance_id]["point_labels"]
2025        return conditioning
2026
2027    def _propagate_candidates(
2028        self, candidates: List[dict], n_objects_per_pass: int, early_stop_patience: Optional[int],
2029        verbose: bool, max_overlap: float, propagation_waves: int = 1,
2030        pbar_init=None, pbar_update=None,
2031    ) -> List[Dict[str, Any]]:
2032        """Turn every candidate into a volumetric mask by propagating its prompts through the volume.
2033
2034        Every object of a pass is anchored on the same slice, because the video predictor propagates
2035        them together from the earliest slice any of them is conditioned on: an object anchored later
2036        than that would be tracked before it is conditioned, and never propagated backwards at all.
2037        """
2038        def run_pass(propagator, batch):
2039            # Only the objects: re-reading the volume's features each pass costs more than the propagation.
2040            propagator.reset_tracking()
2041            for object_id, candidate in enumerate(batch, start=1):
2042                self._condition_pass(candidate, object_id, propagator)
2043            video_segments = propagator.propagate_prompts(early_stop_patience=early_stop_patience)
2044            return _volume_records(video_segments, batch, self._volume.shape[:3]), len(video_segments)
2045
2046        claims: Dict[Any, np.ndarray] = {}
2047        records, anchors = [], set()
2048        n_passes = propagated_frame_steps = n_propagated = 0
2049        waves = self._candidate_waves(candidates, propagation_waves)
2050        for wave_index, wave in enumerate(waves):
2051            wave = [candidate for candidate in wave if not self._is_claimed(claims, candidate, max_overlap)]
2052            n_propagated += len(wave)
2053            by_anchor: Dict[int, List[dict]] = {}
2054            for candidate in wave:
2055                by_anchor.setdefault(candidate["frame"], []).append(candidate)
2056            passes = [
2057                group[start:start + n_objects_per_pass]
2058                for _, group in sorted(by_anchor.items())
2059                for start in range(0, len(group), n_objects_per_pass)
2060            ]
2061            if not passes:
2062                continue
2063            anchors.update(by_anchor)
2064            n_passes += len(passes)
2065
2066            # The passes share nothing but the volume, so each goes to whichever device is free.
2067            if pbar_init is not None:
2068                pbar_init(len(passes), f"APG: propagation passes (wave {wave_index + 1}/{len(waves)})")
2069            with tqdm(total=len(passes), desc="Propagate prompts", disable=not verbose) as progress:
2070                if pbar_update is None:
2071                    per_pass = self._propagator.map_passes(passes, run_pass, update_progress=progress.update)
2072                else:
2073                    per_pass = _run_with_progress(
2074                        lambda update: self._propagator.map_passes(passes, run_pass, update_progress=update),
2075                        pbar_update,
2076                    )
2077
2078            for pass_records, steps in per_pass:
2079                records.extend(pass_records)
2080                propagated_frame_steps += steps
2081                if wave_index + 1 < len(waves):
2082                    self._claim_records(claims, None, pass_records)
2083
2084        possible_frame_steps = n_passes * int(self._volume.shape[0])
2085        self._last_generation_stats.update({
2086            "unique_anchor_slices": len(anchors),
2087            "propagation_passes": n_passes,
2088            "propagated_candidates": n_propagated,
2089            "pruned_candidates": len(candidates) - n_propagated,
2090            "propagated_frame_steps": propagated_frame_steps,
2091            "early_stopped_frame_steps": possible_frame_steps - propagated_frame_steps,
2092        })
2093        self._propagator.reset_predictor()
2094        return records
2095
2096    def _claim_key(self, candidate: dict):
2097        """The region a candidate's masks are expressed in. An untiled volume is a single region."""
2098        return None
2099
2100    def _claim_shape(self, key) -> tuple:
2101        """The shape of that region's claim volume, which the record bounding boxes index into."""
2102        return tuple(int(side) for side in self._volume.shape[:3])
2103
2104    def _candidate_waves(self, candidates: List[dict], propagation_waves: int) -> List[List[dict]]:
2105        """The candidates in descending merge score, cut into the rounds they are propagated in.
2106
2107        Descending, because that is the order the merge resolves them in: an instance a later
2108        candidate would duplicate has already been propagated by the time that candidate is reached.
2109        """
2110        if not candidates:
2111            return []
2112        if propagation_waves <= 1:
2113            return [list(candidates)]
2114        order = sorted(candidates, key=lambda candidate: -(candidate["score"] * candidate["stability"]))
2115        size = -(-len(order) // propagation_waves)
2116        return [order[start:start + size] for start in range(0, len(order), size)]
2117
2118    def _region_claim(self, claims: Dict[Any, np.ndarray], key) -> np.ndarray:
2119        """The voxels of one region that an already-propagated instance covers, made on first use."""
2120        if key not in claims:
2121            claims[key] = np.zeros(self._claim_shape(key), dtype=bool)
2122        return claims[key]
2123
2124    def _claim_records(self, claims: Dict[Any, np.ndarray], key, records: List[dict]) -> None:
2125        """Record the voxels a round's masks cover, in the frame the records are expressed in."""
2126        if not records:
2127            return
2128        claim = self._region_claim(claims, key)
2129        for record in records:
2130            claim[record["bounding_box"]] |= record["segmentation"]
2131
2132    def _is_claimed(self, claims: Dict[Any, np.ndarray], candidate: dict, max_overlap: float) -> bool:
2133        """Whether earlier rounds already claim enough of this candidate to make it a duplicate.
2134
2135        The merge rejects a candidate when a better-scoring mask claims more than 'max_overlap' of
2136        it. This applies that same rule to the candidate's anchor-slice mask rather than to the
2137        volumetric mask it has not been propagated into yet, so it predicts the rejection instead of
2138        being it. Testing the anchor point instead measures less and prunes less: 597 candidates
2139        against 1222 on one gonuclear crop, for the same score.
2140
2141        Where instances tile space rather than sit apart in background this misfires, because an
2142        abutting neighbour then claims a real share of the candidate. Measured on cremi it costs
2143        0.03 CREMI score, which is why the default is one round, see 'propagation_waves'.
2144        """
2145        if self._is_protected_from_pruning(candidate):
2146            return False
2147        claim = claims.get(self._claim_key(candidate))
2148        if claim is None:
2149            return False
2150        mask = candidate["mask"]
2151        area = int(mask.sum())
2152        if area == 0:
2153            return False
2154        claimed = np.logical_and(claim[(candidate["frame"],) + tuple(candidate["mask_box"])], mask).sum()
2155        return bool(claimed > max_overlap * area)
2156
2157    def _is_protected_from_pruning(self, candidate: dict) -> bool:
2158        """Whether a candidate's anchor frame or mask reaches into the halo margin, if one is set.
2159
2160        '_pruning_protected_margin' is None outside 'TiledAutomaticPromptGenerator', so this is
2161        always False there and pruning behaves exactly as it did before this option existed. A tile
2162        or block sets it to its own halo before propagating: a candidate this close to the block's
2163        outer edge is exactly the kind of prediction the halo-overlap multicut compares against the
2164        neighbouring tile/block, so dropping it as a within-tile duplicate could discard the one
2165        candidate that seam needed, even though it looked safe to prune from this tile alone.
2166        """
2167        margin = getattr(self, "_pruning_protected_margin", None)
2168        if margin is None:
2169            return False
2170        z_margin, y_margin, x_margin = margin
2171        frame = candidate["frame"]
2172        y_box, x_box = candidate["mask_box"]
2173        depth, height, width = self._volume.shape[:3]
2174        return (
2175            frame < z_margin or frame >= depth - z_margin
2176            or y_box.start < y_margin or y_box.stop > height - y_margin
2177            or x_box.start < x_margin or x_box.stop > width - x_margin
2178        )
2179
2180    def _condition_pass(self, candidate: dict, object_id: int, propagator) -> None:
2181        """Push one candidate's conditioning onto the propagator, as the object with this id.
2182
2183        Without a refinement a candidate is conditioned on the single point the decoder proposed it
2184        at. A refined one carries either the mask its second round produced, which conditions the
2185        anchor frame directly, or that round's box and points - in as many pushes as its
2186        'conditioning' asks for, because a push is a decoder step on the anchor frame rather than
2187        bookkeeping, and more of them refine the anchor further. See `DEFAULT_REFINEMENT_3D`.
2188        """
2189        frame = candidate["frame"]
2190        conditioning = candidate.get("conditioning")
2191        if conditioning is None:
2192            x, y = candidate["point"]
2193            propagator.add_point_prompts(
2194                frame_ids=frame,
2195                points=np.array([[y, x]], dtype="float32"),  # The propagator takes YX.
2196                point_labels=np.array([1], dtype="int32"),
2197                object_id=object_id,
2198            )
2199            return
2200
2201        mask = conditioning.get("mask")
2202        if mask is not None:
2203            # Already refined against this slice, so the propagator must not refine it a second time.
2204            propagator.add_mask_prompts(
2205                frame_ids=frame, masks=[mask], object_id=object_id, refine=False,
2206            )
2207            return
2208
2209        # Every producer of a conditioning dict sets this; a missing one is a bug in the producer,
2210        # so it raises rather than silently picking a strategy.
2211        mode = conditioning["mode"]
2212        box = conditioning.get("box")
2213        points = conditioning.get("points")
2214        # The propagator takes YX for both.
2215        points_yx = None if points is None else np.asarray(points, dtype="float32")[:, ::-1]
2216        labels = conditioning.get("point_labels")
2217        box_yx = None if box is None else np.array([box[1], box[0], box[3], box[2]], dtype="float32")
2218
2219        if mode == "prompts-joint":
2220            propagator.add_prompt_set(
2221                frame_id=frame, points=points_yx, point_labels=labels, box=box_yx,
2222                object_id=object_id,
2223            )
2224            return
2225
2226        # A box has to come first, and it clears whatever the object carried on the frame.
2227        if box_yx is not None:
2228            propagator.add_box_prompts(
2229                frame_ids=frame, boxes=[box_yx], object_id=object_id,
2230            )
2231        if points_yx is None or not len(points_yx):
2232            return
2233        if mode == "prompts-grouped":
2234            propagator.add_prompt_set(
2235                frame_id=frame, points=points_yx, point_labels=labels, object_id=object_id,
2236                # Appends to the box rather than replacing it.
2237                clear_old_points=box_yx is None,
2238            )
2239            return
2240        propagator.add_point_prompts(
2241            frame_ids=frame, points=points_yx,
2242            point_labels=np.asarray(labels, dtype="int32"), object_id=object_id,
2243        )
2244
2245
2246def _check_tiled_embeddings(image_embeddings: dict, shape: tuple, tile_shape: tuple, halo: tuple, i) -> None:
2247    """Check that the blocks can read their embeddings from the precomputed tiled embeddings.
2248
2249    The blocks and the embedding tiles use the same blocking. Thus a block covers the in-plane crop
2250    of one embedding tile only if the embeddings have the same in-plane tiling and the same input.
2251
2252    Args:
2253        image_embeddings: The precomputed tiled embeddings (see `precompute_image_embeddings`).
2254        shape: The spatial shape of the input, (y, x) or (z, y, x).
2255        tile_shape: The block shape of the tiled generator, matching `shape`'s axes.
2256        halo: The block halo of the tiled generator, matching `shape`'s axes.
2257        i: The index of the slice the input is in the embedded volume, or None.
2258
2259    Raises:
2260        ValueError: If the embeddings do not match the input or its tiling.
2261    """
2262    features = image_embeddings["features"]
2263    if image_embeddings.get("input_size") is not None or "tile_shape" not in features.attrs:
2264        raise ValueError("Tiled prompt generation can only reuse tiled embeddings.")
2265
2266    in_plane_tiling = (tuple(tile_shape[-2:]), tuple(halo[-2:]))
2267    embedding_tiling = (
2268        tuple(int(t) for t in features.attrs["tile_shape"]), tuple(int(h) for h in features.attrs["halo"]),
2269    )
2270    if in_plane_tiling != embedding_tiling:
2271        raise ValueError(
2272            f"The in-plane tiling {in_plane_tiling} (tile shape, halo) is not the tiling {embedding_tiling} of "
2273            "the embeddings. Compute the embeddings with the same tiling."
2274        )
2275
2276    embedded_shape = tuple(int(s) for s in features.attrs["shape"])
2277    is_video = "fpn" in image_embeddings
2278    if len(shape) == 3 or i is not None:
2279        expected_shape = tuple(shape) if len(shape) == 3 else (embedded_shape[0], *shape)
2280        valid = is_video and embedded_shape == expected_shape and (i is None or 0 <= i < embedded_shape[0])
2281    else:
2282        valid = not is_video and embedded_shape == tuple(shape)
2283    if not valid:
2284        slice_info = "" if i is None else f" (slice {i})"
2285        raise ValueError(
2286            f"The embeddings of shape {embedded_shape} are not for the input of shape {tuple(shape)}"
2287            f"{slice_info}. Compute the embeddings for this input."
2288        )
2289
2290
2291def _block_embeddings(image_embeddings: dict, shape: tuple, tile_shape: tuple, halo: tuple, block_id: int, i):
2292    """Read the precomputed embeddings of one block from the embedding tile that contains it.
2293
2294    The in-plane crop of a block is one embedding tile with its halo, see `_check_tiled_embeddings`.
2295    A volume block selects the slices of the block from that tile. This function reads the slices
2296    into memory, so that a worker process can receive them.
2297
2298    Args:
2299        image_embeddings: The precomputed tiled embeddings, checked by `_check_tiled_embeddings`.
2300        shape: The spatial shape of the input, (y, x) or (z, y, x).
2301        tile_shape: The block shape of the tiled generator, matching `shape`'s axes.
2302        halo: The block halo of the tiled generator, matching `shape`'s axes.
2303        block_id: The id of the block, as `bioimage_py.segmentation.stitch_segmentation` passes it.
2304        i: The index of the slice the input is in the embedded volume, or None.
2305
2306    Returns:
2307        The block's embeddings, and the slice index to initialize its generator with.
2308    """
2309    blocking = Blocking([0] * len(shape), list(shape), list(tile_shape))
2310    block = blocking.get_block_with_halo(block_id, list(halo))
2311    tiling = Blocking([0, 0], list(shape[-2:]), list(tile_shape[-2:]))
2312    tile_id = tiling.coordinates_to_block_id(list(block.inner_block.begin)[-2:])
2313    tile = tiling.get_block_with_halo(tile_id, list(halo[-2:])).outer_block
2314    if (list(tile.begin), list(tile.end)) != (list(block.outer_block.begin)[-2:], list(block.outer_block.end)[-2:]):
2315        raise RuntimeError(f"Block {block_id} does not cover the same in-plane crop as the embedding tile {tile_id}.")
2316
2317    name = str(tile_id)
2318    features = image_embeddings["features"][name]
2319    sizes = {"input_size": features.attrs["input_size"], "original_size": features.attrs["original_size"]}
2320    if "fpn" not in image_embeddings:  # A 2d image.
2321        high_res_feats = _load_list_datasets(image_embeddings["high_res_feats"], name, lazy_loading=False)
2322        return {"features": features[:], "high_res_feats": high_res_feats, **sizes}, None
2323
2324    # A volume block reads its slices, a slice of a volume only that one.
2325    z = slice(block.outer_block.begin[0], block.outer_block.end[0]) if len(shape) == 3 else slice(i, i + 1)
2326    fpn = _load_list_datasets(image_embeddings["fpn"], name, lazy_loading=True)
2327    embeddings = {
2328        "features": features[z],
2329        "fpn": [level[z] for level in fpn],
2330        "pos_enc": _load_list_datasets(image_embeddings["pos_enc"], name, lazy_loading=False),
2331        **sizes,
2332    }
2333    return embeddings, (None if len(shape) == 3 else 0)
2334
2335
2336def _process_worker(model_builder: Callable[[str], tuple], device: str, task_queue) -> None:
2337    """One persistent OS process per device for `TiledAutomaticPromptGenerator(execution='process')`.
2338
2339    A live CUDA model cannot cross a process boundary safely (its tensors are tied to the parent's
2340    CUDA context), so the worker builds its own copy with `model_builder` instead of receiving one
2341    from the parent - the same reason `_build_pool` deep-copies a model per device rather than
2342    sharing one, just paid once per process instead of once per thread. Every block after that stays
2343    entirely inside this process: no shared Python interpreter, so no GIL contention with the other
2344    devices' workers. See finetuning/v2/evaluation for the measurements this is based on.
2345    """
2346    model, predictor = model_builder(device)
2347    generator = AutomaticPromptGenerator(model, predictor, device=device, inference_device=device)
2348    while True:
2349        task = task_queue.get()
2350        if task is None:
2351            return
2352        result_queue = task["result_queue"]
2353        try:
2354            generator.clear_state()
2355            generator.initialize(
2356                task["block"], ndim=task["ndim"], normalization_bounds=task["normalization_bounds"],
2357                offload_to_cpu=task["offload_to_cpu"], cache_all_slices=task["cache_all_slices"],
2358                **task["embedding_kwargs"],
2359            )
2360            generator._pruning_protected_margin = task["protected_margin"]
2361            result_queue.put(("ok", generator.generate(**task["params"])))
2362        except Exception as exc:  # surfaced in the parent instead of hanging it on an empty queue
2363            result_queue.put(("err", repr(exc)))
2364        finally:
2365            generator.clear_state()
2366
2367
2368class TiledAutomaticPromptGenerator:
2369    """Generates an instance segmentation with automatically generated prompts, tile or block by tile.
2370
2371    Like `AutomaticPromptGenerator`, but every tile (an image) or XYZ block (a volume) is segmented
2372    independently at native resolution, with a halo, and the results are stitched by
2373    `bioimage_py.segmentation.stitch_segmentation`'s multicut over the halo overlap rather than by
2374    giving each candidate to exactly one tile. A volume is blocked in Z too, so an object crossing a
2375    Z seam is reconciled the same way one crossing a Y or X seam is: independently predicted in both
2376    neighbouring blocks and merged by how well their halo predictions agree, instead of being routed
2377    to a single owning tile - which a full-depth tile column cannot do for a Z seam at all. This
2378    trades some redundant halo computation (every tile/block re-encodes and re-propagates its own
2379    halo) for correctness at every seam, including ones the previous tile-column design could not
2380    represent. See finetuning/v2/evaluation/apg_3d_blockwise_ab.py for the measurements.
2381
2382    Every resolved device gets its own persistent (decoder, model) copy, built once and reused
2383    across every tile/block for the life of the generator, so `generate` keeps every device busy on
2384    a different tile/block concurrently rather than rebuilding the model per tile.
2385
2386    Args:
2387        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
2388        predictor: The SAM2 image predictor for the interactive branch of the same model, or its
2389            video predictor for a volume.
2390        device: The device the model lives on, used to resolve `inference_device=None`.
2391        inference_device: The device(s) to run tiles/blocks on concurrently, resolved the same way
2392            as `UniSAM2InstanceSegmentation`'s: None fans out over every visible GPU when the model
2393            is on CUDA, a single device stays on it, a sequence pins one pool member per device.
2394        beta: The multicut boundary bias passed to `stitch_segmentation`; > 0.5 biases towards
2395            over-segmentation (cutting), < 0.5 towards under-segmentation (merging).
2396        workers_per_device: How many independent (decoder, model) copies to build per resolved
2397            device. `generate` still gives each worker one tile/block at a time, so this only helps
2398            when a single worker leaves a device's compute or memory underused, e.g. a small model
2399            on a large GPU. Not supported together with `execution='process'`.
2400        execution: How a tile/block's own segmentation runs. `'thread'` (the default) runs every
2401            worker in this process on a `concurrent.futures.ThreadPoolExecutor`, sharing one Python
2402            interpreter. `'process'` instead gives every device its own persistent OS process, with
2403            its own interpreter and CUDA context, so one device's per-frame propagation bookkeeping
2404            never blocks another's behind the GIL - measured at 1.5-4x faster than `'thread'` once
2405            the pool is warm (bigger blocks and more of them widen the gap), with no quality change
2406            (see finetuning/v2/evaluation). The first `generate` call after building the generator
2407            pays extra for it, though: every worker process loads its own model from disk instead of
2408            reusing an in-memory copy the way `'thread'`'s pool does, which cost ~10-15s total across
2409            4 workers in that same measurement. Worth it for a generator that runs many volumes, not
2410            necessarily for a single one-off call. Requires `model_builder`.
2411        model_builder: Required for `execution='process'`. A callable `(device) -> (model,
2412            predictor)` that builds a fresh model and predictor pair on a device string - every
2413            worker process calls this itself rather than receiving `model`/`predictor` from the
2414            parent, because a live CUDA model cannot cross a process boundary safely.
2415        process_timeout: `execution='process'` only. Seconds a block waits for its worker before
2416            raising, rather than hanging forever if a worker process has died or wedged.
2417    """
2418
2419    # Read by `automatic_instance_segmentation` to decide whether to pass the AIS 'mode' argument.
2420    _has_postprocessing_mode = False
2421    _is_decoder_based = True
2422    # The front end computes the embeddings only when it caches them.
2423    _precompute_embeddings_in_frontend = False
2424
2425    def __init__(
2426        self,
2427        model: torch.nn.Module,
2428        predictor,
2429        device: Optional[Union[str, torch.device]] = None,
2430        inference_device: Devices = USE_MODEL_DEVICE,
2431        beta: float = DEFAULT_STITCHING_BETA,
2432        workers_per_device: int = 1,
2433        execution: str = "thread",
2434        model_builder: Optional[Callable[[str], tuple]] = None,
2435        process_timeout: float = 600.0,
2436    ) -> None:
2437        self._model = model
2438        self._predictor = predictor
2439        self._device = device
2440        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
2441        self._beta = beta
2442        if workers_per_device < 1:
2443            raise ValueError(f"'workers_per_device' must be >= 1, got {workers_per_device}.")
2444        self._workers_per_device = int(workers_per_device)
2445        if execution not in ("thread", "process"):
2446            raise ValueError(f"'execution' must be 'thread' or 'process', got {execution!r}.")
2447        if execution == "process":
2448            if workers_per_device != 1:
2449                raise ValueError("'workers_per_device' > 1 is not supported with execution='process'.")
2450            if model_builder is None:
2451                raise ValueError(
2452                    "execution='process' needs 'model_builder', a callable (device) -> (model, "
2453                    "predictor) every worker process calls to build its own model copy - a live CUDA "
2454                    "model cannot cross a process boundary safely."
2455                )
2456        self._execution = execution
2457        self._model_builder = model_builder
2458        self._process_timeout = float(process_timeout)
2459        self._pool: Optional[List[AutomaticPromptGenerator]] = None
2460        self._process_devices: Optional[List[str]] = None
2461        self._task_queues: Optional[list] = None
2462        self._processes: Optional[list] = None
2463        self._manager = None
2464        self._image = None
2465        self._ndim = None
2466        self._tile_shape = None
2467        self._halo = None
2468        self._verbose = False
2469        self._offload_to_cpu = None
2470        self._cache_all_slices = False
2471        self._image_embeddings = None
2472        self._i = None
2473
2474    def _inference_devices(self, devices: Devices) -> Devices:
2475        """Resolve the inference devices and discard a pool that uses different devices."""
2476        inference_devices = self._inference_device if devices is None else devices
2477        if inference_devices != self._inference_device:
2478            self.close()
2479            if self._pool is not None:
2480                for generator in self._pool:
2481                    generator.clear_state()
2482                self._pool = None
2483            self._inference_device = inference_devices
2484        return inference_devices
2485
2486    def _build_pool(self) -> List[AutomaticPromptGenerator]:
2487        """'workers_per_device' independent (decoder, model) copies per resolved device.
2488
2489        Every worker is pinned entirely to its own device, and only one tile/block ever owns a
2490        worker at a time (see `generate`'s queue), so multiple workers sharing a device compete for
2491        its compute rather than racing on shared state. This is worth it only because a single
2492        worker's block leaves a large GPU's memory and, more importantly, its compute scheduling far
2493        from saturated (a `hvit_t` block is a few GB on an 80+ GB H100): plain Python threads sharing
2494        a device all submit to its one default CUDA stream, which runs their kernels in submission
2495        order and gives no real concurrency, so every worker beyond the first on a device gets its
2496        own `torch.cuda.Stream` (`generate` runs it under that stream) to let the driver actually
2497        interleave independent tiles' kernels on the same device.
2498        """
2499        devices = _resolve_devices(self._model, self._inference_device)
2500        worker_devices = [device for device in devices for _ in range(self._workers_per_device)]
2501
2502        def move_pair(model, predictor, device):
2503            model.to(device)
2504            getattr(predictor, "model", predictor).to(device)
2505
2506        worker_pairs = [None] * len(worker_devices)
2507        if len(worker_devices) > 1:
2508            move_pair(self._model, self._predictor, "cpu")
2509            for worker_id in range(1, len(worker_devices)):
2510                pair = copy.deepcopy((self._model, self._predictor))
2511                move_pair(*pair, worker_devices[worker_id])
2512                worker_pairs[worker_id] = pair
2513        move_pair(self._model, self._predictor, worker_devices[0])
2514        worker_pairs[0] = self._model, self._predictor
2515
2516        pool = []
2517        for (model, predictor), device in zip(worker_pairs, worker_devices):
2518            device_obj = torch.device(device)
2519            generator = AutomaticPromptGenerator(model, predictor, device=device, inference_device=device)
2520            if self._workers_per_device > 1 and device_obj.type == "cuda":
2521                generator._tile_stream = torch.cuda.Stream(device=device_obj)
2522            pool.append(generator)
2523        return pool
2524
2525    def _build_process_pool(self) -> None:
2526        """Start one persistent worker OS process per resolved device, each with its own model copy.
2527
2528        Sidesteps the thread pool's GIL contention rather than working around it: every worker has
2529        its own Python interpreter, so the per-frame propagation bookkeeping of one device's block
2530        never blocks another device's. `_manager` backs the per-block reply queues - a `Queue`
2531        created after these processes already exist cannot be pickled to a `spawn`-context child,
2532        only a manager-proxied one can.
2533        """
2534        devices = _resolve_devices(self._model, self._inference_device)
2535        ctx = mp.get_context("spawn")
2536        self._manager = ctx.Manager()
2537        self._process_devices = devices
2538        self._task_queues = [ctx.Queue() for _ in devices]
2539        self._processes = [
2540            ctx.Process(target=_process_worker, args=(self._model_builder, device, task_queue), daemon=True)
2541            for device, task_queue in zip(devices, self._task_queues)
2542        ]
2543        for process in self._processes:
2544            process.start()
2545
2546    def close(self) -> None:
2547        """Stop the process pool, if `execution='process'` built one. A no-op otherwise.
2548
2549        Not required for correctness - every worker process is a daemon, so it exits with the main
2550        process - but lets a caller reclaim the devices deterministically before that.
2551        """
2552        if self._processes is None:
2553            return
2554        for task_queue in self._task_queues:
2555            task_queue.put(None)
2556        for process in self._processes:
2557            process.join(timeout=10)
2558            if process.is_alive():
2559                process.terminate()
2560        self._manager.shutdown()
2561        self._processes = None
2562        self._task_queues = None
2563        self._process_devices = None
2564        self._manager = None
2565
2566    def initialize(
2567        self,
2568        image: np.ndarray,
2569        ndim: int = 2,
2570        tile_shape: Optional[tuple] = None,
2571        halo: Optional[tuple] = None,
2572        verbose: bool = False,
2573        offload_to_cpu: Optional[bool] = None,
2574        cache_all_slices: bool = False,
2575        image_embeddings: Optional[dict] = None,
2576        i: Optional[int] = None,
2577    ) -> None:
2578        """Store the input and the tile/block geometry; the actual segmentation happens in `generate`.
2579
2580        Unlike `AutomaticPromptGenerator`, nothing is encoded here: each tile/block is encoded from
2581        scratch inside `generate`, since every tile/block needs its own encoder pass over its halo.
2582        If you give precomputed tiled `image_embeddings`, every tile/block reads its embeddings from
2583        them, and the encoder does not run.
2584
2585        Args:
2586            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
2587            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
2588            tile_shape: The inner tile/block shape, (y, x) for an image, always the full (z, y, x)
2589                for a volume - it is blocked in z too, not tiled in-plane only, so an object crossing
2590                a z seam is reconciled by the halo-overlap multicut the same way a y/x one is. Pass
2591                the full volume depth as the z entry for in-plane-only tiling (one whole-depth block
2592                per xy tile).
2593            halo: The halo added on each side of a tile/block, matching `tile_shape`'s axes.
2594            verbose: Whether each tile/block's generator prints progress while it segments it.
2595            offload_to_cpu: Volumes only, forwarded to every tile/block's own
2596                `AutomaticPromptGenerator.initialize`.
2597            cache_all_slices: Volumes only, forwarded the same way.
2598            image_embeddings: The optional precomputed tiled embeddings of the input. With `i`, the
2599                embeddings of the volume that contains the input slice. Their in-plane tile shape
2600                and halo must be the ones of `tile_shape` and `halo`.
2601            i: The index of the input slice in the volume of `image_embeddings`.
2602        """
2603        if ndim not in (2, 3):
2604            raise ValueError(f"Tiled prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
2605        if tile_shape is None or halo is None:
2606            raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled generator.")
2607        if len(tile_shape) != ndim or len(halo) != ndim:
2608            raise ValueError(
2609                f"'tile_shape' and 'halo' must have {ndim} entries for a {ndim}d input, one per spatial "
2610                "axis - always (z, y, x) for a volume, never in-plane only."
2611            )
2612        tile_shape = tuple(int(t) for t in tile_shape)
2613        halo = tuple(int(h) for h in halo)
2614        if image_embeddings is not None:
2615            _check_tiled_embeddings(image_embeddings, image.shape[:ndim], tile_shape, halo, i)
2616        self._image = image
2617        self._ndim = ndim
2618        self._tile_shape = tile_shape
2619        self._halo = halo
2620        self._verbose = verbose
2621        self._offload_to_cpu = offload_to_cpu
2622        self._cache_all_slices = cache_all_slices
2623        self._image_embeddings = image_embeddings
2624        self._i = None if image_embeddings is None else i
2625
2626    @torch.no_grad()
2627    def generate(self, *, pbar_init=None, pbar_update=None, **params) -> np.ndarray:
2628        """Segment every tile/block independently and stitch them by halo-overlap multicut.
2629
2630        `propagation_waves` reaches every tile/block unchanged, but each one propagates with its
2631        own halo as a protected margin (see `AutomaticPromptGenerator._is_protected_from_pruning`):
2632        a candidate whose anchor frame or mask reaches into that margin is never pruned as a
2633        within-tile duplicate, since it is exactly the kind of prediction the halo-overlap multicut
2634        compares against the neighbouring tile/block.
2635
2636        For a volume, every tile/block is also normalized against percentile bounds computed once
2637        over the whole image (`normalization_bounds`, see `AutomaticPromptGenerator.initialize`),
2638        never its own local crop - the same statistics an untiled `AutomaticPromptGenerator` would
2639        use, so a tile's brightness/contrast does not depend on which tile it happens to be.
2640
2641        Args:
2642            pbar_init: Initialize progress with the number of tiles and a description.
2643            pbar_update: Advance progress after each completed tile, on the calling thread.
2644            params: Keyword arguments for `AutomaticPromptGenerator.generate`, applied identically
2645                to every tile/block.
2646
2647        Returns:
2648            The stitched instance segmentation, uint32 array with the shape of the input.
2649        """
2650        if self._image is None:
2651            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
2652        if bp is None:
2653            raise RuntimeError("Tiled automatic prompt generation requires 'bioimage_py'. Install bioimage-py.")
2654
2655        params = dict(params)
2656        protected_margin = tuple(self._halo)
2657        # Computed once over the whole image/volume so every tile/block shares one normalization
2658        # instead of each estimating its own percentiles from its own, smaller, biased crop.
2659        encodes = self._ndim == 3 and self._image_embeddings is None  # Only the encoder uses the bounds.
2660        normalization_bounds = _volume_normalization_bounds(self._image) if encodes else None
2661
2662        if self._execution == "process":
2663            segment_block, num_workers = self._process_dispatch(params, normalization_bounds, protected_margin)
2664        else:
2665            segment_block, num_workers = self._thread_dispatch(params, normalization_bounds, protected_margin)
2666
2667        shape = self._image.shape[:self._ndim]
2668        n_tiles = int(np.prod([(size + tile - 1) // tile for size, tile in zip(shape, self._tile_shape)]))
2669        if pbar_init is not None:
2670            pbar_init(n_tiles, "APG: segmenting tiles")
2671
2672        def stitch(update):
2673            def segment_with_progress(block, block_id):
2674                result = segment_block(block, block_id)
2675                if update is not None:
2676                    update(1)
2677                return result
2678
2679            return bp.segmentation.stitch_segmentation(
2680                input=self._image,
2681                segmentation_function=segment_with_progress,
2682                shape=self._image.shape[:self._ndim],
2683                tile_shape=self._tile_shape,
2684                tile_overlap=self._halo,
2685                beta=self._beta,
2686                with_background=True,
2687                num_workers=num_workers,
2688                job_type="local",
2689            )
2690        output = _run_with_progress(stitch, pbar_update)
2691        return np.asarray(output).astype("uint32")
2692
2693    def _block_embedding_kwargs(self, block_id: int) -> dict:
2694        """The precomputed embeddings to initialize a block's generator with, if there are any."""
2695        if self._image_embeddings is None:
2696            return {}
2697        embeddings, i = _block_embeddings(
2698            self._image_embeddings, self._image.shape[:self._ndim], self._tile_shape, self._halo, block_id, self._i,
2699        )
2700        return {"image_embeddings": embeddings, "i": i}
2701
2702    def _thread_dispatch(self, params: dict, normalization_bounds, protected_margin: tuple):
2703        """Build the `segment_block` closure for `execution='thread'` (the default)."""
2704        if self._pool is None:
2705            self._pool = self._build_pool()
2706        available: "queue.Queue[AutomaticPromptGenerator]" = queue.Queue()
2707        for generator in self._pool:
2708            available.put(generator)
2709
2710        def segment_block(block: np.ndarray, block_id: int) -> np.ndarray:
2711            block = np.asarray(block)
2712            embedding_kwargs = self._block_embedding_kwargs(block_id)
2713            generator = available.get()
2714            # None (a worker alone on its device) skips the stream context entirely, keeping the
2715            # default stream - torch.cuda.stream(None) resolves the current device even when there
2716            # is no CUDA at all, which errors on a CPU/MPS-only machine.
2717            stream = getattr(generator, "_tile_stream", None)
2718            stream_context = torch.cuda.stream(stream) if stream is not None else contextlib.nullcontext()
2719            try:
2720                with stream_context:
2721                    generator.initialize(
2722                        block, ndim=self._ndim, verbose=self._verbose,
2723                        offload_to_cpu=self._offload_to_cpu, cache_all_slices=self._cache_all_slices,
2724                        normalization_bounds=normalization_bounds, **embedding_kwargs,
2725                    )
2726                    generator._pruning_protected_margin = protected_margin
2727                    result = generator.generate(**params)
2728                    if stream is not None:
2729                        # Block until this tile's queued GPU work is done before it is handed off:
2730                        # the caller reads 'result' outside the stream context, on another thread.
2731                        stream.synchronize()
2732                return result
2733            finally:
2734                generator.clear_state()
2735                available.put(generator)
2736
2737        return segment_block, len(self._pool)
2738
2739    def _process_dispatch(self, params: dict, normalization_bounds, protected_margin: tuple):
2740        """Build the `segment_block` closure for `execution='process'`.
2741
2742        Each call round-trips a block through its worker's task queue and a per-block reply queue,
2743        synchronously - the dispatching thread blocks on I/O while it waits, which releases the GIL,
2744        so several dispatch threads still overlap even though the real segmentation work now happens
2745        in another process entirely.
2746        """
2747        if self._processes is None:
2748            self._build_process_pool()
2749        available: "queue.Queue[int]" = queue.Queue()
2750        for worker_id in range(len(self._processes)):
2751            available.put(worker_id)
2752
2753        def segment_block(block: np.ndarray, block_id: int) -> np.ndarray:
2754            block = np.asarray(block)
2755            worker_id = available.get()
2756            if not self._processes[worker_id].is_alive():
2757                raise RuntimeError(f"process worker {worker_id} died before block {block_id} was dispatched.")
2758            result_queue = self._manager.Queue()
2759            try:
2760                self._task_queues[worker_id].put({
2761                    "block": block, "ndim": self._ndim, "protected_margin": protected_margin,
2762                    "params": params, "normalization_bounds": normalization_bounds,
2763                    "offload_to_cpu": self._offload_to_cpu, "cache_all_slices": self._cache_all_slices,
2764                    "embedding_kwargs": self._block_embedding_kwargs(block_id), "result_queue": result_queue,
2765                })
2766                try:
2767                    status, payload = result_queue.get(timeout=self._process_timeout)
2768                except queue.Empty:
2769                    raise RuntimeError(
2770                        f"process worker {worker_id} timed out after {self._process_timeout:.0f}s on "
2771                        f"block {block_id}."
2772                    )
2773                if status == "err":
2774                    raise RuntimeError(f"process worker {worker_id} failed on block {block_id}: {payload}")
2775                return payload
2776            finally:
2777                available.put(worker_id)
2778
2779        return segment_block, len(self._processes)
2780
2781    def get_state(self) -> dict:
2782        """Return the input, the tile/block geometry and the embeddings, so `set_state` can restore them."""
2783        return {
2784            "image": self._image, "ndim": self._ndim, "tile_shape": self._tile_shape, "halo": self._halo,
2785            "image_embeddings": self._image_embeddings, "i": self._i,
2786        }
2787
2788    def set_state(self, state: dict) -> None:
2789        """Restore the input, the tile/block geometry and the embeddings `initialize` stored.
2790
2791        Args:
2792            state: The state, as returned by `get_state`.
2793        """
2794        if "image" not in state:
2795            raise ValueError("A tiled prompt-generator state must hold its 'image'.")
2796        self._image = state["image"]
2797        self._ndim = state.get("ndim", 2)
2798        self._tile_shape = state.get("tile_shape")
2799        self._halo = state.get("halo")
2800        self._image_embeddings = state.get("image_embeddings")
2801        self._i = state.get("i")
2802
2803    def clear_state(self) -> None:
2804        """Clear the stored input, tile/block geometry and embeddings. The device pool stays alive."""
2805        self._image = None
2806        self._ndim = None
2807        self._tile_shape = None
2808        self._halo = None
2809        self._image_embeddings = None
2810        self._i = None
STABILITY_SCORE_OFFSET = 1.0
DEFAULT_STITCHING_BETA = 0.5
def default_prompt_generation(model_type: str = 'hvit_t_cells', is_volume: bool = False) -> dict:
 90def default_prompt_generation(model_type: str = DEFAULT_MODEL, is_volume: bool = False) -> dict:
 91    """The default APG parameters for one model and dimensionality.
 92
 93    Args:
 94        model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which
 95            uses the 'cells' defaults. Its family and backbone select the table, see `parameter_family`.
 96        is_volume: Whether to use the 3D table (`derive_volume_prompts`) or the 2D one
 97            (`derive_point_prompts`). A volume prompts once per object rather than once per slice, so
 98            the two are swept and tuned independently.
 99
100    Returns:
101        The default parameter dict for that model and dimensionality.
102    """
103    family, backbone = parameter_family(model_type), model_type[:6]
104    params = DEFAULT_PROMPT_GENERATION_PARAMETERS.get(family, {}).get(backbone)
105    if params is None:
106        raise ValueError(
107            f"No default prompt generation parameters for model type '{model_type}'. They exist for "
108            + ", ".join(f"{name}: {sorted(table)}" for name, table in DEFAULT_PROMPT_GENERATION_PARAMETERS.items())
109            + "."
110        )
111    return params["3d" if is_volume else "2d"]

The default APG parameters for one model and dimensionality.

Arguments:
  • model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which uses the 'cells' defaults. Its family and backbone select the table, see parameter_family.
  • is_volume: Whether to use the 3D table (derive_volume_prompts) or the 2D one (derive_point_prompts). A volume prompts once per object rather than once per slice, so the two are swept and tuned independently.
Returns:

The default parameter dict for that model and dimensionality.

PROPAGATION_JOBS_PER_DEVICE = 4
MIN_PASSES_PER_PROPAGATION_JOB = 4
DEFAULT_PROMPT_GENERATION = {'multimasking': True, 'refinement': 'default', 'refinement_kwargs': None, 'n_objects_per_pass': 16, 'early_stop_patience': 2, 'propagation_waves': 1, 'max_size_factor': None, 'batch_size': 64, 'dt': 0.5, 'n_threads': 8}
REFINEMENT_COMPONENTS = ('points', 'boxes', 'masks')
REFINEMENT_KWARGS = {'shared': ('policy', 'multimasking', 'min_consistency', 'max_foreign_overlap'), 'points': ('n_positives', 'n_negatives', 'max_negative_distance', 'negative_source', 'min_negative_distance'), 'boxes': ('box_extension',), 'masks': ()}
DEFAULT_REFINEMENT = {'policy': 'replace', 'multimasking': False, 'min_consistency': 0.7, 'max_foreign_overlap': 0.15, 'n_positives': 1, 'n_negatives': 6, 'max_negative_distance': None, 'negative_source': 'prompts', 'min_negative_distance': 0, 'box_extension': 0}
CONDITIONING_MODES = ('prompts', 'prompts-grouped', 'prompts-joint', 'mask')
REFINEMENT_KWARGS_3D = {'shared': ('policy', 'multimasking', 'min_consistency', 'max_foreign_overlap', 'conditioning'), 'points': ('n_positives', 'n_negatives', 'max_negative_distance', 'negative_source', 'min_negative_distance'), 'boxes': ('box_extension',), 'masks': ()}
DEFAULT_REFINEMENT_3D = {'policy': 'replace', 'multimasking': False, 'min_consistency': 0.85, 'max_foreign_overlap': 0.15, 'n_positives': 1, 'n_negatives': 4, 'max_negative_distance': None, 'negative_source': 'prompts', 'min_negative_distance': 0, 'box_extension': 0, 'conditioning': 'prompts'}
REFINEMENT_STATS_3D = ('refined_candidates', 'replaced_candidates', 'gated_consistency', 'gated_foreign', 'refinement_negatives')
def mask_to_logits(mask: numpy.ndarray, eps: float = 0.001) -> numpy.ndarray:
260def mask_to_logits(mask: np.ndarray, eps: float = 1e-3) -> np.ndarray:
261    """Turn a binary mask into the low-resolution logit prompt SAM2 expects.
262
263    The image predictor preserves the aspect ratio and pads the bottom or right side. The mask uses
264    the same frame, so it stays aligned with the image features and other prompts.
265
266    Args:
267        mask: The binary mask, shape (Y, X).
268        eps: Probability assigned to the background, from which the logit magnitude follows.
269
270    Returns:
271        The logits, shape (1, 256, 256), float32.
272    """
273    binary = torch.from_numpy(np.asarray(mask, dtype="float32"))[None, None]
274    resized, _ = resize_longest_side_and_pad_tensor(binary, target_length=256)
275    logit = float(np.log((1.0 - eps) / eps))
276    return np.where(resized[0].numpy() > 0.5, logit, -logit).astype("float32")

Turn a binary mask into the low-resolution logit prompt SAM2 expects.

The image predictor preserves the aspect ratio and pads the bottom or right side. The mask uses the same frame, so it stays aligned with the image features and other prompts.

Arguments:
  • mask: The binary mask, shape (Y, X).
  • eps: Probability assigned to the background, from which the logit magnitude follows.
Returns:

The logits, shape (1, 256, 256), float32.

def derive_refinement_prompts( segmentation: numpy.ndarray, points: numpy.ndarray, surviving_points: Dict[int, tuple], n_positives: int = 1, n_negatives: int = 6, max_negative_distance: Optional[float] = None, negative_source: str = 'prompts', min_negative_distance: float = 0) -> Dict[int, Dict[str, numpy.ndarray]]:
384def derive_refinement_prompts(
385    segmentation: np.ndarray,
386    points: np.ndarray,
387    surviving_points: Dict[int, tuple],
388    n_positives: int = DEFAULT_REFINEMENT["n_positives"],
389    n_negatives: int = DEFAULT_REFINEMENT["n_negatives"],
390    max_negative_distance: Optional[float] = DEFAULT_REFINEMENT["max_negative_distance"],
391    negative_source: str = DEFAULT_REFINEMENT["negative_source"],
392    min_negative_distance: float = DEFAULT_REFINEMENT["min_negative_distance"],
393) -> Dict[int, Dict[str, np.ndarray]]:
394    """Group the first round's prompts onto the instances they landed in and derive re-prompts.
395
396    An instance's positives are the prompt that made it plus the suppressed prompts inside it: each
397    marks a spot the decoder proposed an object at, so together they cover the instance in a way a
398    single point cannot. Its negatives are nearby points belonging to other instances, which tell
399    the model where the instance ends.
400
401    Args:
402        segmentation: The instance segmentation of the first round.
403        points: All first-round prompt points as (N, 2) in XY, including the suppressed ones.
404        surviving_points: The prompt that made each instance, as {instance_id: (x, y)}.
405        n_positives: Number of positive points per instance, including the surviving prompt. The
406            surplus is subsampled farthest-point-first, for spatial coverage.
407        n_negatives: Number of negative points per instance. The surplus is dropped farthest-first,
408            measured to the instance's bounding box.
409        max_negative_distance: Only points within this distance of an instance's bounding box can
410            be its negatives. None takes the nearest ones regardless of distance.
411        negative_source: Where the negatives come from: the other instances' first-round 'prompts',
412            or the deepest 'interior' point of each other instance's mask, which sits away from any
413            border the two instances share.
414        min_negative_distance: Exclude negatives closer than this to the instance's own mask. A
415            negative that touches the instance's true extent cuts into the object instead of
416            bounding it, which is the suspected failure on densely packed data.
417
418    Returns:
419        The prompts per instance, as {instance_id: {'points': (M, 2) XY, 'point_labels': (M,),
420        'n_grouped': int}}, where 'n_grouped' counts the suppressed prompts grouped onto the
421        instance before any subsampling - the supply signal an adaptive re-prompt keys on.
422    """
423    points = np.asarray(points, dtype="float32").reshape(-1, 2)
424    assignment = _assign_points_to_instances(segmentation, points)
425
426    if negative_source == "interior":
427        # One deep interior point per instance, ordered by ascending instance id; converted to XY.
428        interior = interior_points(segmentation)[:, ::-1].astype("float32")
429        present = np.array(sorted(surviving_points), dtype="int64")
430        negative_points, negative_owners = interior, present
431    elif negative_source == "prompts":
432        foreign = assignment > 0
433        negative_points, negative_owners = points[foreign], assignment[foreign]
434    else:
435        raise ValueError(f"Invalid negative_source {negative_source!r}: expected 'prompts' or 'interior'.")
436
437    prompts = {}
438    for index, bounding_box in enumerate(find_objects(segmentation), start=1):
439        if bounding_box is None:
440            continue
441        anchor = np.asarray(surviving_points[index], dtype="float32")
442        grouped = points[assignment == index]
443        # The anchor is one of the grouped points; keep it once, as the seed of the subsampling.
444        grouped = grouped[np.linalg.norm(grouped - anchor, axis=1) > 0]
445        positives = _subsample_positives(anchor, grouped, n_positives)
446
447        allowed = negative_owners != index
448        candidates = negative_points[allowed]
449        if min_negative_distance > 0 and len(candidates) and n_negatives > 0:
450            distances = _distances_to_mask(segmentation, index, bounding_box, candidates, min_negative_distance)
451            candidates = candidates[distances >= min_negative_distance]
452        negatives = _select_negatives(candidates, bounding_box, n_negatives, max_negative_distance)
453
454        prompts[index] = {
455            "points": np.concatenate([positives, negatives]).astype("float32"),
456            "point_labels": np.concatenate([
457                np.ones(len(positives), dtype="int32"), np.zeros(len(negatives), dtype="int32"),
458            ]),
459            "n_grouped": int(len(grouped)),
460        }
461    return prompts

Group the first round's prompts onto the instances they landed in and derive re-prompts.

An instance's positives are the prompt that made it plus the suppressed prompts inside it: each marks a spot the decoder proposed an object at, so together they cover the instance in a way a single point cannot. Its negatives are nearby points belonging to other instances, which tell the model where the instance ends.

Arguments:
  • segmentation: The instance segmentation of the first round.
  • points: All first-round prompt points as (N, 2) in XY, including the suppressed ones.
  • surviving_points: The prompt that made each instance, as {instance_id: (x, y)}.
  • n_positives: Number of positive points per instance, including the surviving prompt. The surplus is subsampled farthest-point-first, for spatial coverage.
  • n_negatives: Number of negative points per instance. The surplus is dropped farthest-first, measured to the instance's bounding box.
  • max_negative_distance: Only points within this distance of an instance's bounding box can be its negatives. None takes the nearest ones regardless of distance.
  • negative_source: Where the negatives come from: the other instances' first-round 'prompts', or the deepest 'interior' point of each other instance's mask, which sits away from any border the two instances share.
  • min_negative_distance: Exclude negatives closer than this to the instance's own mask. A negative that touches the instance's true extent cuts into the object instead of bounding it, which is the suspected failure on densely packed data.
Returns:

The prompts per instance, as {instance_id: {'points': (M, 2) XY, 'point_labels': (M,), 'n_grouped': int}}, where 'n_grouped' counts the suppressed prompts grouped onto the instance before any subsampling - the supply signal an adaptive re-prompt keys on.

def interior_points(labels: numpy.ndarray) -> numpy.ndarray:
521def interior_points(labels: np.ndarray) -> np.ndarray:
522    """The deepest interior point of every labelled component, in ascending label order.
523
524    The v1 counterpart transforms a `find_boundaries` image, whose 'outer' mode marks a thin
525    component's own pixels as boundary. Its maximum then falls on the bounding box's first pixel,
526    which need not lie in the component at all.
527
528    Args:
529        labels: A labelled image or volume.
530
531    Returns:
532        The points as (N, ndim), one per component, in the array's own axis order.
533    """
534    points = []
535    for index, bounding_box in enumerate(find_objects(labels), start=1):
536        if bounding_box is None:
537            continue
538        # Padded, so a component reaching the border is measured from that border too.
539        distances = distance_transform(np.pad(labels[bounding_box] == index, 1))
540        coordinates = np.unravel_index(int(np.argmax(distances)), distances.shape)
541        points.append(tuple(int(c) + box.start - 1 for c, box in zip(coordinates, bounding_box)))
542    return np.array(points, dtype="int64").reshape(-1, labels.ndim)

The deepest interior point of every labelled component, in ascending label order.

The v1 counterpart transforms a find_boundaries image, whose 'outer' mode marks a thin component's own pixels as boundary. Its maximum then falls on the bounding box's first pixel, which need not lie in the component at all.

Arguments:
  • labels: A labelled image or volume.
Returns:

The points as (N, ndim), one per component, in the array's own axis order.

def derive_point_prompts( foreground: numpy.ndarray, directed_distances: numpy.ndarray, model_type: str = 'hvit_t_cells', candidate_threshold: Optional[float] = None, foreground_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, min_candidate_size: Optional[int] = None, n_threads: int = 8) -> Optional[Dict[str, numpy.ndarray]]:
545def derive_point_prompts(
546    foreground: np.ndarray,
547    directed_distances: np.ndarray,
548    model_type: str = DEFAULT_MODEL,
549    candidate_threshold: Optional[float] = None,
550    foreground_threshold: Optional[float] = None,
551    n_iter: Optional[int] = None,
552    dt: Optional[float] = None,
553    sigma: Optional[float] = None,
554    min_candidate_size: Optional[int] = None,
555    n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
556) -> Optional[Dict[str, np.ndarray]]:
557    """Derive one positive point prompt per convergence-density component.
558
559    The v1 counterpart intersects thresholded centre and boundary distances; UniSAM2 predicts directed
560    distances instead, so the candidates come from the flow-convergence density that the sparse
561    post-processing also seeds from, thresholded lower.
562
563    Args:
564        foreground: Foreground probability map, shape (Y, X).
565        directed_distances: Distance channels stacked along axis 0. A leading z-channel is dropped, so
566            `prediction[1:4]` can be passed regardless of dimensionality.
567        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
568            for any of the tunable parameters below left as None, see `default_prompt_generation`.
569        candidate_threshold: Density threshold for proposing candidates. Lower proposes more. The density
570            of a component scales with the object's area, so this is coupled to object size.
571        foreground_threshold: Foreground binarisation threshold, which bounds the pixels that can be
572            proposed from.
573        n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a pixel is
574            advected, which has to be enough to reach the object's centre.
575        dt: Integration step size. Mostly only the product with 'n_iter' matters.
576        sigma: Gaussian sigma for smoothing the convergence-density map.
577        min_candidate_size: Discard components smaller than this, which are noise rather than objects.
578        n_threads: Number of threads for the flow computation.
579
580    Returns:
581        The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1)}, or None if none were found.
582    """
583    defaults = default_prompt_generation(model_type, is_volume=False)
584    if candidate_threshold is None:
585        candidate_threshold = defaults["candidate_threshold"]
586    if foreground_threshold is None:
587        foreground_threshold = defaults["foreground_threshold"]
588    if n_iter is None:
589        n_iter = defaults["n_iter"]
590    if dt is None:
591        dt = DEFAULT_PROMPT_GENERATION["dt"]
592    if sigma is None:
593        sigma = defaults["sigma"]
594    if min_candidate_size is None:
595        min_candidate_size = defaults["min_candidate_size"]
596
597    if directed_distances.shape[0] > foreground.ndim:
598        directed_distances = directed_distances[-foreground.ndim:]
599
600    fg_mask = foreground > foreground_threshold
601    density = _compute_flow_density(
602        directed_distances, fg_mask, n_iter=int(n_iter), dt=dt, sigma=sigma, n_threads=n_threads,
603    )
604    candidates = label(density > candidate_threshold)
605
606    if min_candidate_size > 0:
607        ids, sizes = np.unique(candidates, return_counts=True)
608        discard = ids[(sizes < min_candidate_size) & (ids > 0)]
609        if discard.size:
610            candidates[np.isin(candidates, discard)] = 0
611    if candidates.max() == 0:
612        return None
613
614    # The interior point rather than the centroid, which can lie outside a curved object.
615    centers = interior_points(candidates)
616    if len(centers) == 0:
617        return None
618
619    return {
620        "points": np.ascontiguousarray(centers[:, ::-1], dtype="float32")[:, None, :],  # SAM2 wants XY
621        "point_labels": np.ones((len(centers), 1), dtype="int32"),
622    }

Derive one positive point prompt per convergence-density component.

The v1 counterpart intersects thresholded centre and boundary distances; UniSAM2 predicts directed distances instead, so the candidates come from the flow-convergence density that the sparse post-processing also seeds from, thresholded lower.

Arguments:
  • foreground: Foreground probability map, shape (Y, X).
  • directed_distances: Distance channels stacked along axis 0. A leading z-channel is dropped, so prediction[1:4] can be passed regardless of dimensionality.
  • model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default for any of the tunable parameters below left as None, see default_prompt_generation.
  • candidate_threshold: Density threshold for proposing candidates. Lower proposes more. The density of a component scales with the object's area, so this is coupled to object size.
  • foreground_threshold: Foreground binarisation threshold, which bounds the pixels that can be proposed from.
  • n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a pixel is advected, which has to be enough to reach the object's centre.
  • dt: Integration step size. Mostly only the product with 'n_iter' matters.
  • sigma: Gaussian sigma for smoothing the convergence-density map.
  • min_candidate_size: Discard components smaller than this, which are noise rather than objects.
  • n_threads: Number of threads for the flow computation.
Returns:

The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1)}, or None if none were found.

def derive_volume_prompts( foreground: numpy.ndarray, directed_distances: numpy.ndarray, model_type: str = 'hvit_t_cells', candidate_threshold: Union[float, Sequence[float], NoneType] = None, foreground_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, spacing: Optional[tuple] = None, min_candidate_size: Optional[int] = None, n_threads: int = 8) -> Optional[Dict[str, numpy.ndarray]]:
625def derive_volume_prompts(
626    foreground: np.ndarray,
627    directed_distances: np.ndarray,
628    model_type: str = DEFAULT_MODEL,
629    candidate_threshold: Optional[Union[float, Sequence[float]]] = None,
630    foreground_threshold: Optional[float] = None,
631    n_iter: Optional[int] = None,
632    dt: Optional[float] = None,
633    sigma: Optional[float] = None,
634    spacing: Optional[tuple] = None,
635    min_candidate_size: Optional[int] = None,
636    n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
637) -> Optional[Dict[str, np.ndarray]]:
638    """Derive one positive point prompt, on one slice, per volumetric convergence-density component.
639
640    The volumetric counterpart of `derive_point_prompts`. The flow is integrated in 3d, so a component
641    of the resulting density is a whole object rather than one of its cross-sections, and each object
642    is prompted once instead of once per slice. The prompt is placed on the slice where the component
643    converges most, which is the slice the video predictor propagates away from in both directions.
644
645    Args:
646        foreground: Foreground probability map, shape (Z, Y, X).
647        directed_distances: Distance channels stacked along axis 0, shape (3, Z, Y, X).
648        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
649            for any of the tunable parameters below left as None, see `default_prompt_generation`.
650        candidate_threshold: Density threshold for proposing candidates, or several of them. Lower
651            proposes more, but also merges the peaks of touching objects into one component, so a
652            ladder recovers what a single threshold cannot separate.
653        foreground_threshold: Foreground binarisation threshold, which bounds the voxels that can be
654            proposed from.
655        n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a voxel is
656            advected, which has to be enough to reach the object's centre.
657        dt: Integration step size. Mostly only the product with 'n_iter' matters.
658        sigma: Gaussian sigma for smoothing the convergence-density map.
659        spacing: Anisotropic voxel spacing, e.g. (4, 1, 1), for physically isotropic smoothing.
660        min_candidate_size: Discard components smaller than this, which are noise rather than objects.
661        n_threads: Number of threads for the flow computation.
662
663    Returns:
664        The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1), 'frames': (N,) slice
665        indices}, or None if no candidate was found.
666    """
667    if foreground.ndim != 3:
668        raise ValueError(f"Volumetric prompt generation expects a (Z, Y, X) foreground map, got {foreground.shape}.")
669    if directed_distances.shape[0] != 3:
670        raise ValueError(f"Expected 3 distance channels, got {directed_distances.shape[0]}.")
671
672    defaults = default_prompt_generation(model_type, is_volume=True)
673    if candidate_threshold is None:
674        candidate_threshold = defaults["candidate_threshold"]
675    if foreground_threshold is None:
676        foreground_threshold = defaults["foreground_threshold"]
677    if n_iter is None:
678        n_iter = defaults["n_iter"]
679    if dt is None:
680        dt = DEFAULT_PROMPT_GENERATION["dt"]
681    if sigma is None:
682        sigma = defaults["sigma"]
683    if min_candidate_size is None:
684        min_candidate_size = defaults["min_candidate_size"]
685
686    fg_mask = foreground > foreground_threshold
687    density = _compute_flow_density(
688        directed_distances, fg_mask, n_iter=int(n_iter), dt=dt, sigma=sigma, spacing=spacing,
689        n_threads=n_threads,
690    )
691
692    levels = sorted(np.atleast_1d(np.asarray(candidate_threshold, dtype="float32")).tolist(), reverse=True)
693    points, frames, seen = [], [], set()
694    # Descending, so that the peaks a lower threshold merges into one component are proposed first.
695    for threshold in levels:
696        candidates = label(density > threshold)
697        if min_candidate_size > 0:
698            ids, sizes = np.unique(candidates, return_counts=True)
699            discard = ids[(sizes < min_candidate_size) & (ids > 0)]
700            if discard.size:
701                candidates[np.isin(candidates, discard)] = 0
702
703        for index, bounding_box in enumerate(find_objects(candidates)):
704            if bounding_box is None:
705                continue
706            component = candidates[bounding_box] == (index + 1)
707            component_density = np.where(component, density[bounding_box], 0.0)
708            # The most converged slice, i.e. the one closest to the object's centre.
709            z = int(np.argmax(component_density.sum(axis=(1, 2))))
710            plane = component_density[z]
711            # The density peak: it is inside the component and the least ambiguous prompt.
712            y, x = np.unravel_index(int(np.argmax(plane)), plane.shape)
713            anchor = (bounding_box[0].start + z, bounding_box[1].start + y, bounding_box[2].start + x)
714            # A component that no lower threshold has merged peaks at the same voxel at every level.
715            if anchor in seen:
716                continue
717            seen.add(anchor)
718            frames.append(anchor[0])
719            points.append((anchor[2], anchor[1]))  # SAM2 wants XY.
720
721    if not points:
722        return None
723
724    return {
725        "points": np.array(points, dtype="float32")[:, None, :],
726        "point_labels": np.ones((len(points), 1), dtype="int32"),
727        "frames": np.array(frames, dtype="int64"),
728    }

Derive one positive point prompt, on one slice, per volumetric convergence-density component.

The volumetric counterpart of derive_point_prompts. The flow is integrated in 3d, so a component of the resulting density is a whole object rather than one of its cross-sections, and each object is prompted once instead of once per slice. The prompt is placed on the slice where the component converges most, which is the slice the video predictor propagates away from in both directions.

Arguments:
  • foreground: Foreground probability map, shape (Z, Y, X).
  • directed_distances: Distance channels stacked along axis 0, shape (3, Z, Y, X).
  • model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default for any of the tunable parameters below left as None, see default_prompt_generation.
  • candidate_threshold: Density threshold for proposing candidates, or several of them. Lower proposes more, but also merges the peaks of touching objects into one component, so a ladder recovers what a single threshold cannot separate.
  • foreground_threshold: Foreground binarisation threshold, which bounds the voxels that can be proposed from.
  • n_iter: Number of flow-integration steps. Together with 'dt' this is the distance a voxel is advected, which has to be enough to reach the object's centre.
  • dt: Integration step size. Mostly only the product with 'n_iter' matters.
  • sigma: Gaussian sigma for smoothing the convergence-density map.
  • spacing: Anisotropic voxel spacing, e.g. (4, 1, 1), for physically isotropic smoothing.
  • min_candidate_size: Discard components smaller than this, which are noise rather than objects.
  • n_threads: Number of threads for the flow computation.
Returns:

The prompts as {'points': (N, 1, 2) in XY, 'point_labels': (N, 1), 'frames': (N,) slice indices}, or None if no candidate was found.

def merge_by_score( records: List[Dict[str, Any]], shape: tuple, max_overlap: float = 0.3, min_size: int = 50, max_size_factor: Optional[float] = None, keep_largest_component: bool = False, return_matches: bool = False, return_reasons: bool = False) -> Union[numpy.ndarray, tuple]:
746def merge_by_score(
747    records: List[Dict[str, Any]], shape: tuple, max_overlap: float = 0.3, min_size: int = 50,
748    max_size_factor: Optional[float] = None, keep_largest_component: bool = False,
749    return_matches: bool = False, return_reasons: bool = False,
750) -> Union[np.ndarray, tuple]:
751    """Merge prediction records in descending score order, each claiming only unclaimed pixels.
752
753    Linear in the number of candidates, where `micro_sam.util.apply_nms` is quadratic, and marginally
754    better on livecell: truncating a later mask preserves the better-scoring instance's boundary.
755
756    A record carries a 'bounding_box' (a tuple of slices) and its mask is only the crop inside that
757    box, so both the merge and the records themselves scale with the objects rather than with the
758    image. A volumetric mask per object would otherwise make the 3d generator run out of memory.
759
760    Args:
761        records: The prediction records, as produced by `AutomaticPromptGenerator._apply_prompts`.
762        shape: The spatial shape of the output.
763        max_overlap: Reject a candidate when more than this fraction of it is already claimed. This is
764            the duplicate suppression of the merge.
765        min_size: Minimum object size to keep.
766        max_size_factor: Reject a candidate larger than this multiple of the median record size.
767            Catches propagation drift: a track that grows onto background instead of ending produces
768            an occasional candidate many times larger than every real object, most easily seen next
769            to the rest of the same call's candidates rather than by any fixed size. None (the
770            default) applies no such cap.
771        keep_largest_component: Whether to paint only the largest connected component of a
772            candidate's unclaimed pixels. Truncating a mask by the better-scoring ones around it
773            leaves specks and slivers where their boundaries disagree by a pixel or two, which
774            would otherwise stay part of the instance, detached from it. Dropping them keeps every
775            instance in one piece; on the 2d benchmark it never lowered mSA and gains up to 0.002.
776        return_matches: Whether to also return which record made each instance.
777        return_reasons: Whether to also return why each record was kept or dropped. A candidate is
778            'too small', 'too large', a 'duplicate' when a better-scoring mask already claims more
779            than 'max_overlap' of it, 'truncated below min size' when too few of its pixels are free,
780            or 'kept'. This is what the merge does, reported rather than recomputed.
781
782    Returns:
783        The instance segmentation, uint32 array. If `return_matches`, additionally a mapping from
784        every instance id to the index of the record that made it. If `return_reasons`, additionally
785        the reason per record, in the order the records were given.
786    """
787    out = np.zeros(shape, dtype="uint32")
788    next_id = 1
789    scores = np.array([record["predicted_iou"] * record["stability_score"] for record in records])
790    if not np.isfinite(scores).all():
791        raise ValueError("Every merge score must be finite.")
792    max_size = None
793    if max_size_factor is not None and records:
794        areas = np.array([int(_record_mask(record).sum()) for record in records])
795        max_size = max_size_factor * np.median(areas)
796    full_box = tuple(slice(None) for _ in shape)
797    matches = {}
798    reasons = ["" for _ in records]
799    for index in sorted(range(len(records)), key=lambda candidate: (-scores[candidate], candidate)):
800        record = records[index]
801        mask = _record_mask(record)
802        area = int(mask.sum())
803        if area < min_size:
804            reasons[index] = "too small"
805            continue
806        if max_size is not None and area > max_size:
807            reasons[index] = "too large"
808            continue
809        # A view, so painting the fresh pixels below writes straight into the output.
810        box = record.get("bounding_box", full_box)
811        target = out[box]
812        claimed = target[mask]
813        n_claimed = int(np.count_nonzero(claimed))
814        if n_claimed / area > max_overlap:
815            reasons[index] = "duplicate"
816            continue
817        fresh = mask & (target == 0)
818        if keep_largest_component:
819            fresh = _largest_component(fresh)
820        n_gained = int(fresh.sum())
821        if n_gained < min_size:
822            reasons[index] = "truncated below min size"
823            continue
824        target[fresh] = next_id
825        reasons[index] = "kept"
826        matches[next_id] = int(index)
827        next_id += 1
828
829    result = (out,)
830    if return_matches:
831        result += (matches,)
832    if return_reasons:
833        result += (reasons,)
834    return result[0] if len(result) == 1 else result

Merge prediction records in descending score order, each claiming only unclaimed pixels.

Linear in the number of candidates, where micro_sam.util.apply_nms is quadratic, and marginally better on livecell: truncating a later mask preserves the better-scoring instance's boundary.

A record carries a 'bounding_box' (a tuple of slices) and its mask is only the crop inside that box, so both the merge and the records themselves scale with the objects rather than with the image. A volumetric mask per object would otherwise make the 3d generator run out of memory.

Arguments:
  • records: The prediction records, as produced by AutomaticPromptGenerator._apply_prompts.
  • shape: The spatial shape of the output.
  • max_overlap: Reject a candidate when more than this fraction of it is already claimed. This is the duplicate suppression of the merge.
  • min_size: Minimum object size to keep.
  • max_size_factor: Reject a candidate larger than this multiple of the median record size. Catches propagation drift: a track that grows onto background instead of ending produces an occasional candidate many times larger than every real object, most easily seen next to the rest of the same call's candidates rather than by any fixed size. None (the default) applies no such cap.
  • keep_largest_component: Whether to paint only the largest connected component of a candidate's unclaimed pixels. Truncating a mask by the better-scoring ones around it leaves specks and slivers where their boundaries disagree by a pixel or two, which would otherwise stay part of the instance, detached from it. Dropping them keeps every instance in one piece; on the 2d benchmark it never lowered mSA and gains up to 0.002.
  • return_matches: Whether to also return which record made each instance.
  • return_reasons: Whether to also return why each record was kept or dropped. A candidate is 'too small', 'too large', a 'duplicate' when a better-scoring mask already claims more than 'max_overlap' of it, 'truncated below min size' when too few of its pixels are free, or 'kept'. This is what the merge does, reported rather than recomputed.
Returns:

The instance segmentation, uint32 array. If return_matches, additionally a mapping from every instance id to the index of the record that made it. If return_reasons, additionally the reason per record, in the order the records were given.

class AutomaticPromptGenerator(micro_sam.v2.instance_segmentation.UniSAM2InstanceSegmentation):
 897class AutomaticPromptGenerator(UniSAM2InstanceSegmentation):
 898    """Generates an instance segmentation automatically, from prompts derived from the UniSAM2 decoder.
 899
 900    Used in the same way as `UniSAM2InstanceSegmentation`, and the counterpart of
 901    `micro_sam.v1.instance_segmentation.AutomaticPromptGenerator`:
 902    ```python
 903    segmenter = AutomaticPromptGenerator(model, predictor)
 904    segmenter.initialize(image, ndim=2)  # Encode the image, then run the decoder on the encoding.
 905    masks = segmenter.generate(score_threshold=0.6)  # Prompt, then merge the masks.
 906    ```
 907
 908    Volumes are segmented by passing the SAM2 video predictor instead of an image predictor:
 909    ```python
 910    segmenter = AutomaticPromptGenerator(model, video_predictor)
 911    segmenter.initialize(volume, ndim=3)
 912    masks = segmenter.generate()  # Prompt one slice per object, propagate, then merge the masks.
 913    ```
 914    The decoder finds the objects and the interactive branch segments them either way. What differs is
 915    that an object's mask comes from propagating one prompt through the volume rather than from a
 916    single forward pass, and that the candidates are scored in 2d on the slice they are prompted on,
 917    which drops the weak and the duplicate ones before the propagation - which is where the cost is.
 918    The decoder and the video predictor read the same 3d embeddings, so the volume is encoded once.
 919
 920    Args:
 921        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
 922        predictor: The SAM2 image predictor for the interactive branch of the same model, or its
 923            video predictor, which is what a volume is prompted with.
 924        device: The device the model lives on (used for the non-tiled 2d decoder).
 925        inference_device: The device intent used as the `devices=None` fallback. Defaults to the
 926            model device (single GPU); pass None to fan out over all visible GPUs, or a device / list.
 927    """
 928
 929    # Read by `automatic_instance_segmentation` to decide whether to pass the AIS 'mode' argument.
 930    _has_postprocessing_mode = False
 931    _model_type = DEFAULT_MODEL
 932
 933    def __init__(
 934        self,
 935        model: torch.nn.Module,
 936        predictor,
 937        device: Optional[Union[str, torch.device]] = None,
 938        inference_device: Devices = USE_MODEL_DEVICE,
 939    ) -> None:
 940        super().__init__(model, device=device, inference_device=inference_device)
 941        self._video_predictor = predictor if hasattr(predictor, "propagate_in_video") else None
 942        if self._video_predictor is None:
 943            self._predictor = configure_image_predictor(predictor)
 944        else:
 945            # Build the image predictor on the video predictor's weights.
 946            self._predictor = get_sam2_image_predictor(predictor)
 947        predictor = self._predictor
 948
 949        self._image_embeddings = None
 950        self._volume = None
 951        self._propagator = None
 952        self._offload_to_cpu = None
 953        self._max_cached_frames = None
 954        self._temporary_embedding_path = None
 955        self._i = None
 956        self._owns_image_embeddings = False
 957        self._last_generation_stats = {}
 958        # Set by 'TiledAutomaticPromptGenerator' to this block's full spatial halo before propagating,
 959        # so pruning never drops a candidate the halo-overlap multicut might need; None elsewhere.
 960        self._pruning_protected_margin: Optional[tuple] = None
 961        self._scoring_predictor_pool = None
 962        # The embedding cache is keyed on these, which a SAM2 image predictor does not carry itself.
 963        sam2_model = getattr(predictor, "model", None)
 964        if getattr(predictor, "model_type", None) is None:
 965            predictor.model_type = getattr(sam2_model, "model_type", None) or "hvit"
 966        if getattr(predictor, "model_name", None) is None:
 967            predictor.model_name = getattr(sam2_model, "model_name", None) or predictor.model_type
 968
 969    def _encode(self, image: np.ndarray) -> dict:
 970        """Run the image encoder once and return the embeddings that both branches use."""
 971        self._predictor.reset_predictor()
 972        # Preserve each microscopy channel's contrast before SAM2 sees the image.
 973        encode_image(self._predictor, to_image(image))
 974        return {
 975            "features": self._predictor.get_image_embedding().cpu().numpy(),
 976            "high_res_feats": self._predictor._features["high_res_feats"],
 977            "input_size": self._predictor.model.image_size,
 978            "original_size": self._predictor._orig_hw,
 979        }
 980
 981    def _prepare_image_embeddings(self, image_embeddings: dict, i: Optional[int]) -> dict:
 982        """Prepare image embeddings for the interactive branch."""
 983        if i is None:
 984            set_precomputed(self._predictor, image_embeddings)
 985            return image_embeddings
 986
 987        if "fpn" not in image_embeddings:
 988            raise ValueError("A slice index requires video-style embeddings with FPN features.")
 989        _set_image_predictor_from_3d_embeddings(self._predictor, image_embeddings, i)
 990        return {
 991            "features": self._predictor.get_image_embedding().detach().cpu().numpy(),
 992            "high_res_feats": self._predictor._features["high_res_feats"],
 993            "input_size": self._predictor.model.image_size,
 994            "original_size": self._predictor._orig_hw,
 995        }
 996
 997    def initialize(
 998        self,
 999        image: np.ndarray,
1000        ndim: int = 2,
1001        image_embeddings: Optional[dict] = None,
1002        i: Optional[int] = None,
1003        save_path: Optional[str] = None,
1004        verbose: bool = False,
1005        offload_to_cpu: Optional[bool] = None,
1006        cache_all_slices: bool = False,
1007        lazy_embeddings: bool = True,
1008        normalization_bounds: Optional[tuple] = None,
1009        **kwargs,
1010    ) -> None:
1011        """Encode the input, run the decoder on that encoding and leave the predictor ready to be prompted.
1012
1013        Both branches of a joint checkpoint share their image encoder weights, so one pass serves both
1014        and `generate` can be called repeatedly without any further encoding.
1015
1016        Args:
1017            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
1018            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
1019            image_embeddings: Optional precomputed image embeddings. If given, the encoder does not run.
1020            i: The slice index for video-style embeddings. By default the embeddings contain one image.
1021            save_path: Optional path to cache the embeddings of a volume in a zarr container. Without
1022                one an ephemeral store is used, which `clear_state` removes.
1023            verbose: Whether to print progress while the embeddings of a volume are computed.
1024            offload_to_cpu: Whether a volume's tracking state is held on the host rather than on the
1025                device. False propagates the same masks 6-11% faster, for the memory of one pass of
1026                objects across the volume, which is about 17 MB per slice at the default pass size.
1027                None leaves the choice to `PromptableSegmentation3D`, which offloads on cuda.
1028            cache_all_slices: Whether every slice's features stay on the device while a volume is
1029                propagated. A pass walks the whole volume, so a cache shorter than it is never hit
1030                and every slice is fetched again on every pass - which is most of the run on a deep
1031                volume. Costs about 90 MB of device memory per slice.
1032            lazy_embeddings: Whether a volume's embeddings are read from their store slice by slice.
1033                False holds them in host memory instead, which makes the fetch above much cheaper
1034                without spending device memory.
1035            normalization_bounds: Volumes only. Precomputed (lower, upper) percentile bounds (see
1036                `batched_inference._volume_normalization_bounds`), normally computed from `image`
1037                itself. Pass this when `image` is only a tile/block of a larger volume, so it shares
1038                that volume's bounds instead of estimating its own from its own, smaller, biased crop
1039                (see `TiledAutomaticPromptGenerator.generate`).
1040            kwargs: Additional arguments for `UniSAM2InstanceSegmentation.initialize`.
1041        """
1042        if ndim not in (2, 3):
1043            raise ValueError(f"Automatic prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
1044
1045        # A volume leaves a propagator and possibly a temporary embedding store behind. Release both
1046        # before replacing its state, including when the next input is a 2d image.
1047        if self._volume is not None or self._temporary_embedding_path is not None:
1048            self.clear_state()
1049
1050        if ndim == 3:
1051            self._i = None
1052            self._initialize_volume(
1053                image, image_embeddings, save_path, verbose, offload_to_cpu, cache_all_slices,
1054                lazy_embeddings, normalization_bounds=normalization_bounds, **kwargs
1055            )
1056            return
1057
1058        owns_image_embeddings = image_embeddings is None
1059        if image_embeddings is None:
1060            image_embeddings = self._encode(image)
1061        else:
1062            image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1063        super().initialize(image, ndim=ndim, image_embeddings=image_embeddings, **kwargs)
1064        self._image_embeddings = image_embeddings
1065        self._i = None
1066        self._owns_image_embeddings = owns_image_embeddings
1067
1068    def _build_propagator(self, volume, image_embeddings) -> ReplicatedPromptableSegmentation3D:
1069        """The video predictor this volume is propagated with, one state per inference device."""
1070        return ReplicatedPromptableSegmentation3D(
1071            self._video_predictor, volume, image_embeddings, devices=self._inference_devices(None),
1072            offload_state_to_cpu=self._offload_to_cpu, max_cached_frames=self._max_cached_frames,
1073            release_stale_mask_memory=True,
1074        )
1075
1076    def _initialize_volume(
1077        self, volume, image_embeddings, save_path, verbose, offload_to_cpu, cache_all_slices,
1078        lazy_embeddings, normalization_bounds=None, **kwargs
1079    ) -> None:
1080        """Encode the volume, run the decoder on that encoding and initialize the video predictor."""
1081        if self._video_predictor is None:
1082            raise ValueError(
1083                "Volumetric prompt generation prompts the SAM2 video predictor, so it has to be "
1084                "constructed with one instead of an image predictor."
1085            )
1086        if volume.ndim not in (3, 4):
1087            raise ValueError(
1088                f"Volumetric prompt generation expects a (Z, Y, X) or (Z, Y, X, C) volume, got shape {volume.shape}."
1089            )
1090
1091        owns_image_embeddings = image_embeddings is None
1092        if image_embeddings is None:
1093            path = save_path
1094            if path is None:
1095                self._temporary_embedding_path = make_temp_embedding_path()
1096                path = self._temporary_embedding_path
1097            image_embeddings = precompute_image_embeddings(
1098                self._video_predictor, volume, save_path=path, ndim=3, verbose=verbose,
1099                lazy_loading=lazy_embeddings, devices=self._inference_devices(None),
1100                norm_bounds=normalization_bounds,
1101            )
1102
1103        UniSAM2InstanceSegmentation.initialize(self, volume, ndim=3, image_embeddings=image_embeddings, **kwargs)
1104        self._image_embeddings = image_embeddings
1105        self._owns_image_embeddings = owns_image_embeddings
1106        self._volume = volume
1107        self._offload_to_cpu = offload_to_cpu
1108        self._max_cached_frames = int(volume.shape[0]) if cache_all_slices else None
1109        self._propagator = self._build_propagator(volume, image_embeddings)
1110
1111    def get_state(self) -> dict:
1112        """Return the decoder predictions and the image embeddings, so that both branches can be restored.
1113
1114        `generate` also prompts the interactive branch, which needs the encoding of the same input. For
1115        a volume the volume itself is part of the state, because the video predictor is initialized on it.
1116        """
1117        state = super().get_state()
1118        state["image_embeddings"] = self._image_embeddings
1119        if self._volume is not None:
1120            state["volume"] = self._volume
1121        return state
1122
1123    def set_state(self, state: dict) -> None:
1124        """Restore the decoder predictions and the encoding of the input they belong to.
1125
1126        The state must hold either 'image_embeddings' or 'image'. Without one, `generate` would prompt
1127        whatever image the predictor still holds. A volumetric state must also hold 'volume'.
1128
1129        Args:
1130            state: The state, as returned by `get_state`, or a dict with 'prediction' and 'image'.
1131        """
1132        image_embeddings = state.get("image_embeddings")
1133        volume = state.get("volume")
1134        i = state.get("i")
1135
1136        if volume is not None:
1137            if image_embeddings is None:
1138                raise ValueError("A volumetric state must hold the 'image_embeddings' of its volume.")
1139            super().set_state(state)
1140            self._volume = volume
1141            self._propagator = self._build_propagator(volume, image_embeddings)
1142            self._i = None
1143        else:
1144            if image_embeddings is None:
1145                if "image" not in state:
1146                    raise ValueError("The state must hold either 'image_embeddings' or 'image'.")
1147                image_embeddings = self._encode(state["image"])
1148            else:
1149                image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1150            super().set_state(state)
1151            self._i = None
1152        self._image_embeddings = image_embeddings
1153        self._owns_image_embeddings = False
1154
1155    def clear_state(self) -> None:
1156        """Clear the decoder predictions and the input that is set on the predictor."""
1157        owned_embeddings = self._image_embeddings if getattr(self, "_owns_image_embeddings", False) else None
1158        super().clear_state()
1159        self._image_embeddings = None
1160        self._i = None
1161        self._owns_image_embeddings = False
1162        self._predictor.reset_predictor()
1163        self._volume = None
1164        # Built on the propagator's replicas, so it must not outlive them.
1165        self._scoring_predictor_pool = None
1166        if self._propagator is not None:
1167            self._propagator.reset_predictor()
1168            self._propagator = None
1169        try:
1170            close = getattr(owned_embeddings, "close", None)
1171            if close is not None:
1172                close()
1173        finally:
1174            if self._temporary_embedding_path is not None:
1175                shutil.rmtree(self._temporary_embedding_path, ignore_errors=True)
1176                self._temporary_embedding_path = None
1177
1178    @torch.no_grad()
1179    def generate(
1180        self,
1181        candidate_threshold: Optional[Union[float, Sequence[float]]] = None,
1182        foreground_threshold: Optional[float] = None,
1183        n_iter: Optional[int] = None,
1184        dt: Optional[float] = None,
1185        sigma: Optional[float] = None,
1186        spacing: Optional[tuple] = None,
1187        min_candidate_size: Optional[int] = None,
1188        score_threshold: Optional[float] = None,
1189        max_overlap: Optional[float] = None,
1190        min_size: Optional[int] = None,
1191        max_size_factor: Optional[float] = DEFAULT_PROMPT_GENERATION["max_size_factor"],
1192        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1193        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1194        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1195        n_objects_per_pass: int = DEFAULT_PROMPT_GENERATION["n_objects_per_pass"],
1196        early_stop_patience: Optional[int] = DEFAULT_PROMPT_GENERATION["early_stop_patience"],
1197        propagation_waves: int = DEFAULT_PROMPT_GENERATION["propagation_waves"],
1198        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1199        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1200        verbose: bool = False,
1201        pbar_init: Optional[Callable] = None,
1202        pbar_update: Optional[Callable] = None,
1203    ) -> np.ndarray:
1204        """Derive prompts from the stored predictions, apply them and merge the masks.
1205
1206        Args:
1207            candidate_threshold: Density threshold for proposing candidates, or several of them for
1208                a volume. By default resolved per model type and dimensionality, see
1209                `default_prompt_generation`.
1210            foreground_threshold: Foreground binarisation threshold. Here it only limits which pixels can
1211                be proposed from, since the masks come from the interactive branch, so it trades candidate
1212                recall rather than boundary quality.
1213            n_iter: Number of flow-integration steps for the candidate density.
1214            dt: Integration step size. Mostly only the product with 'n_iter' matters, which is the
1215                distance a pixel is advected.
1216            sigma: Gaussian sigma for smoothing the candidate density. Less smoothing leaves more peaks,
1217                which costs precision for the sparse post-processing but buys candidate recall here.
1218            spacing: Anisotropic voxel spacing of a volume, e.g. (4, 1, 1).
1219            min_candidate_size: Discard density components smaller than this.
1220            score_threshold: Discard candidates whose predicted IoU is below this.
1221            max_overlap: Reject a candidate when more than this fraction of it is already claimed. For a
1222                volume this applies on the slice a candidate is prompted on and again on the 3d merge.
1223            min_size: Minimum object size in the result.
1224            max_size_factor: Volumes only. Reject a candidate this many times larger than the median
1225                size among the candidates it is merged against, which catches propagation drift (a
1226                track that grows onto background instead of ending). None (the default) applies no
1227                such cap; see `merge_by_score`.
1228            refinement: Optional second round, a '+'-joined combination of 'points' (the first
1229                round's prompts grouped onto each merged instance, see `derive_refinement_prompts`),
1230                'boxes' (its bounding box) and 'masks' (its mask as a logit prompt). None runs no second
1231                round. 'default' (the default) takes the mode of `default_prompt_generation`. For a
1232                volume the round runs on each candidate's anchor slice, before the propagation, and
1233                produces the conditioning that propagation starts from rather than a finished mask,
1234                see `_refine_anchors`.
1235            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1236                components; see `DEFAULT_REFINEMENT`, or `DEFAULT_REFINEMENT_3D` for a volume, for
1237                the accepted keys and their defaults.
1238            multimasking: Whether to predict several masks per point and keep the best scoring one. A
1239                single point is ambiguous between one object and a cluster, so this is on by default.
1240            n_objects_per_pass: Number of objects propagated together through a volume. The video
1241                predictor runs them as one batch, so this trades device memory against the pass count.
1242            propagation_waves: Tiled volumes only. Rounds the candidates are propagated in, highest
1243                scoring first, dropping between rounds those an already-propagated instance covers by
1244                more than 'max_overlap'. One round propagates every candidate, see
1245                `DEFAULT_PROMPT_GENERATION`.
1246            early_stop_patience: Stop a propagation pass after this many consecutive slices in which
1247                every object of the pass is empty. None propagates through the whole volume. Two by
1248                default: propagating past the end of every object of a pass only reproduces empty
1249                masks, so this saves work without changing the result. Raise it where an object may
1250                disappear and reappear, because a stop that fires mid-object truncates it.
1251            batch_size: Number of prompts per forward pass.
1252            n_threads: Number of threads for the flow integration the candidates come from.
1253            verbose: Whether to show progress over the propagation passes of a volume.
1254            pbar_init: Initialize an external progress stage with its total and description.
1255            pbar_update: Advance the external progress bar after completed work.
1256
1257        Returns:
1258            The instance segmentation, uint32 array with the spatial shape of the prediction.
1259        """
1260        if not self._is_initialized:
1261            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1262
1263        self._last_generation_stats = {}
1264        shape = self._prediction[0].shape
1265        # The prediction carries the dimensionality it was run at: (4, Y, X) or (4, Z, Y, X).
1266        is_volume = self._prediction.ndim == 4
1267        defaults = default_prompt_generation(self._model_type, is_volume=is_volume)
1268        if candidate_threshold is None:
1269            candidate_threshold = defaults["candidate_threshold"]
1270        if score_threshold is None:
1271            score_threshold = defaults["score_threshold"]
1272        if max_overlap is None:
1273            max_overlap = defaults["max_overlap"]
1274        if min_size is None:
1275            min_size = defaults["min_size"]
1276        if refinement == "default":
1277            refinement = defaults["refinement"]
1278
1279        if is_volume:
1280            components = resolved = None
1281            if refinement is not None:
1282                components, resolved = _parse_refinement(refinement, refinement_kwargs, is_volume=True)
1283            if pbar_init is not None:
1284                pbar_init(1, "APG: deriving volume prompts")
1285            prompts = derive_volume_prompts(
1286                self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1287                candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1288                n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing,
1289                min_candidate_size=min_candidate_size, n_threads=n_threads,
1290            )
1291            if pbar_update is not None:
1292                pbar_update(1)
1293            if prompts is None:
1294                self._last_generation_stats = {
1295                    "proposed_candidates": 0,
1296                    "scored_candidates": 0,
1297                    "unique_anchor_slices": 0,
1298                    "propagation_passes": 0,
1299                    "propagated_frame_steps": 0,
1300                    "early_stopped_frame_steps": 0,
1301                }
1302                if components is not None:
1303                    self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1304                return np.zeros(shape, dtype="uint32")
1305            self._last_generation_stats["proposed_candidates"] = len(prompts["points"])
1306            if components is not None:
1307                self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1308            # The refinement's forwards are not wrapped by '_apply_prompts', which has its own.
1309            if components is None:
1310                candidates = self._score_candidates(
1311                    prompts, multimasking=multimasking, batch_size=batch_size,
1312                    score_threshold=score_threshold, max_overlap=max_overlap,
1313                    components=components, refinement_kwargs=resolved,
1314                    pbar_init=pbar_init, pbar_update=pbar_update,
1315                )
1316            else:
1317                with autocast(self._predictor.device):
1318                    candidates = self._score_candidates(
1319                        prompts, multimasking=multimasking, batch_size=batch_size,
1320                        score_threshold=score_threshold, max_overlap=max_overlap,
1321                        components=components, refinement_kwargs=resolved,
1322                        pbar_init=pbar_init, pbar_update=pbar_update,
1323                    )
1324            self._last_generation_stats["scored_candidates"] = len(candidates)
1325            records = self._propagate_candidates(
1326                candidates, n_objects_per_pass=n_objects_per_pass,
1327                early_stop_patience=early_stop_patience, verbose=verbose, max_overlap=max_overlap,
1328                propagation_waves=propagation_waves, pbar_init=pbar_init, pbar_update=pbar_update,
1329            )
1330            # Tiled records arrive grouped by tile and need their halo overlaps resolved, which
1331            # '_merge' does polymorphically; an untiled volume merges them flat.
1332            if pbar_init is not None:
1333                pbar_init(1, "APG: merging volume masks")
1334            segmentation, _ = self._merge(
1335                records, shape, score_threshold=score_threshold, max_overlap=max_overlap,
1336                min_size=min_size, max_size_factor=max_size_factor,
1337            )
1338            if pbar_update is not None:
1339                pbar_update(1)
1340            return segmentation
1341
1342        proposals = self.propose(
1343            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1344            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size,
1345            multimasking=multimasking, batch_size=batch_size, n_threads=n_threads,
1346            pbar_init=pbar_init, pbar_update=pbar_update,
1347        )
1348        return self.select(
1349            proposals, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1350            refinement=refinement, refinement_kwargs=refinement_kwargs, batch_size=batch_size,
1351        )
1352
1353    @torch.no_grad()
1354    def propose(
1355        self,
1356        candidate_threshold: Optional[float] = None,
1357        foreground_threshold: Optional[float] = None,
1358        n_iter: Optional[int] = None,
1359        dt: Optional[float] = None,
1360        sigma: Optional[float] = None,
1361        min_candidate_size: Optional[int] = None,
1362        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1363        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1364        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1365        pbar_init: Optional[Callable] = None,
1366        pbar_update: Optional[Callable] = None,
1367    ) -> list:
1368        """Derive the prompts and turn them into scored mask proposals, without selecting any of them.
1369
1370        This is the half of `generate` that needs the model. Splitting it off lets a parameter sweep
1371        reuse one set of proposals across every value of 'score_threshold', 'max_overlap' and
1372        'min_size', which only filter and merge. Images only: a volume gates its propagation on the
1373        score, so its proposals depend on those parameters too.
1374
1375        Args:
1376            candidate_threshold: Density threshold for proposing candidates, see `derive_point_prompts`.
1377            foreground_threshold: Foreground binarisation threshold.
1378            n_iter: Number of flow-integration steps for the candidate density.
1379            dt: Integration step size.
1380            sigma: Gaussian sigma for smoothing the candidate density.
1381            min_candidate_size: Discard density components smaller than this.
1382            multimasking: Whether to predict several masks per point and keep the best scoring one.
1383            batch_size: Number of prompts per forward pass.
1384            n_threads: Number of threads for the flow integration the candidates come from.
1385            pbar_init: Initialize each progress stage with its total and description.
1386            pbar_update: Advance progress after deriving prompts and each prediction batch.
1387
1388        Returns:
1389            The proposals, to be passed to `select`. Their layout is an implementation detail of the
1390            generator that produced them.
1391        """
1392        if not self._is_initialized:
1393            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1394        if self._prediction.ndim == 4:
1395            raise ValueError("Proposals can only be reused for an image, because a volume gates its propagation.")
1396
1397        if pbar_init is not None:
1398            pbar_init(1, "APG: deriving prompts")
1399        prompts = derive_point_prompts(
1400            self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1401            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1402            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size, n_threads=n_threads,
1403        )
1404        if pbar_update is not None:
1405            pbar_update(1)
1406        if prompts is None:
1407            return []
1408        if pbar_init is not None:
1409            pbar_init((len(prompts["points"]) + batch_size - 1) // batch_size, "APG: prompting batches")
1410        return self._apply(
1411            prompts, multimasking=multimasking, batch_size=batch_size, pbar_update=pbar_update,
1412        )
1413
1414    def select(
1415        self,
1416        proposals: list,
1417        score_threshold: Optional[float] = None,
1418        max_overlap: Optional[float] = None,
1419        min_size: Optional[int] = None,
1420        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1421        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1422        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1423    ) -> np.ndarray:
1424        """Merge the proposals of `propose` into an instance segmentation.
1425
1426        Args:
1427            proposals: The proposals, as returned by `propose` on the same generator.
1428            score_threshold: Discard proposals whose predicted IoU is below this.
1429            max_overlap: Reject a proposal when more than this fraction of it is already claimed.
1430            min_size: Minimum object size in the result.
1431            refinement: Optional second round, a '+'-joined combination of 'points', 'boxes',
1432                and 'masks', or 'default' for the mode of `default_prompt_generation`; see `generate`.
1433            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1434                components; see `DEFAULT_REFINEMENT` for the accepted keys and their defaults.
1435            batch_size: Number of prompts per forward pass of the refinement.
1436
1437        Returns:
1438            The instance segmentation, uint32 array with the spatial shape of the prediction.
1439        """
1440        defaults = default_prompt_generation(self._model_type, is_volume=False)
1441        if score_threshold is None:
1442            score_threshold = defaults["score_threshold"]
1443        if max_overlap is None:
1444            max_overlap = defaults["max_overlap"]
1445        if min_size is None:
1446            min_size = defaults["min_size"]
1447        if refinement == "default":
1448            refinement = defaults["refinement"]
1449
1450        components = resolved = None
1451        if refinement is not None:
1452            components, resolved = _parse_refinement(refinement, refinement_kwargs)
1453
1454        shape = self._prediction[0].shape
1455        if not proposals:
1456            return np.zeros(shape, dtype="uint32")
1457
1458        segmentation, context = self._merge(
1459            proposals, shape, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1460            return_context=components is not None,
1461        )
1462        if components is not None and segmentation.max() > 0:
1463            segmentation = self._refine(segmentation, context, components, resolved, batch_size)
1464        return segmentation
1465
1466    def _region_of(self, context: dict, record_index: int):
1467        """The region a record's instance is re-prompted in, keyed however the generator likes.
1468
1469        A refinement runs region by region, because a tiled generator has to point its predictor at
1470        one tile at a time. Here the whole image is one region, so every record shares the key None.
1471        """
1472        return None
1473
1474    def _region_box(self, key) -> tuple:
1475        """The region's bounding box, as a slice tuple into the segmentation."""
1476        return (slice(None), slice(None))
1477
1478    def _set_region(self, key) -> None:
1479        """Point the predictor at the region. Its image is already set for a single one."""
1480
1481    def _apply(self, prompts: dict, multimasking: bool, batch_size: int, pbar_update=None) -> list:
1482        """Turn the prompts into mask proposals."""
1483        return self._apply_prompts(
1484            self._predictor, prompts, multimasking=multimasking, batch_size=batch_size, pbar_update=pbar_update,
1485        )
1486
1487    def _merge(
1488        self, proposals: list, shape: tuple, score_threshold: float, max_overlap: float, min_size: int,
1489        max_size_factor: Optional[float] = None, return_context: bool = False,
1490    ) -> tuple:
1491        """Merge the mask proposals into an instance segmentation.
1492
1493        Returns:
1494            The segmentation, and the refinement context: the score-filtered records and the mapping
1495            from every instance id to the record that made it. Without `return_context` the context
1496            is None, so the matches are not computed for nothing.
1497        """
1498        records = [record for record in proposals if record["predicted_iou"] >= score_threshold]
1499        if not records:
1500            return np.zeros(shape, dtype="uint32"), None
1501        # Images only: a volume's track may leave its object and come back across slices, and that
1502        # merge is not measured with it.
1503        merge_kwargs = {
1504            "max_overlap": max_overlap, "min_size": min_size, "max_size_factor": max_size_factor,
1505            "keep_largest_component": len(shape) == 2,
1506        }
1507        if not return_context:
1508            return merge_by_score(records, shape, **merge_kwargs), None
1509        segmentation, matches, reasons = merge_by_score(
1510            records, shape, return_matches=True, return_reasons=True, **merge_kwargs,
1511        )
1512        self._last_generation_stats.update({
1513            "proposed_candidates": len(proposals),
1514            "scored_candidates": len(records),
1515            "merge_reasons": {reason: reasons.count(reason) for reason in sorted(set(reasons))},
1516        })
1517        return segmentation, {"proposals": proposals, "records": records, "matches": matches}
1518
1519    def _refine(
1520        self, segmentation: np.ndarray, context: dict, components: tuple, refinement_kwargs: dict,
1521        batch_size: int,
1522    ) -> np.ndarray:
1523        """Re-prompt the accepted instances with the requested refinement components."""
1524        with autocast(self._predictor.device):
1525            return self._reprompt_instances(
1526                segmentation, context, components, refinement_kwargs, batch_size,
1527            )
1528
1529    def _reprompt_instances(
1530        self, segmentation: np.ndarray, context: dict, components: tuple, refinement_kwargs: dict,
1531        batch_size: int,
1532    ) -> np.ndarray:
1533        """Predict one second-round mask per instance from the assembled prompts and repaint.
1534
1535        Every requested component contributes to one joint re-prompt per instance, evaluated in
1536        batches. The 'policy' decides what the second round is allowed to do: 'replace' repaints
1537        every instance from its new mask (the most confident painted last, so it wins contested
1538        pixels), 'keep-if-better' keeps the first-round mask unless the new one scores higher. The
1539        geometric gates then veto independently of either policy: a second-round mask that is
1540        inconsistent with the first round ('min_consistency') or grows into a neighbour
1541        ('max_foreign_overlap') is discarded, because the model's own score cannot arbitrate across
1542        prompt types. An instance whose re-prompt comes back empty keeps its first-round mask.
1543
1544        The instances are grouped by the region they are re-prompted in and every region is set up
1545        once, since a tiled generator pays for each switch. Within a region everything runs on its
1546        crop of the segmentation, which is the frame the predictor works in; only the repaint at
1547        the end is global, so the score order arbitrates across regions as well as within them.
1548        """
1549        shape = segmentation.shape
1550        instances = [
1551            (index + 1, bounding_box)
1552            for index, bounding_box in enumerate(find_objects(segmentation))
1553            if bounding_box is not None
1554        ]
1555
1556        point_prompts = None
1557        if "points" in components:
1558            all_points = np.array([record["point"] for record in context["proposals"]], dtype="float32")
1559            surviving_points = {
1560                instance_id: context["records"][record_index]["point"]
1561                for instance_id, record_index in context["matches"].items()
1562            }
1563            point_prompts = derive_refinement_prompts(
1564                segmentation, all_points, surviving_points,
1565                n_positives=refinement_kwargs["n_positives"], n_negatives=refinement_kwargs["n_negatives"],
1566                max_negative_distance=refinement_kwargs["max_negative_distance"],
1567                negative_source=refinement_kwargs["negative_source"],
1568                min_negative_distance=refinement_kwargs["min_negative_distance"],
1569            )
1570
1571        n_negatives_used = 0
1572        if point_prompts is not None:
1573            n_negatives_used = sum(
1574                int(np.count_nonzero(point_prompts[instance_id]["point_labels"] == 0)) for instance_id, _ in instances
1575            )
1576        self._last_generation_stats.update({
1577            "refinement_eligible_instances": len(instances),
1578            "refinement_negatives": n_negatives_used,
1579        })
1580        if not instances:
1581            self._last_generation_stats.update({
1582                "refined_instances": 0, "replaced_instances": 0, "dropped_negatives": 0,
1583                "gated_consistency": 0, "gated_foreign": 0,
1584            })
1585            return segmentation
1586
1587        # Every instance needs the record that made it, for its first-round score.
1588        groups = {}
1589        for instance_id, bounding_box in instances:
1590            if instance_id not in context["matches"]:
1591                raise RuntimeError(
1592                    f"Instance {instance_id} is in the segmentation but not in the merge context. The "
1593                    "refinement cannot score it against its first round."
1594                )
1595            key = self._region_of(context, context["matches"][instance_id])
1596            groups.setdefault(key, []).append((instance_id, bounding_box))
1597
1598        min_consistency = refinement_kwargs["min_consistency"]
1599        max_foreign_overlap = refinement_kwargs["max_foreign_overlap"]
1600        keep_if_better = refinement_kwargs["policy"] == "keep-if-better"
1601        chosen, replaced, dropped = [], 0, 0
1602        gated = {"gated_consistency": 0, "gated_foreign": 0}
1603        for key in sorted(groups):
1604            self._set_region(key)
1605            region_box = self._region_box(key)
1606            crop = segmentation[region_box]
1607            origin = tuple(box.start or 0 for box in region_box)
1608            members = groups[key]
1609
1610            region_prompts = point_prompts
1611            if point_prompts is not None and (any(origin) or crop.shape != shape):
1612                region_prompts = {}
1613                for instance_id, _ in members:
1614                    region_prompts[instance_id], region_dropped = _localize_prompts(
1615                        point_prompts[instance_id], origin, crop.shape
1616                    )
1617                    dropped += region_dropped
1618
1619            def accept(instance_id: int, bounding_box: tuple, mask: np.ndarray, score: float) -> None:
1620                """Decide between the second-round mask and the first round, and queue the repaint."""
1621                nonlocal replaced
1622                record = context["records"][context["matches"][instance_id]]
1623                first_round_score = record["predicted_iou"] * record["stability_score"]
1624                take_second = mask.any() and (not keep_if_better or score > first_round_score)
1625                if take_second and min_consistency is not None:
1626                    first_round_mask = crop == instance_id
1627                    union = int(np.count_nonzero(mask | first_round_mask))
1628                    iou = int(np.count_nonzero(mask & first_round_mask)) / union if union else 0.0
1629                    if iou < min_consistency:
1630                        take_second = False
1631                        gated["gated_consistency"] += 1
1632                if take_second and max_foreign_overlap is not None:
1633                    on_mask = crop[mask]
1634                    foreign = int(np.count_nonzero((on_mask != 0) & (on_mask != instance_id)))
1635                    if foreign / int(mask.sum()) > max_foreign_overlap:
1636                        take_second = False
1637                        gated["gated_foreign"] += 1
1638                if take_second:
1639                    replaced += 1
1640                    rows, columns = np.nonzero(mask)
1641                    box = (
1642                        slice(int(rows.min()), int(rows.max()) + 1), slice(int(columns.min()), int(columns.max()) + 1)
1643                    )
1644                    chosen.append((score, instance_id, _shift_box(box, origin), mask[box]))
1645                else:
1646                    chosen.append((
1647                        first_round_score, instance_id, _shift_box(bounding_box, origin),
1648                        crop[bounding_box] == instance_id,
1649                    ))
1650
1651            region_instances = [
1652                (instance_id, _shift_box(bounding_box, tuple(-shift for shift in origin)))
1653                for instance_id, bounding_box in members
1654            ]
1655            for start in range(0, len(region_instances), batch_size):
1656                batch = region_instances[start:start + batch_size]
1657                predictions = self._predict_refinement_batch(
1658                    crop, batch, components, region_prompts, refinement_kwargs,
1659                )
1660                for (instance_id, bounding_box), (mask, score) in zip(batch, predictions):
1661                    accept(instance_id, bounding_box, mask, score)
1662
1663        self._last_generation_stats.update({
1664            "refined_instances": len(instances), "replaced_instances": replaced, "dropped_negatives": dropped, **gated,
1665        })
1666        # Ascending score, so that the most confident instance is painted last and wins contested pixels.
1667        refined = np.zeros(shape, dtype="uint32")
1668        for score, instance_id, bounding_box, mask in sorted(chosen, key=lambda entry: (entry[0], entry[1])):
1669            refined[bounding_box][mask] = instance_id
1670        return refined
1671
1672    def _predict_refinement_batch(
1673        self, segmentation: np.ndarray, batch: list, components: tuple,
1674        point_prompts: Optional[dict], refinement_kwargs: dict,
1675    ) -> list:
1676        """Return one (mask, combined score) pair per instance in ``batch``."""
1677        shape = segmentation.shape
1678        box_extension = refinement_kwargs.get("box_extension", 0)
1679        points = labels = boxes = mask_logits = None
1680
1681        if "points" in components:
1682            per_instance = [point_prompts[instance_id] for instance_id, _ in batch]
1683            width = max(len(prompt["points"]) for prompt in per_instance)
1684            points = np.zeros((len(batch), width, 2), dtype="float32")
1685            labels = np.full((len(batch), width), -1, dtype="int32")
1686            for row, prompt in enumerate(per_instance):
1687                points[row, :len(prompt["points"])] = prompt["points"]
1688                labels[row, :len(prompt["points"])] = prompt["point_labels"]
1689        if "boxes" in components:
1690            boxes = np.array([
1691                _prompt_box(bounding_box, shape, box_extension) for _, bounding_box in batch
1692            ], dtype="float32")
1693        if "masks" in components:
1694            mask_logits = np.stack([mask_to_logits(segmentation == instance_id) for instance_id, _ in batch])
1695
1696        return self._predict_prompt_batch(
1697            points, labels, boxes, mask_logits, refinement_kwargs["multimasking"],
1698        )
1699
1700    def _predict_prompt_batch(
1701        self,
1702        points: Optional[np.ndarray],
1703        labels: Optional[np.ndarray],
1704        boxes: Optional[np.ndarray],
1705        mask_logits: Optional[np.ndarray],
1706        multimasking: bool,
1707    ) -> list:
1708        """One batched forward pass over assembled prompts, returning (mask, combined score) pairs.
1709
1710        The point counts may differ between the batch's prompts, so the coordinate arrays are padded
1711        to the longest with the label -1, which the SAM2 prompt encoder treats as 'not a point'.
1712        """
1713        n_prompts = len(points) if points is not None else len(boxes if boxes is not None else mask_logits)
1714        mask_input, coords, point_labels, box_input = self._predictor._prep_prompts(
1715            points, labels, boxes, mask_logits, True,
1716        )
1717        logits, scores, _ = self._predictor._predict(
1718            coords, point_labels, box_input, mask_input, multimasking, return_logits=True,
1719        )
1720        logits = logits.reshape(n_prompts, -1, *logits.shape[-2:])
1721        scores = scores.reshape(n_prompts, -1)
1722        index = torch.arange(n_prompts, device=scores.device)
1723        best = scores.argmax(dim=1)
1724        logits, scores = logits[index, best], scores[index, best]
1725
1726        mask_threshold = getattr(self._predictor, "mask_threshold", 0.0)
1727        stability = calculate_stability_score(logits, mask_threshold, STABILITY_SCORE_OFFSET)
1728        masks = (logits > mask_threshold).cpu().numpy()
1729        combined = (scores.float() * stability.float()).cpu().numpy()
1730        return [(mask, float(score)) for mask, score in zip(masks, combined)]
1731
1732    def _apply_prompts(
1733        self, predictor, prompts, multimasking: bool, batch_size: int, pbar_update=None,
1734    ) -> List[Dict[str, Any]]:
1735        """Prompt the interactive branch in batches, returning records for the merge.
1736
1737        Takes the predictor rather than reading `self._predictor`, so the volumetric scoring can hand
1738        every worker the replica on its own device.
1739        """
1740        points, point_labels = prompts["points"], prompts["point_labels"]
1741        mask_threshold = getattr(predictor, "mask_threshold", 0.0)
1742
1743        records = []
1744        for start in range(0, len(points), batch_size):
1745            stop = start + batch_size
1746            batch_points, batch_labels = points[start:stop], point_labels[start:stop]
1747            n_prompts = len(batch_points)
1748            # Reduced on the device, so only the kept mask is transferred rather than every proposal.
1749            mask_input, coords, labels, _ = predictor._prep_prompts(batch_points, batch_labels, None, None, True)
1750            with autocast(predictor.device):
1751                logits, scores, _ = predictor._predict(
1752                    coords, labels, None, mask_input, multimasking, return_logits=True,
1753                )
1754            logits = logits.reshape(n_prompts, -1, *logits.shape[-2:])
1755            scores = scores.reshape(n_prompts, -1)
1756            index = torch.arange(n_prompts, device=scores.device)
1757            best = scores.argmax(dim=1)
1758            logits, scores = logits[index, best], scores[index, best]
1759
1760            stability = calculate_stability_score(logits, mask_threshold, STABILITY_SCORE_OFFSET)
1761            binary = logits > mask_threshold
1762            # Two reductions on the device: an np.nonzero per mask costs more than the rest of the loop.
1763            rows_any = binary.any(dim=2).cpu().numpy()
1764            columns_any = binary.any(dim=1).cpu().numpy()
1765            masks = binary.cpu().numpy()
1766            scores = scores.float().cpu().numpy()
1767            stability = stability.float().cpu().numpy()
1768            for offset, (mask, row_any, column_any, score, stable) in enumerate(
1769                zip(masks, rows_any, columns_any, scores, stability)
1770            ):
1771                if not row_any.any():
1772                    continue
1773                y0, y1 = int(row_any.argmax()), len(row_any) - int(row_any[::-1].argmax())
1774                x0, x1 = int(column_any.argmax()), len(column_any) - int(column_any[::-1].argmax())
1775                records.append({
1776                    # The crop rather than the full mask: the merge is linear in the mask's size.
1777                    "segmentation": mask[y0:y1, x0:x1].copy(),
1778                    "bounding_box": (slice(y0, y1), slice(x0, x1)),
1779                    "predicted_iou": float(score),
1780                    "stability_score": float(stable),
1781                    # Empty masks are dropped, so the record order does not track the prompts.
1782                    "prompt_index": start + offset,
1783                    # The prompt as (x, y); the refinement groups the first round's prompts by it.
1784                    "point": (float(batch_points[offset, 0, 0]), float(batch_points[offset, 0, 1])),
1785                })
1786            if pbar_update is not None:
1787                pbar_update(1)
1788        return records
1789
1790    def _score_candidates(
1791        self, prompts: dict, multimasking: bool, batch_size: int, score_threshold: float,
1792        max_overlap: float, components: Optional[tuple] = None, refinement_kwargs: Optional[dict] = None,
1793        pbar_init=None, pbar_update=None,
1794    ) -> List[dict]:
1795        """Prompt every candidate in 2d on its anchor slice, and keep the strong, non-duplicate ones.
1796
1797        This runs before the propagation, which is where the cost is: a candidate the model scores
1798        poorly, or that a better-scoring one already covers on that slice, is never propagated. It
1799        also gives every surviving candidate the predicted IoU that orders the volumetric merge.
1800
1801        A refinement runs here too, slice by slice, while the predictor is still pointed at that
1802        slice: re-reading a slice's features costs more than the re-prompt itself does.
1803
1804        Args:
1805            prompts: The volumetric prompts, as `derive_volume_prompts` returns them.
1806            multimasking: Whether to predict several masks per point and keep the best scoring one.
1807            batch_size: Number of prompts per forward pass.
1808            score_threshold: Discard candidates whose predicted IoU is below this.
1809            max_overlap: Reject a candidate when more than this fraction of it is already claimed.
1810            components: The refinement components, or None to run no second round.
1811            refinement_kwargs: The resolved refinement keyword arguments.
1812
1813        Returns:
1814            The surviving candidates, each with the prompt it will be propagated with and its global
1815            'prompt_index' into the prompts.
1816        """
1817        points, point_labels, frames = prompts["points"], prompts["point_labels"], prompts["frames"]
1818        slice_shape = self._prediction[0].shape[-2:]
1819        min_size = default_prompt_generation(self._model_type, is_volume=False)["min_size"]
1820        # A refinement round re-prompts through 'self._predictor', so those slices keep to it and to
1821        # this process. Without one a slice is scored independently and the slices spread over the
1822        # devices, each worker prompting the replica on its own.
1823        refining = components is not None
1824        devices = [self._predictor.device] if refining else self._scoring_devices()
1825
1826        def score_frame(worker_id, frame):
1827            predictor = self._predictor if refining else self._scoring_predictors()[worker_id]
1828            indices = np.where(frames == frame)[0]
1829            # Reads the slice's features out of the volume's embeddings, so nothing is re-encoded.
1830            _set_image_predictor_from_3d_embeddings(predictor, self._image_embeddings, int(frame))
1831            frame_prompts = {"points": points[indices], "point_labels": point_labels[indices]}
1832            records = self._apply_prompts(
1833                predictor, frame_prompts, multimasking=multimasking, batch_size=batch_size,
1834            )
1835            records = [record for record in records if record["predicted_iou"] >= score_threshold]
1836            if not records:
1837                return []
1838
1839            def finish(candidate, record):
1840                candidate["prompt_index"] = int(indices[int(record["prompt_index"])])
1841                return candidate
1842
1843            if not refining:
1844                _, kept = merge_by_score(
1845                    records, _records_shape(records), max_overlap=max_overlap,
1846                    min_size=min_size, return_matches=True,
1847                )
1848                return [
1849                    finish(self._anchor_candidate(int(frame), records[record_index]), records[record_index])
1850                    for record_index in kept.values()
1851                ]
1852
1853            # On the slice's own canvas rather than the records' bounding one, because a refinement
1854            # looks instance ids up by position: for the foreign-overlap gate and for the negatives.
1855            segmentation, matches = merge_by_score(
1856                records, slice_shape, max_overlap=max_overlap,
1857                min_size=min_size,
1858                return_matches=True,
1859            )
1860            context = {
1861                "frame": int(frame), "segmentation": segmentation, "records": records,
1862                "matches": matches, "points": points[indices][:, 0, :],
1863            }
1864            with autocast(predictor.device):
1865                refined = self._refine_anchors(context, components, refinement_kwargs, batch_size)
1866            return [
1867                finish(candidate, records[record_index])
1868                for candidate, record_index in zip(refined, matches.values())
1869            ]
1870
1871        anchor_frames = np.unique(frames)
1872        if pbar_init is not None:
1873            pbar_init(len(anchor_frames), "APG: scoring anchor slices")
1874        per_frame = _run_with_progress(
1875            lambda update: map_jobs_over_devices(devices, anchor_frames, score_frame, update_progress=update),
1876            pbar_update,
1877        )
1878        return [candidate for frame_candidates in per_frame for candidate in frame_candidates]
1879
1880    def _scoring_predictors(self) -> list:
1881        """One image predictor per inference device, built on the video predictor's own replicas.
1882
1883        The volumetric scoring reads one slice's features per job and prompts the interactive branch
1884        with them, which is independent per job, so the jobs spread over the devices exactly like the
1885        propagation. Built lazily and only once, because a replica is a full model.
1886        """
1887        if self._propagator is None:
1888            return [self._predictor]
1889        if self._scoring_predictor_pool is None:
1890            self._scoring_predictor_pool = [
1891                get_sam2_image_predictor(predictor) for predictor, _ in self._propagator.predictor_devices
1892            ]
1893        return self._scoring_predictor_pool
1894
1895    def _scoring_devices(self) -> list:
1896        """The devices the volumetric scoring spreads its jobs over, or the one it has."""
1897        if self._propagator is None:
1898            return [self._predictor.device]
1899        return [device for _, device in self._propagator.predictor_devices]
1900
1901    def _anchor_candidate(self, frame: int, record: dict) -> dict:
1902        """One propagation candidate: the prompt that made the anchor mask, and the merge's score."""
1903        return {
1904            "frame": int(frame),
1905            "point": record["point"],
1906            "score": record["predicted_iou"],
1907            "stability": record["stability_score"],
1908            # The mask on the anchor slice, which the pruning between propagation rounds measures
1909            # the claimed overlap of.
1910            "mask": record["segmentation"],
1911            "mask_box": record["bounding_box"],
1912        }
1913
1914    def _refine_anchors(
1915        self, context: dict, components: tuple, refinement_kwargs: dict, batch_size: int,
1916    ) -> List[dict]:
1917        """Re-prompt every scored candidate of one anchor slice, and return what to propagate.
1918
1919        The volumetric counterpart of `_reprompt_instances`, and the only place a volume can refine
1920        at all: a prompt on an already propagated slice would turn it into a conditioning frame and
1921        replace the mask there with a single-point one. So the second round runs on the anchor slice,
1922        before the propagation, and what it produces is not a mask - the propagation still makes that
1923        - but the conditioning the propagation starts from and the score that orders the 3d merge.
1924
1925        The prompts, the batched forward and both gates are the 2d ones, applied in-plane on the
1926        anchor slice: `derive_refinement_prompts` groups that slice's suppressed prompts onto their
1927        candidate and takes the neighbouring ones as negatives, 'min_consistency' keeps a re-prompt
1928        from reshaping the anchor rather than polishing it, and 'max_foreign_overlap' keeps it out of
1929        a neighbour. A candidate whose re-prompt comes back empty or gated keeps its first round.
1930
1931        Returns:
1932            The slice's candidates in first-round score order. An accepted re-prompt carries its
1933            conditioning under 'conditioning'; a rejected one has no such key and is propagated from
1934            its first-round point, exactly as without a refinement.
1935        """
1936        segmentation, records = context["segmentation"], context["records"]
1937        frame, frame_points = context["frame"], context["points"]
1938        candidates = {
1939            instance_id: self._anchor_candidate(frame, records[record_index])
1940            for instance_id, record_index in context["matches"].items()
1941        }
1942
1943        point_prompts = None
1944        if "points" in components:
1945            point_prompts = derive_refinement_prompts(
1946                segmentation, frame_points,
1947                {instance_id: candidate["point"] for instance_id, candidate in candidates.items()},
1948                n_positives=refinement_kwargs["n_positives"],
1949                n_negatives=refinement_kwargs["n_negatives"],
1950                max_negative_distance=refinement_kwargs["max_negative_distance"],
1951                negative_source=refinement_kwargs["negative_source"],
1952                min_negative_distance=refinement_kwargs["min_negative_distance"],
1953            )
1954
1955        boxes = {
1956            index + 1: bounding_box
1957            for index, bounding_box in enumerate(find_objects(segmentation))
1958            if bounding_box is not None
1959        }
1960        instances = [(instance_id, boxes[instance_id]) for instance_id in candidates]
1961        min_consistency = refinement_kwargs["min_consistency"]
1962        max_foreign_overlap = refinement_kwargs["max_foreign_overlap"]
1963        keep_if_better = refinement_kwargs["policy"] == "keep-if-better"
1964        stats = self._last_generation_stats
1965        stats["refined_candidates"] += len(instances)
1966        if point_prompts is not None:
1967            # A volume takes negatives only from the candidates on the same slice, so it reports how many it got.
1968            stats["refinement_negatives"] += sum(
1969                int(np.count_nonzero(point_prompts[instance_id]["point_labels"] == 0))
1970                for instance_id, _ in instances
1971            )
1972
1973        for start in range(0, len(instances), batch_size):
1974            batch = instances[start:start + batch_size]
1975            predictions = self._predict_refinement_batch(
1976                segmentation, batch, components, point_prompts, refinement_kwargs,
1977            )
1978            for (instance_id, bounding_box), (mask, score) in zip(batch, predictions):
1979                candidate = candidates[instance_id]
1980                first_round_score = candidate["score"] * candidate["stability"]
1981                take_second = mask.any() and (not keep_if_better or score > first_round_score)
1982                if take_second and min_consistency is not None:
1983                    first_round_mask = segmentation == instance_id
1984                    union = int(np.count_nonzero(mask | first_round_mask))
1985                    iou = int(np.count_nonzero(mask & first_round_mask)) / union if union else 0.0
1986                    if iou < min_consistency:
1987                        take_second = False
1988                        stats["gated_consistency"] += 1
1989                if take_second and max_foreign_overlap is not None:
1990                    on_mask = segmentation[mask]
1991                    foreign = int(np.count_nonzero((on_mask != 0) & (on_mask != instance_id)))
1992                    if foreign / int(mask.sum()) > max_foreign_overlap:
1993                        take_second = False
1994                        stats["gated_foreign"] += 1
1995                if not take_second:
1996                    continue
1997                stats["replaced_candidates"] += 1
1998                # The merge only reads the product of the two, and the second round reports it as one
1999                # combined score, so it goes in whole rather than being split back up arbitrarily.
2000                candidate["score"], candidate["stability"] = float(score), 1.0
2001                candidate["conditioning"] = self._anchor_conditioning(
2002                    mask, bounding_box, segmentation.shape, components,
2003                    point_prompts, instance_id, refinement_kwargs,
2004                )
2005        return list(candidates.values())
2006
2007    def _anchor_conditioning(
2008        self, mask: np.ndarray, bounding_box: tuple, shape: tuple, components: tuple,
2009        point_prompts: Optional[dict], instance_id: int, refinement_kwargs: dict,
2010    ) -> dict:
2011        """What the propagation conditions the anchor frame on, once a second round is accepted.
2012
2013        'conditioning="mask"' hands the video predictor the refined mask, so the anchor frame is
2014        exactly the mask the gates accepted, but its decoder never sees the prompt that produced it.
2015        'prompts' pushes that prompt instead - the same box and points the second round used - and
2016        lets the decoder rebuild the mask, which is what the interactive branch does everywhere else.
2017        """
2018        if refinement_kwargs["conditioning"] == "mask":
2019            return {"mask": mask}
2020        conditioning = {"mode": refinement_kwargs["conditioning"]}
2021        if "boxes" in components:
2022            conditioning["box"] = _prompt_box(bounding_box, shape, refinement_kwargs["box_extension"])
2023        if "points" in components:
2024            conditioning["points"] = point_prompts[instance_id]["points"]
2025            conditioning["point_labels"] = point_prompts[instance_id]["point_labels"]
2026        return conditioning
2027
2028    def _propagate_candidates(
2029        self, candidates: List[dict], n_objects_per_pass: int, early_stop_patience: Optional[int],
2030        verbose: bool, max_overlap: float, propagation_waves: int = 1,
2031        pbar_init=None, pbar_update=None,
2032    ) -> List[Dict[str, Any]]:
2033        """Turn every candidate into a volumetric mask by propagating its prompts through the volume.
2034
2035        Every object of a pass is anchored on the same slice, because the video predictor propagates
2036        them together from the earliest slice any of them is conditioned on: an object anchored later
2037        than that would be tracked before it is conditioned, and never propagated backwards at all.
2038        """
2039        def run_pass(propagator, batch):
2040            # Only the objects: re-reading the volume's features each pass costs more than the propagation.
2041            propagator.reset_tracking()
2042            for object_id, candidate in enumerate(batch, start=1):
2043                self._condition_pass(candidate, object_id, propagator)
2044            video_segments = propagator.propagate_prompts(early_stop_patience=early_stop_patience)
2045            return _volume_records(video_segments, batch, self._volume.shape[:3]), len(video_segments)
2046
2047        claims: Dict[Any, np.ndarray] = {}
2048        records, anchors = [], set()
2049        n_passes = propagated_frame_steps = n_propagated = 0
2050        waves = self._candidate_waves(candidates, propagation_waves)
2051        for wave_index, wave in enumerate(waves):
2052            wave = [candidate for candidate in wave if not self._is_claimed(claims, candidate, max_overlap)]
2053            n_propagated += len(wave)
2054            by_anchor: Dict[int, List[dict]] = {}
2055            for candidate in wave:
2056                by_anchor.setdefault(candidate["frame"], []).append(candidate)
2057            passes = [
2058                group[start:start + n_objects_per_pass]
2059                for _, group in sorted(by_anchor.items())
2060                for start in range(0, len(group), n_objects_per_pass)
2061            ]
2062            if not passes:
2063                continue
2064            anchors.update(by_anchor)
2065            n_passes += len(passes)
2066
2067            # The passes share nothing but the volume, so each goes to whichever device is free.
2068            if pbar_init is not None:
2069                pbar_init(len(passes), f"APG: propagation passes (wave {wave_index + 1}/{len(waves)})")
2070            with tqdm(total=len(passes), desc="Propagate prompts", disable=not verbose) as progress:
2071                if pbar_update is None:
2072                    per_pass = self._propagator.map_passes(passes, run_pass, update_progress=progress.update)
2073                else:
2074                    per_pass = _run_with_progress(
2075                        lambda update: self._propagator.map_passes(passes, run_pass, update_progress=update),
2076                        pbar_update,
2077                    )
2078
2079            for pass_records, steps in per_pass:
2080                records.extend(pass_records)
2081                propagated_frame_steps += steps
2082                if wave_index + 1 < len(waves):
2083                    self._claim_records(claims, None, pass_records)
2084
2085        possible_frame_steps = n_passes * int(self._volume.shape[0])
2086        self._last_generation_stats.update({
2087            "unique_anchor_slices": len(anchors),
2088            "propagation_passes": n_passes,
2089            "propagated_candidates": n_propagated,
2090            "pruned_candidates": len(candidates) - n_propagated,
2091            "propagated_frame_steps": propagated_frame_steps,
2092            "early_stopped_frame_steps": possible_frame_steps - propagated_frame_steps,
2093        })
2094        self._propagator.reset_predictor()
2095        return records
2096
2097    def _claim_key(self, candidate: dict):
2098        """The region a candidate's masks are expressed in. An untiled volume is a single region."""
2099        return None
2100
2101    def _claim_shape(self, key) -> tuple:
2102        """The shape of that region's claim volume, which the record bounding boxes index into."""
2103        return tuple(int(side) for side in self._volume.shape[:3])
2104
2105    def _candidate_waves(self, candidates: List[dict], propagation_waves: int) -> List[List[dict]]:
2106        """The candidates in descending merge score, cut into the rounds they are propagated in.
2107
2108        Descending, because that is the order the merge resolves them in: an instance a later
2109        candidate would duplicate has already been propagated by the time that candidate is reached.
2110        """
2111        if not candidates:
2112            return []
2113        if propagation_waves <= 1:
2114            return [list(candidates)]
2115        order = sorted(candidates, key=lambda candidate: -(candidate["score"] * candidate["stability"]))
2116        size = -(-len(order) // propagation_waves)
2117        return [order[start:start + size] for start in range(0, len(order), size)]
2118
2119    def _region_claim(self, claims: Dict[Any, np.ndarray], key) -> np.ndarray:
2120        """The voxels of one region that an already-propagated instance covers, made on first use."""
2121        if key not in claims:
2122            claims[key] = np.zeros(self._claim_shape(key), dtype=bool)
2123        return claims[key]
2124
2125    def _claim_records(self, claims: Dict[Any, np.ndarray], key, records: List[dict]) -> None:
2126        """Record the voxels a round's masks cover, in the frame the records are expressed in."""
2127        if not records:
2128            return
2129        claim = self._region_claim(claims, key)
2130        for record in records:
2131            claim[record["bounding_box"]] |= record["segmentation"]
2132
2133    def _is_claimed(self, claims: Dict[Any, np.ndarray], candidate: dict, max_overlap: float) -> bool:
2134        """Whether earlier rounds already claim enough of this candidate to make it a duplicate.
2135
2136        The merge rejects a candidate when a better-scoring mask claims more than 'max_overlap' of
2137        it. This applies that same rule to the candidate's anchor-slice mask rather than to the
2138        volumetric mask it has not been propagated into yet, so it predicts the rejection instead of
2139        being it. Testing the anchor point instead measures less and prunes less: 597 candidates
2140        against 1222 on one gonuclear crop, for the same score.
2141
2142        Where instances tile space rather than sit apart in background this misfires, because an
2143        abutting neighbour then claims a real share of the candidate. Measured on cremi it costs
2144        0.03 CREMI score, which is why the default is one round, see 'propagation_waves'.
2145        """
2146        if self._is_protected_from_pruning(candidate):
2147            return False
2148        claim = claims.get(self._claim_key(candidate))
2149        if claim is None:
2150            return False
2151        mask = candidate["mask"]
2152        area = int(mask.sum())
2153        if area == 0:
2154            return False
2155        claimed = np.logical_and(claim[(candidate["frame"],) + tuple(candidate["mask_box"])], mask).sum()
2156        return bool(claimed > max_overlap * area)
2157
2158    def _is_protected_from_pruning(self, candidate: dict) -> bool:
2159        """Whether a candidate's anchor frame or mask reaches into the halo margin, if one is set.
2160
2161        '_pruning_protected_margin' is None outside 'TiledAutomaticPromptGenerator', so this is
2162        always False there and pruning behaves exactly as it did before this option existed. A tile
2163        or block sets it to its own halo before propagating: a candidate this close to the block's
2164        outer edge is exactly the kind of prediction the halo-overlap multicut compares against the
2165        neighbouring tile/block, so dropping it as a within-tile duplicate could discard the one
2166        candidate that seam needed, even though it looked safe to prune from this tile alone.
2167        """
2168        margin = getattr(self, "_pruning_protected_margin", None)
2169        if margin is None:
2170            return False
2171        z_margin, y_margin, x_margin = margin
2172        frame = candidate["frame"]
2173        y_box, x_box = candidate["mask_box"]
2174        depth, height, width = self._volume.shape[:3]
2175        return (
2176            frame < z_margin or frame >= depth - z_margin
2177            or y_box.start < y_margin or y_box.stop > height - y_margin
2178            or x_box.start < x_margin or x_box.stop > width - x_margin
2179        )
2180
2181    def _condition_pass(self, candidate: dict, object_id: int, propagator) -> None:
2182        """Push one candidate's conditioning onto the propagator, as the object with this id.
2183
2184        Without a refinement a candidate is conditioned on the single point the decoder proposed it
2185        at. A refined one carries either the mask its second round produced, which conditions the
2186        anchor frame directly, or that round's box and points - in as many pushes as its
2187        'conditioning' asks for, because a push is a decoder step on the anchor frame rather than
2188        bookkeeping, and more of them refine the anchor further. See `DEFAULT_REFINEMENT_3D`.
2189        """
2190        frame = candidate["frame"]
2191        conditioning = candidate.get("conditioning")
2192        if conditioning is None:
2193            x, y = candidate["point"]
2194            propagator.add_point_prompts(
2195                frame_ids=frame,
2196                points=np.array([[y, x]], dtype="float32"),  # The propagator takes YX.
2197                point_labels=np.array([1], dtype="int32"),
2198                object_id=object_id,
2199            )
2200            return
2201
2202        mask = conditioning.get("mask")
2203        if mask is not None:
2204            # Already refined against this slice, so the propagator must not refine it a second time.
2205            propagator.add_mask_prompts(
2206                frame_ids=frame, masks=[mask], object_id=object_id, refine=False,
2207            )
2208            return
2209
2210        # Every producer of a conditioning dict sets this; a missing one is a bug in the producer,
2211        # so it raises rather than silently picking a strategy.
2212        mode = conditioning["mode"]
2213        box = conditioning.get("box")
2214        points = conditioning.get("points")
2215        # The propagator takes YX for both.
2216        points_yx = None if points is None else np.asarray(points, dtype="float32")[:, ::-1]
2217        labels = conditioning.get("point_labels")
2218        box_yx = None if box is None else np.array([box[1], box[0], box[3], box[2]], dtype="float32")
2219
2220        if mode == "prompts-joint":
2221            propagator.add_prompt_set(
2222                frame_id=frame, points=points_yx, point_labels=labels, box=box_yx,
2223                object_id=object_id,
2224            )
2225            return
2226
2227        # A box has to come first, and it clears whatever the object carried on the frame.
2228        if box_yx is not None:
2229            propagator.add_box_prompts(
2230                frame_ids=frame, boxes=[box_yx], object_id=object_id,
2231            )
2232        if points_yx is None or not len(points_yx):
2233            return
2234        if mode == "prompts-grouped":
2235            propagator.add_prompt_set(
2236                frame_id=frame, points=points_yx, point_labels=labels, object_id=object_id,
2237                # Appends to the box rather than replacing it.
2238                clear_old_points=box_yx is None,
2239            )
2240            return
2241        propagator.add_point_prompts(
2242            frame_ids=frame, points=points_yx,
2243            point_labels=np.asarray(labels, dtype="int32"), object_id=object_id,
2244        )

Generates an instance segmentation automatically, from prompts derived from the UniSAM2 decoder.

Used in the same way as UniSAM2InstanceSegmentation, and the counterpart of micro_sam.v1.instance_segmentation.AutomaticPromptGenerator:

segmenter = AutomaticPromptGenerator(model, predictor)
segmenter.initialize(image, ndim=2)  # Encode the image, then run the decoder on the encoding.
masks = segmenter.generate(score_threshold=0.6)  # Prompt, then merge the masks.

Volumes are segmented by passing the SAM2 video predictor instead of an image predictor:

segmenter = AutomaticPromptGenerator(model, video_predictor)
segmenter.initialize(volume, ndim=3)
masks = segmenter.generate()  # Prompt one slice per object, propagate, then merge the masks.

The decoder finds the objects and the interactive branch segments them either way. What differs is that an object's mask comes from propagating one prompt through the volume rather than from a single forward pass, and that the candidates are scored in 2d on the slice they are prompted on, which drops the weak and the duplicate ones before the propagation - which is where the cost is. The decoder and the video predictor read the same 3d embeddings, so the volume is encoded once.

Arguments:
  • model: The UniSAM2 model (see get_unisam2_model / get_decoder).
  • predictor: The SAM2 image predictor for the interactive branch of the same model, or its video predictor, which is what a volume is prompted with.
  • 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.
AutomaticPromptGenerator( model: torch.nn.modules.module.Module, predictor, device: Union[str, torch.device, NoneType] = None, inference_device: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = <object object>)
933    def __init__(
934        self,
935        model: torch.nn.Module,
936        predictor,
937        device: Optional[Union[str, torch.device]] = None,
938        inference_device: Devices = USE_MODEL_DEVICE,
939    ) -> None:
940        super().__init__(model, device=device, inference_device=inference_device)
941        self._video_predictor = predictor if hasattr(predictor, "propagate_in_video") else None
942        if self._video_predictor is None:
943            self._predictor = configure_image_predictor(predictor)
944        else:
945            # Build the image predictor on the video predictor's weights.
946            self._predictor = get_sam2_image_predictor(predictor)
947        predictor = self._predictor
948
949        self._image_embeddings = None
950        self._volume = None
951        self._propagator = None
952        self._offload_to_cpu = None
953        self._max_cached_frames = None
954        self._temporary_embedding_path = None
955        self._i = None
956        self._owns_image_embeddings = False
957        self._last_generation_stats = {}
958        # Set by 'TiledAutomaticPromptGenerator' to this block's full spatial halo before propagating,
959        # so pruning never drops a candidate the halo-overlap multicut might need; None elsewhere.
960        self._pruning_protected_margin: Optional[tuple] = None
961        self._scoring_predictor_pool = None
962        # The embedding cache is keyed on these, which a SAM2 image predictor does not carry itself.
963        sam2_model = getattr(predictor, "model", None)
964        if getattr(predictor, "model_type", None) is None:
965            predictor.model_type = getattr(sam2_model, "model_type", None) or "hvit"
966        if getattr(predictor, "model_name", None) is None:
967            predictor.model_name = getattr(sam2_model, "model_name", None) or predictor.model_type
def initialize( self, image: numpy.ndarray, ndim: int = 2, image_embeddings: Optional[dict] = None, i: Optional[int] = None, save_path: Optional[str] = None, verbose: bool = False, offload_to_cpu: Optional[bool] = None, cache_all_slices: bool = False, lazy_embeddings: bool = True, normalization_bounds: Optional[tuple] = None, **kwargs) -> None:
 997    def initialize(
 998        self,
 999        image: np.ndarray,
1000        ndim: int = 2,
1001        image_embeddings: Optional[dict] = None,
1002        i: Optional[int] = None,
1003        save_path: Optional[str] = None,
1004        verbose: bool = False,
1005        offload_to_cpu: Optional[bool] = None,
1006        cache_all_slices: bool = False,
1007        lazy_embeddings: bool = True,
1008        normalization_bounds: Optional[tuple] = None,
1009        **kwargs,
1010    ) -> None:
1011        """Encode the input, run the decoder on that encoding and leave the predictor ready to be prompted.
1012
1013        Both branches of a joint checkpoint share their image encoder weights, so one pass serves both
1014        and `generate` can be called repeatedly without any further encoding.
1015
1016        Args:
1017            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
1018            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
1019            image_embeddings: Optional precomputed image embeddings. If given, the encoder does not run.
1020            i: The slice index for video-style embeddings. By default the embeddings contain one image.
1021            save_path: Optional path to cache the embeddings of a volume in a zarr container. Without
1022                one an ephemeral store is used, which `clear_state` removes.
1023            verbose: Whether to print progress while the embeddings of a volume are computed.
1024            offload_to_cpu: Whether a volume's tracking state is held on the host rather than on the
1025                device. False propagates the same masks 6-11% faster, for the memory of one pass of
1026                objects across the volume, which is about 17 MB per slice at the default pass size.
1027                None leaves the choice to `PromptableSegmentation3D`, which offloads on cuda.
1028            cache_all_slices: Whether every slice's features stay on the device while a volume is
1029                propagated. A pass walks the whole volume, so a cache shorter than it is never hit
1030                and every slice is fetched again on every pass - which is most of the run on a deep
1031                volume. Costs about 90 MB of device memory per slice.
1032            lazy_embeddings: Whether a volume's embeddings are read from their store slice by slice.
1033                False holds them in host memory instead, which makes the fetch above much cheaper
1034                without spending device memory.
1035            normalization_bounds: Volumes only. Precomputed (lower, upper) percentile bounds (see
1036                `batched_inference._volume_normalization_bounds`), normally computed from `image`
1037                itself. Pass this when `image` is only a tile/block of a larger volume, so it shares
1038                that volume's bounds instead of estimating its own from its own, smaller, biased crop
1039                (see `TiledAutomaticPromptGenerator.generate`).
1040            kwargs: Additional arguments for `UniSAM2InstanceSegmentation.initialize`.
1041        """
1042        if ndim not in (2, 3):
1043            raise ValueError(f"Automatic prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
1044
1045        # A volume leaves a propagator and possibly a temporary embedding store behind. Release both
1046        # before replacing its state, including when the next input is a 2d image.
1047        if self._volume is not None or self._temporary_embedding_path is not None:
1048            self.clear_state()
1049
1050        if ndim == 3:
1051            self._i = None
1052            self._initialize_volume(
1053                image, image_embeddings, save_path, verbose, offload_to_cpu, cache_all_slices,
1054                lazy_embeddings, normalization_bounds=normalization_bounds, **kwargs
1055            )
1056            return
1057
1058        owns_image_embeddings = image_embeddings is None
1059        if image_embeddings is None:
1060            image_embeddings = self._encode(image)
1061        else:
1062            image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1063        super().initialize(image, ndim=ndim, image_embeddings=image_embeddings, **kwargs)
1064        self._image_embeddings = image_embeddings
1065        self._i = None
1066        self._owns_image_embeddings = owns_image_embeddings

Encode the input, run the decoder on that encoding and leave the predictor ready to be prompted.

Both branches of a joint checkpoint share their image encoder weights, so one pass serves both and generate can be called repeatedly without any further encoding.

Arguments:
  • image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
  • ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
  • image_embeddings: Optional precomputed image embeddings. If given, the encoder does not run.
  • i: The slice index for video-style embeddings. By default the embeddings contain one image.
  • save_path: Optional path to cache the embeddings of a volume in a zarr container. Without one an ephemeral store is used, which clear_state removes.
  • verbose: Whether to print progress while the embeddings of a volume are computed.
  • offload_to_cpu: Whether a volume's tracking state is held on the host rather than on the device. False propagates the same masks 6-11% faster, for the memory of one pass of objects across the volume, which is about 17 MB per slice at the default pass size. None leaves the choice to PromptableSegmentation3D, which offloads on cuda.
  • cache_all_slices: Whether every slice's features stay on the device while a volume is propagated. A pass walks the whole volume, so a cache shorter than it is never hit and every slice is fetched again on every pass - which is most of the run on a deep volume. Costs about 90 MB of device memory per slice.
  • lazy_embeddings: Whether a volume's embeddings are read from their store slice by slice. False holds them in host memory instead, which makes the fetch above much cheaper without spending device memory.
  • normalization_bounds: Volumes only. Precomputed (lower, upper) percentile bounds (see batched_inference._volume_normalization_bounds), normally computed from image itself. Pass this when image is only a tile/block of a larger volume, so it shares that volume's bounds instead of estimating its own from its own, smaller, biased crop (see TiledAutomaticPromptGenerator.generate).
  • kwargs: Additional arguments for UniSAM2InstanceSegmentation.initialize.
def get_state(self) -> dict:
1111    def get_state(self) -> dict:
1112        """Return the decoder predictions and the image embeddings, so that both branches can be restored.
1113
1114        `generate` also prompts the interactive branch, which needs the encoding of the same input. For
1115        a volume the volume itself is part of the state, because the video predictor is initialized on it.
1116        """
1117        state = super().get_state()
1118        state["image_embeddings"] = self._image_embeddings
1119        if self._volume is not None:
1120            state["volume"] = self._volume
1121        return state

Return the decoder predictions and the image embeddings, so that both branches can be restored.

generate also prompts the interactive branch, which needs the encoding of the same input. For a volume the volume itself is part of the state, because the video predictor is initialized on it.

def set_state(self, state: dict) -> None:
1123    def set_state(self, state: dict) -> None:
1124        """Restore the decoder predictions and the encoding of the input they belong to.
1125
1126        The state must hold either 'image_embeddings' or 'image'. Without one, `generate` would prompt
1127        whatever image the predictor still holds. A volumetric state must also hold 'volume'.
1128
1129        Args:
1130            state: The state, as returned by `get_state`, or a dict with 'prediction' and 'image'.
1131        """
1132        image_embeddings = state.get("image_embeddings")
1133        volume = state.get("volume")
1134        i = state.get("i")
1135
1136        if volume is not None:
1137            if image_embeddings is None:
1138                raise ValueError("A volumetric state must hold the 'image_embeddings' of its volume.")
1139            super().set_state(state)
1140            self._volume = volume
1141            self._propagator = self._build_propagator(volume, image_embeddings)
1142            self._i = None
1143        else:
1144            if image_embeddings is None:
1145                if "image" not in state:
1146                    raise ValueError("The state must hold either 'image_embeddings' or 'image'.")
1147                image_embeddings = self._encode(state["image"])
1148            else:
1149                image_embeddings = self._prepare_image_embeddings(image_embeddings, i)
1150            super().set_state(state)
1151            self._i = None
1152        self._image_embeddings = image_embeddings
1153        self._owns_image_embeddings = False

Restore the decoder predictions and the encoding of the input they belong to.

The state must hold either 'image_embeddings' or 'image'. Without one, generate would prompt whatever image the predictor still holds. A volumetric state must also hold 'volume'.

Arguments:
  • state: The state, as returned by get_state, or a dict with 'prediction' and 'image'.
def clear_state(self) -> None:
1155    def clear_state(self) -> None:
1156        """Clear the decoder predictions and the input that is set on the predictor."""
1157        owned_embeddings = self._image_embeddings if getattr(self, "_owns_image_embeddings", False) else None
1158        super().clear_state()
1159        self._image_embeddings = None
1160        self._i = None
1161        self._owns_image_embeddings = False
1162        self._predictor.reset_predictor()
1163        self._volume = None
1164        # Built on the propagator's replicas, so it must not outlive them.
1165        self._scoring_predictor_pool = None
1166        if self._propagator is not None:
1167            self._propagator.reset_predictor()
1168            self._propagator = None
1169        try:
1170            close = getattr(owned_embeddings, "close", None)
1171            if close is not None:
1172                close()
1173        finally:
1174            if self._temporary_embedding_path is not None:
1175                shutil.rmtree(self._temporary_embedding_path, ignore_errors=True)
1176                self._temporary_embedding_path = None

Clear the decoder predictions and the input that is set on the predictor.

@torch.no_grad()
def generate( self, candidate_threshold: Union[float, Sequence[float], NoneType] = None, foreground_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, spacing: Optional[tuple] = None, min_candidate_size: Optional[int] = None, score_threshold: Optional[float] = None, max_overlap: Optional[float] = None, min_size: Optional[int] = None, max_size_factor: Optional[float] = None, refinement: Optional[str] = 'default', refinement_kwargs: Optional[Dict[str, Any]] = None, multimasking: bool = True, n_objects_per_pass: int = 16, early_stop_patience: Optional[int] = 2, propagation_waves: int = 1, batch_size: int = 64, n_threads: int = 8, verbose: bool = False, pbar_init: Optional[Callable] = None, pbar_update: Optional[Callable] = None) -> numpy.ndarray:
1178    @torch.no_grad()
1179    def generate(
1180        self,
1181        candidate_threshold: Optional[Union[float, Sequence[float]]] = None,
1182        foreground_threshold: Optional[float] = None,
1183        n_iter: Optional[int] = None,
1184        dt: Optional[float] = None,
1185        sigma: Optional[float] = None,
1186        spacing: Optional[tuple] = None,
1187        min_candidate_size: Optional[int] = None,
1188        score_threshold: Optional[float] = None,
1189        max_overlap: Optional[float] = None,
1190        min_size: Optional[int] = None,
1191        max_size_factor: Optional[float] = DEFAULT_PROMPT_GENERATION["max_size_factor"],
1192        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1193        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1194        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1195        n_objects_per_pass: int = DEFAULT_PROMPT_GENERATION["n_objects_per_pass"],
1196        early_stop_patience: Optional[int] = DEFAULT_PROMPT_GENERATION["early_stop_patience"],
1197        propagation_waves: int = DEFAULT_PROMPT_GENERATION["propagation_waves"],
1198        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1199        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1200        verbose: bool = False,
1201        pbar_init: Optional[Callable] = None,
1202        pbar_update: Optional[Callable] = None,
1203    ) -> np.ndarray:
1204        """Derive prompts from the stored predictions, apply them and merge the masks.
1205
1206        Args:
1207            candidate_threshold: Density threshold for proposing candidates, or several of them for
1208                a volume. By default resolved per model type and dimensionality, see
1209                `default_prompt_generation`.
1210            foreground_threshold: Foreground binarisation threshold. Here it only limits which pixels can
1211                be proposed from, since the masks come from the interactive branch, so it trades candidate
1212                recall rather than boundary quality.
1213            n_iter: Number of flow-integration steps for the candidate density.
1214            dt: Integration step size. Mostly only the product with 'n_iter' matters, which is the
1215                distance a pixel is advected.
1216            sigma: Gaussian sigma for smoothing the candidate density. Less smoothing leaves more peaks,
1217                which costs precision for the sparse post-processing but buys candidate recall here.
1218            spacing: Anisotropic voxel spacing of a volume, e.g. (4, 1, 1).
1219            min_candidate_size: Discard density components smaller than this.
1220            score_threshold: Discard candidates whose predicted IoU is below this.
1221            max_overlap: Reject a candidate when more than this fraction of it is already claimed. For a
1222                volume this applies on the slice a candidate is prompted on and again on the 3d merge.
1223            min_size: Minimum object size in the result.
1224            max_size_factor: Volumes only. Reject a candidate this many times larger than the median
1225                size among the candidates it is merged against, which catches propagation drift (a
1226                track that grows onto background instead of ending). None (the default) applies no
1227                such cap; see `merge_by_score`.
1228            refinement: Optional second round, a '+'-joined combination of 'points' (the first
1229                round's prompts grouped onto each merged instance, see `derive_refinement_prompts`),
1230                'boxes' (its bounding box) and 'masks' (its mask as a logit prompt). None runs no second
1231                round. 'default' (the default) takes the mode of `default_prompt_generation`. For a
1232                volume the round runs on each candidate's anchor slice, before the propagation, and
1233                produces the conditioning that propagation starts from rather than a finished mask,
1234                see `_refine_anchors`.
1235            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1236                components; see `DEFAULT_REFINEMENT`, or `DEFAULT_REFINEMENT_3D` for a volume, for
1237                the accepted keys and their defaults.
1238            multimasking: Whether to predict several masks per point and keep the best scoring one. A
1239                single point is ambiguous between one object and a cluster, so this is on by default.
1240            n_objects_per_pass: Number of objects propagated together through a volume. The video
1241                predictor runs them as one batch, so this trades device memory against the pass count.
1242            propagation_waves: Tiled volumes only. Rounds the candidates are propagated in, highest
1243                scoring first, dropping between rounds those an already-propagated instance covers by
1244                more than 'max_overlap'. One round propagates every candidate, see
1245                `DEFAULT_PROMPT_GENERATION`.
1246            early_stop_patience: Stop a propagation pass after this many consecutive slices in which
1247                every object of the pass is empty. None propagates through the whole volume. Two by
1248                default: propagating past the end of every object of a pass only reproduces empty
1249                masks, so this saves work without changing the result. Raise it where an object may
1250                disappear and reappear, because a stop that fires mid-object truncates it.
1251            batch_size: Number of prompts per forward pass.
1252            n_threads: Number of threads for the flow integration the candidates come from.
1253            verbose: Whether to show progress over the propagation passes of a volume.
1254            pbar_init: Initialize an external progress stage with its total and description.
1255            pbar_update: Advance the external progress bar after completed work.
1256
1257        Returns:
1258            The instance segmentation, uint32 array with the spatial shape of the prediction.
1259        """
1260        if not self._is_initialized:
1261            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1262
1263        self._last_generation_stats = {}
1264        shape = self._prediction[0].shape
1265        # The prediction carries the dimensionality it was run at: (4, Y, X) or (4, Z, Y, X).
1266        is_volume = self._prediction.ndim == 4
1267        defaults = default_prompt_generation(self._model_type, is_volume=is_volume)
1268        if candidate_threshold is None:
1269            candidate_threshold = defaults["candidate_threshold"]
1270        if score_threshold is None:
1271            score_threshold = defaults["score_threshold"]
1272        if max_overlap is None:
1273            max_overlap = defaults["max_overlap"]
1274        if min_size is None:
1275            min_size = defaults["min_size"]
1276        if refinement == "default":
1277            refinement = defaults["refinement"]
1278
1279        if is_volume:
1280            components = resolved = None
1281            if refinement is not None:
1282                components, resolved = _parse_refinement(refinement, refinement_kwargs, is_volume=True)
1283            if pbar_init is not None:
1284                pbar_init(1, "APG: deriving volume prompts")
1285            prompts = derive_volume_prompts(
1286                self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1287                candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1288                n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing,
1289                min_candidate_size=min_candidate_size, n_threads=n_threads,
1290            )
1291            if pbar_update is not None:
1292                pbar_update(1)
1293            if prompts is None:
1294                self._last_generation_stats = {
1295                    "proposed_candidates": 0,
1296                    "scored_candidates": 0,
1297                    "unique_anchor_slices": 0,
1298                    "propagation_passes": 0,
1299                    "propagated_frame_steps": 0,
1300                    "early_stopped_frame_steps": 0,
1301                }
1302                if components is not None:
1303                    self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1304                return np.zeros(shape, dtype="uint32")
1305            self._last_generation_stats["proposed_candidates"] = len(prompts["points"])
1306            if components is not None:
1307                self._last_generation_stats.update({key: 0 for key in REFINEMENT_STATS_3D})
1308            # The refinement's forwards are not wrapped by '_apply_prompts', which has its own.
1309            if components is None:
1310                candidates = self._score_candidates(
1311                    prompts, multimasking=multimasking, batch_size=batch_size,
1312                    score_threshold=score_threshold, max_overlap=max_overlap,
1313                    components=components, refinement_kwargs=resolved,
1314                    pbar_init=pbar_init, pbar_update=pbar_update,
1315                )
1316            else:
1317                with autocast(self._predictor.device):
1318                    candidates = self._score_candidates(
1319                        prompts, multimasking=multimasking, batch_size=batch_size,
1320                        score_threshold=score_threshold, max_overlap=max_overlap,
1321                        components=components, refinement_kwargs=resolved,
1322                        pbar_init=pbar_init, pbar_update=pbar_update,
1323                    )
1324            self._last_generation_stats["scored_candidates"] = len(candidates)
1325            records = self._propagate_candidates(
1326                candidates, n_objects_per_pass=n_objects_per_pass,
1327                early_stop_patience=early_stop_patience, verbose=verbose, max_overlap=max_overlap,
1328                propagation_waves=propagation_waves, pbar_init=pbar_init, pbar_update=pbar_update,
1329            )
1330            # Tiled records arrive grouped by tile and need their halo overlaps resolved, which
1331            # '_merge' does polymorphically; an untiled volume merges them flat.
1332            if pbar_init is not None:
1333                pbar_init(1, "APG: merging volume masks")
1334            segmentation, _ = self._merge(
1335                records, shape, score_threshold=score_threshold, max_overlap=max_overlap,
1336                min_size=min_size, max_size_factor=max_size_factor,
1337            )
1338            if pbar_update is not None:
1339                pbar_update(1)
1340            return segmentation
1341
1342        proposals = self.propose(
1343            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1344            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size,
1345            multimasking=multimasking, batch_size=batch_size, n_threads=n_threads,
1346            pbar_init=pbar_init, pbar_update=pbar_update,
1347        )
1348        return self.select(
1349            proposals, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1350            refinement=refinement, refinement_kwargs=refinement_kwargs, batch_size=batch_size,
1351        )

Derive prompts from the stored predictions, apply them and merge the masks.

Arguments:
  • candidate_threshold: Density threshold for proposing candidates, or several of them for a volume. By default resolved per model type and dimensionality, see default_prompt_generation.
  • foreground_threshold: Foreground binarisation threshold. Here it only limits which pixels can be proposed from, since the masks come from the interactive branch, so it trades candidate recall rather than boundary quality.
  • n_iter: Number of flow-integration steps for the candidate density.
  • dt: Integration step size. Mostly only the product with 'n_iter' matters, which is the distance a pixel is advected.
  • sigma: Gaussian sigma for smoothing the candidate density. Less smoothing leaves more peaks, which costs precision for the sparse post-processing but buys candidate recall here.
  • spacing: Anisotropic voxel spacing of a volume, e.g. (4, 1, 1).
  • min_candidate_size: Discard density components smaller than this.
  • score_threshold: Discard candidates whose predicted IoU is below this.
  • max_overlap: Reject a candidate when more than this fraction of it is already claimed. For a volume this applies on the slice a candidate is prompted on and again on the 3d merge.
  • min_size: Minimum object size in the result.
  • max_size_factor: Volumes only. Reject a candidate this many times larger than the median size among the candidates it is merged against, which catches propagation drift (a track that grows onto background instead of ending). None (the default) applies no such cap; see merge_by_score.
  • refinement: Optional second round, a '+'-joined combination of 'points' (the first round's prompts grouped onto each merged instance, see derive_refinement_prompts), 'boxes' (its bounding box) and 'masks' (its mask as a logit prompt). None runs no second round. 'default' (the default) takes the mode of default_prompt_generation. For a volume the round runs on each candidate's anchor slice, before the propagation, and produces the conditioning that propagation starts from rather than a finished mask, see _refine_anchors.
  • refinement_kwargs: Keyword arguments of that second round, validated against the mode's components; see DEFAULT_REFINEMENT, or DEFAULT_REFINEMENT_3D for a volume, for the accepted keys and their defaults.
  • multimasking: Whether to predict several masks per point and keep the best scoring one. A single point is ambiguous between one object and a cluster, so this is on by default.
  • n_objects_per_pass: Number of objects propagated together through a volume. The video predictor runs them as one batch, so this trades device memory against the pass count.
  • propagation_waves: Tiled volumes only. Rounds the candidates are propagated in, highest scoring first, dropping between rounds those an already-propagated instance covers by more than 'max_overlap'. One round propagates every candidate, see DEFAULT_PROMPT_GENERATION.
  • early_stop_patience: Stop a propagation pass after this many consecutive slices in which every object of the pass is empty. None propagates through the whole volume. Two by default: propagating past the end of every object of a pass only reproduces empty masks, so this saves work without changing the result. Raise it where an object may disappear and reappear, because a stop that fires mid-object truncates it.
  • batch_size: Number of prompts per forward pass.
  • n_threads: Number of threads for the flow integration the candidates come from.
  • verbose: Whether to show progress over the propagation passes of a volume.
  • pbar_init: Initialize an external progress stage with its total and description.
  • pbar_update: Advance the external progress bar after completed work.
Returns:

The instance segmentation, uint32 array with the spatial shape of the prediction.

@torch.no_grad()
def propose( self, candidate_threshold: Optional[float] = None, foreground_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, min_candidate_size: Optional[int] = None, multimasking: bool = True, batch_size: int = 64, n_threads: int = 8, pbar_init: Optional[Callable] = None, pbar_update: Optional[Callable] = None) -> list:
1353    @torch.no_grad()
1354    def propose(
1355        self,
1356        candidate_threshold: Optional[float] = None,
1357        foreground_threshold: Optional[float] = None,
1358        n_iter: Optional[int] = None,
1359        dt: Optional[float] = None,
1360        sigma: Optional[float] = None,
1361        min_candidate_size: Optional[int] = None,
1362        multimasking: bool = DEFAULT_PROMPT_GENERATION["multimasking"],
1363        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1364        n_threads: int = DEFAULT_PROMPT_GENERATION["n_threads"],
1365        pbar_init: Optional[Callable] = None,
1366        pbar_update: Optional[Callable] = None,
1367    ) -> list:
1368        """Derive the prompts and turn them into scored mask proposals, without selecting any of them.
1369
1370        This is the half of `generate` that needs the model. Splitting it off lets a parameter sweep
1371        reuse one set of proposals across every value of 'score_threshold', 'max_overlap' and
1372        'min_size', which only filter and merge. Images only: a volume gates its propagation on the
1373        score, so its proposals depend on those parameters too.
1374
1375        Args:
1376            candidate_threshold: Density threshold for proposing candidates, see `derive_point_prompts`.
1377            foreground_threshold: Foreground binarisation threshold.
1378            n_iter: Number of flow-integration steps for the candidate density.
1379            dt: Integration step size.
1380            sigma: Gaussian sigma for smoothing the candidate density.
1381            min_candidate_size: Discard density components smaller than this.
1382            multimasking: Whether to predict several masks per point and keep the best scoring one.
1383            batch_size: Number of prompts per forward pass.
1384            n_threads: Number of threads for the flow integration the candidates come from.
1385            pbar_init: Initialize each progress stage with its total and description.
1386            pbar_update: Advance progress after deriving prompts and each prediction batch.
1387
1388        Returns:
1389            The proposals, to be passed to `select`. Their layout is an implementation detail of the
1390            generator that produced them.
1391        """
1392        if not self._is_initialized:
1393            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
1394        if self._prediction.ndim == 4:
1395            raise ValueError("Proposals can only be reused for an image, because a volume gates its propagation.")
1396
1397        if pbar_init is not None:
1398            pbar_init(1, "APG: deriving prompts")
1399        prompts = derive_point_prompts(
1400            self._prediction[0], self._prediction[1:4], model_type=self._model_type,
1401            candidate_threshold=candidate_threshold, foreground_threshold=foreground_threshold,
1402            n_iter=n_iter, dt=dt, sigma=sigma, min_candidate_size=min_candidate_size, n_threads=n_threads,
1403        )
1404        if pbar_update is not None:
1405            pbar_update(1)
1406        if prompts is None:
1407            return []
1408        if pbar_init is not None:
1409            pbar_init((len(prompts["points"]) + batch_size - 1) // batch_size, "APG: prompting batches")
1410        return self._apply(
1411            prompts, multimasking=multimasking, batch_size=batch_size, pbar_update=pbar_update,
1412        )

Derive the prompts and turn them into scored mask proposals, without selecting any of them.

This is the half of generate that needs the model. Splitting it off lets a parameter sweep reuse one set of proposals across every value of 'score_threshold', 'max_overlap' and 'min_size', which only filter and merge. Images only: a volume gates its propagation on the score, so its proposals depend on those parameters too.

Arguments:
  • candidate_threshold: Density threshold for proposing candidates, see derive_point_prompts.
  • foreground_threshold: Foreground binarisation threshold.
  • n_iter: Number of flow-integration steps for the candidate density.
  • dt: Integration step size.
  • sigma: Gaussian sigma for smoothing the candidate density.
  • min_candidate_size: Discard density components smaller than this.
  • multimasking: Whether to predict several masks per point and keep the best scoring one.
  • batch_size: Number of prompts per forward pass.
  • n_threads: Number of threads for the flow integration the candidates come from.
  • pbar_init: Initialize each progress stage with its total and description.
  • pbar_update: Advance progress after deriving prompts and each prediction batch.
Returns:

The proposals, to be passed to select. Their layout is an implementation detail of the generator that produced them.

def select( self, proposals: list, score_threshold: Optional[float] = None, max_overlap: Optional[float] = None, min_size: Optional[int] = None, refinement: Optional[str] = 'default', refinement_kwargs: Optional[Dict[str, Any]] = None, batch_size: int = 64) -> numpy.ndarray:
1414    def select(
1415        self,
1416        proposals: list,
1417        score_threshold: Optional[float] = None,
1418        max_overlap: Optional[float] = None,
1419        min_size: Optional[int] = None,
1420        refinement: Optional[str] = DEFAULT_PROMPT_GENERATION["refinement"],
1421        refinement_kwargs: Optional[Dict[str, Any]] = DEFAULT_PROMPT_GENERATION["refinement_kwargs"],
1422        batch_size: int = DEFAULT_PROMPT_GENERATION["batch_size"],
1423    ) -> np.ndarray:
1424        """Merge the proposals of `propose` into an instance segmentation.
1425
1426        Args:
1427            proposals: The proposals, as returned by `propose` on the same generator.
1428            score_threshold: Discard proposals whose predicted IoU is below this.
1429            max_overlap: Reject a proposal when more than this fraction of it is already claimed.
1430            min_size: Minimum object size in the result.
1431            refinement: Optional second round, a '+'-joined combination of 'points', 'boxes',
1432                and 'masks', or 'default' for the mode of `default_prompt_generation`; see `generate`.
1433            refinement_kwargs: Keyword arguments of that second round, validated against the mode's
1434                components; see `DEFAULT_REFINEMENT` for the accepted keys and their defaults.
1435            batch_size: Number of prompts per forward pass of the refinement.
1436
1437        Returns:
1438            The instance segmentation, uint32 array with the spatial shape of the prediction.
1439        """
1440        defaults = default_prompt_generation(self._model_type, is_volume=False)
1441        if score_threshold is None:
1442            score_threshold = defaults["score_threshold"]
1443        if max_overlap is None:
1444            max_overlap = defaults["max_overlap"]
1445        if min_size is None:
1446            min_size = defaults["min_size"]
1447        if refinement == "default":
1448            refinement = defaults["refinement"]
1449
1450        components = resolved = None
1451        if refinement is not None:
1452            components, resolved = _parse_refinement(refinement, refinement_kwargs)
1453
1454        shape = self._prediction[0].shape
1455        if not proposals:
1456            return np.zeros(shape, dtype="uint32")
1457
1458        segmentation, context = self._merge(
1459            proposals, shape, score_threshold=score_threshold, max_overlap=max_overlap, min_size=min_size,
1460            return_context=components is not None,
1461        )
1462        if components is not None and segmentation.max() > 0:
1463            segmentation = self._refine(segmentation, context, components, resolved, batch_size)
1464        return segmentation

Merge the proposals of propose into an instance segmentation.

Arguments:
  • proposals: The proposals, as returned by propose on the same generator.
  • score_threshold: Discard proposals whose predicted IoU is below this.
  • max_overlap: Reject a proposal when more than this fraction of it is already claimed.
  • min_size: Minimum object size in the result.
  • refinement: Optional second round, a '+'-joined combination of 'points', 'boxes', and 'masks', or 'default' for the mode of default_prompt_generation; see generate.
  • refinement_kwargs: Keyword arguments of that second round, validated against the mode's components; see DEFAULT_REFINEMENT for the accepted keys and their defaults.
  • batch_size: Number of prompts per forward pass of the refinement.
Returns:

The instance segmentation, uint32 array with the spatial shape of the prediction.

class TiledAutomaticPromptGenerator:
2369class TiledAutomaticPromptGenerator:
2370    """Generates an instance segmentation with automatically generated prompts, tile or block by tile.
2371
2372    Like `AutomaticPromptGenerator`, but every tile (an image) or XYZ block (a volume) is segmented
2373    independently at native resolution, with a halo, and the results are stitched by
2374    `bioimage_py.segmentation.stitch_segmentation`'s multicut over the halo overlap rather than by
2375    giving each candidate to exactly one tile. A volume is blocked in Z too, so an object crossing a
2376    Z seam is reconciled the same way one crossing a Y or X seam is: independently predicted in both
2377    neighbouring blocks and merged by how well their halo predictions agree, instead of being routed
2378    to a single owning tile - which a full-depth tile column cannot do for a Z seam at all. This
2379    trades some redundant halo computation (every tile/block re-encodes and re-propagates its own
2380    halo) for correctness at every seam, including ones the previous tile-column design could not
2381    represent. See finetuning/v2/evaluation/apg_3d_blockwise_ab.py for the measurements.
2382
2383    Every resolved device gets its own persistent (decoder, model) copy, built once and reused
2384    across every tile/block for the life of the generator, so `generate` keeps every device busy on
2385    a different tile/block concurrently rather than rebuilding the model per tile.
2386
2387    Args:
2388        model: The UniSAM2 model (see `get_unisam2_model` / `get_decoder`).
2389        predictor: The SAM2 image predictor for the interactive branch of the same model, or its
2390            video predictor for a volume.
2391        device: The device the model lives on, used to resolve `inference_device=None`.
2392        inference_device: The device(s) to run tiles/blocks on concurrently, resolved the same way
2393            as `UniSAM2InstanceSegmentation`'s: None fans out over every visible GPU when the model
2394            is on CUDA, a single device stays on it, a sequence pins one pool member per device.
2395        beta: The multicut boundary bias passed to `stitch_segmentation`; > 0.5 biases towards
2396            over-segmentation (cutting), < 0.5 towards under-segmentation (merging).
2397        workers_per_device: How many independent (decoder, model) copies to build per resolved
2398            device. `generate` still gives each worker one tile/block at a time, so this only helps
2399            when a single worker leaves a device's compute or memory underused, e.g. a small model
2400            on a large GPU. Not supported together with `execution='process'`.
2401        execution: How a tile/block's own segmentation runs. `'thread'` (the default) runs every
2402            worker in this process on a `concurrent.futures.ThreadPoolExecutor`, sharing one Python
2403            interpreter. `'process'` instead gives every device its own persistent OS process, with
2404            its own interpreter and CUDA context, so one device's per-frame propagation bookkeeping
2405            never blocks another's behind the GIL - measured at 1.5-4x faster than `'thread'` once
2406            the pool is warm (bigger blocks and more of them widen the gap), with no quality change
2407            (see finetuning/v2/evaluation). The first `generate` call after building the generator
2408            pays extra for it, though: every worker process loads its own model from disk instead of
2409            reusing an in-memory copy the way `'thread'`'s pool does, which cost ~10-15s total across
2410            4 workers in that same measurement. Worth it for a generator that runs many volumes, not
2411            necessarily for a single one-off call. Requires `model_builder`.
2412        model_builder: Required for `execution='process'`. A callable `(device) -> (model,
2413            predictor)` that builds a fresh model and predictor pair on a device string - every
2414            worker process calls this itself rather than receiving `model`/`predictor` from the
2415            parent, because a live CUDA model cannot cross a process boundary safely.
2416        process_timeout: `execution='process'` only. Seconds a block waits for its worker before
2417            raising, rather than hanging forever if a worker process has died or wedged.
2418    """
2419
2420    # Read by `automatic_instance_segmentation` to decide whether to pass the AIS 'mode' argument.
2421    _has_postprocessing_mode = False
2422    _is_decoder_based = True
2423    # The front end computes the embeddings only when it caches them.
2424    _precompute_embeddings_in_frontend = False
2425
2426    def __init__(
2427        self,
2428        model: torch.nn.Module,
2429        predictor,
2430        device: Optional[Union[str, torch.device]] = None,
2431        inference_device: Devices = USE_MODEL_DEVICE,
2432        beta: float = DEFAULT_STITCHING_BETA,
2433        workers_per_device: int = 1,
2434        execution: str = "thread",
2435        model_builder: Optional[Callable[[str], tuple]] = None,
2436        process_timeout: float = 600.0,
2437    ) -> None:
2438        self._model = model
2439        self._predictor = predictor
2440        self._device = device
2441        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
2442        self._beta = beta
2443        if workers_per_device < 1:
2444            raise ValueError(f"'workers_per_device' must be >= 1, got {workers_per_device}.")
2445        self._workers_per_device = int(workers_per_device)
2446        if execution not in ("thread", "process"):
2447            raise ValueError(f"'execution' must be 'thread' or 'process', got {execution!r}.")
2448        if execution == "process":
2449            if workers_per_device != 1:
2450                raise ValueError("'workers_per_device' > 1 is not supported with execution='process'.")
2451            if model_builder is None:
2452                raise ValueError(
2453                    "execution='process' needs 'model_builder', a callable (device) -> (model, "
2454                    "predictor) every worker process calls to build its own model copy - a live CUDA "
2455                    "model cannot cross a process boundary safely."
2456                )
2457        self._execution = execution
2458        self._model_builder = model_builder
2459        self._process_timeout = float(process_timeout)
2460        self._pool: Optional[List[AutomaticPromptGenerator]] = None
2461        self._process_devices: Optional[List[str]] = None
2462        self._task_queues: Optional[list] = None
2463        self._processes: Optional[list] = None
2464        self._manager = None
2465        self._image = None
2466        self._ndim = None
2467        self._tile_shape = None
2468        self._halo = None
2469        self._verbose = False
2470        self._offload_to_cpu = None
2471        self._cache_all_slices = False
2472        self._image_embeddings = None
2473        self._i = None
2474
2475    def _inference_devices(self, devices: Devices) -> Devices:
2476        """Resolve the inference devices and discard a pool that uses different devices."""
2477        inference_devices = self._inference_device if devices is None else devices
2478        if inference_devices != self._inference_device:
2479            self.close()
2480            if self._pool is not None:
2481                for generator in self._pool:
2482                    generator.clear_state()
2483                self._pool = None
2484            self._inference_device = inference_devices
2485        return inference_devices
2486
2487    def _build_pool(self) -> List[AutomaticPromptGenerator]:
2488        """'workers_per_device' independent (decoder, model) copies per resolved device.
2489
2490        Every worker is pinned entirely to its own device, and only one tile/block ever owns a
2491        worker at a time (see `generate`'s queue), so multiple workers sharing a device compete for
2492        its compute rather than racing on shared state. This is worth it only because a single
2493        worker's block leaves a large GPU's memory and, more importantly, its compute scheduling far
2494        from saturated (a `hvit_t` block is a few GB on an 80+ GB H100): plain Python threads sharing
2495        a device all submit to its one default CUDA stream, which runs their kernels in submission
2496        order and gives no real concurrency, so every worker beyond the first on a device gets its
2497        own `torch.cuda.Stream` (`generate` runs it under that stream) to let the driver actually
2498        interleave independent tiles' kernels on the same device.
2499        """
2500        devices = _resolve_devices(self._model, self._inference_device)
2501        worker_devices = [device for device in devices for _ in range(self._workers_per_device)]
2502
2503        def move_pair(model, predictor, device):
2504            model.to(device)
2505            getattr(predictor, "model", predictor).to(device)
2506
2507        worker_pairs = [None] * len(worker_devices)
2508        if len(worker_devices) > 1:
2509            move_pair(self._model, self._predictor, "cpu")
2510            for worker_id in range(1, len(worker_devices)):
2511                pair = copy.deepcopy((self._model, self._predictor))
2512                move_pair(*pair, worker_devices[worker_id])
2513                worker_pairs[worker_id] = pair
2514        move_pair(self._model, self._predictor, worker_devices[0])
2515        worker_pairs[0] = self._model, self._predictor
2516
2517        pool = []
2518        for (model, predictor), device in zip(worker_pairs, worker_devices):
2519            device_obj = torch.device(device)
2520            generator = AutomaticPromptGenerator(model, predictor, device=device, inference_device=device)
2521            if self._workers_per_device > 1 and device_obj.type == "cuda":
2522                generator._tile_stream = torch.cuda.Stream(device=device_obj)
2523            pool.append(generator)
2524        return pool
2525
2526    def _build_process_pool(self) -> None:
2527        """Start one persistent worker OS process per resolved device, each with its own model copy.
2528
2529        Sidesteps the thread pool's GIL contention rather than working around it: every worker has
2530        its own Python interpreter, so the per-frame propagation bookkeeping of one device's block
2531        never blocks another device's. `_manager` backs the per-block reply queues - a `Queue`
2532        created after these processes already exist cannot be pickled to a `spawn`-context child,
2533        only a manager-proxied one can.
2534        """
2535        devices = _resolve_devices(self._model, self._inference_device)
2536        ctx = mp.get_context("spawn")
2537        self._manager = ctx.Manager()
2538        self._process_devices = devices
2539        self._task_queues = [ctx.Queue() for _ in devices]
2540        self._processes = [
2541            ctx.Process(target=_process_worker, args=(self._model_builder, device, task_queue), daemon=True)
2542            for device, task_queue in zip(devices, self._task_queues)
2543        ]
2544        for process in self._processes:
2545            process.start()
2546
2547    def close(self) -> None:
2548        """Stop the process pool, if `execution='process'` built one. A no-op otherwise.
2549
2550        Not required for correctness - every worker process is a daemon, so it exits with the main
2551        process - but lets a caller reclaim the devices deterministically before that.
2552        """
2553        if self._processes is None:
2554            return
2555        for task_queue in self._task_queues:
2556            task_queue.put(None)
2557        for process in self._processes:
2558            process.join(timeout=10)
2559            if process.is_alive():
2560                process.terminate()
2561        self._manager.shutdown()
2562        self._processes = None
2563        self._task_queues = None
2564        self._process_devices = None
2565        self._manager = None
2566
2567    def initialize(
2568        self,
2569        image: np.ndarray,
2570        ndim: int = 2,
2571        tile_shape: Optional[tuple] = None,
2572        halo: Optional[tuple] = None,
2573        verbose: bool = False,
2574        offload_to_cpu: Optional[bool] = None,
2575        cache_all_slices: bool = False,
2576        image_embeddings: Optional[dict] = None,
2577        i: Optional[int] = None,
2578    ) -> None:
2579        """Store the input and the tile/block geometry; the actual segmentation happens in `generate`.
2580
2581        Unlike `AutomaticPromptGenerator`, nothing is encoded here: each tile/block is encoded from
2582        scratch inside `generate`, since every tile/block needs its own encoder pass over its halo.
2583        If you give precomputed tiled `image_embeddings`, every tile/block reads its embeddings from
2584        them, and the encoder does not run.
2585
2586        Args:
2587            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
2588            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
2589            tile_shape: The inner tile/block shape, (y, x) for an image, always the full (z, y, x)
2590                for a volume - it is blocked in z too, not tiled in-plane only, so an object crossing
2591                a z seam is reconciled by the halo-overlap multicut the same way a y/x one is. Pass
2592                the full volume depth as the z entry for in-plane-only tiling (one whole-depth block
2593                per xy tile).
2594            halo: The halo added on each side of a tile/block, matching `tile_shape`'s axes.
2595            verbose: Whether each tile/block's generator prints progress while it segments it.
2596            offload_to_cpu: Volumes only, forwarded to every tile/block's own
2597                `AutomaticPromptGenerator.initialize`.
2598            cache_all_slices: Volumes only, forwarded the same way.
2599            image_embeddings: The optional precomputed tiled embeddings of the input. With `i`, the
2600                embeddings of the volume that contains the input slice. Their in-plane tile shape
2601                and halo must be the ones of `tile_shape` and `halo`.
2602            i: The index of the input slice in the volume of `image_embeddings`.
2603        """
2604        if ndim not in (2, 3):
2605            raise ValueError(f"Tiled prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
2606        if tile_shape is None or halo is None:
2607            raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled generator.")
2608        if len(tile_shape) != ndim or len(halo) != ndim:
2609            raise ValueError(
2610                f"'tile_shape' and 'halo' must have {ndim} entries for a {ndim}d input, one per spatial "
2611                "axis - always (z, y, x) for a volume, never in-plane only."
2612            )
2613        tile_shape = tuple(int(t) for t in tile_shape)
2614        halo = tuple(int(h) for h in halo)
2615        if image_embeddings is not None:
2616            _check_tiled_embeddings(image_embeddings, image.shape[:ndim], tile_shape, halo, i)
2617        self._image = image
2618        self._ndim = ndim
2619        self._tile_shape = tile_shape
2620        self._halo = halo
2621        self._verbose = verbose
2622        self._offload_to_cpu = offload_to_cpu
2623        self._cache_all_slices = cache_all_slices
2624        self._image_embeddings = image_embeddings
2625        self._i = None if image_embeddings is None else i
2626
2627    @torch.no_grad()
2628    def generate(self, *, pbar_init=None, pbar_update=None, **params) -> np.ndarray:
2629        """Segment every tile/block independently and stitch them by halo-overlap multicut.
2630
2631        `propagation_waves` reaches every tile/block unchanged, but each one propagates with its
2632        own halo as a protected margin (see `AutomaticPromptGenerator._is_protected_from_pruning`):
2633        a candidate whose anchor frame or mask reaches into that margin is never pruned as a
2634        within-tile duplicate, since it is exactly the kind of prediction the halo-overlap multicut
2635        compares against the neighbouring tile/block.
2636
2637        For a volume, every tile/block is also normalized against percentile bounds computed once
2638        over the whole image (`normalization_bounds`, see `AutomaticPromptGenerator.initialize`),
2639        never its own local crop - the same statistics an untiled `AutomaticPromptGenerator` would
2640        use, so a tile's brightness/contrast does not depend on which tile it happens to be.
2641
2642        Args:
2643            pbar_init: Initialize progress with the number of tiles and a description.
2644            pbar_update: Advance progress after each completed tile, on the calling thread.
2645            params: Keyword arguments for `AutomaticPromptGenerator.generate`, applied identically
2646                to every tile/block.
2647
2648        Returns:
2649            The stitched instance segmentation, uint32 array with the shape of the input.
2650        """
2651        if self._image is None:
2652            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
2653        if bp is None:
2654            raise RuntimeError("Tiled automatic prompt generation requires 'bioimage_py'. Install bioimage-py.")
2655
2656        params = dict(params)
2657        protected_margin = tuple(self._halo)
2658        # Computed once over the whole image/volume so every tile/block shares one normalization
2659        # instead of each estimating its own percentiles from its own, smaller, biased crop.
2660        encodes = self._ndim == 3 and self._image_embeddings is None  # Only the encoder uses the bounds.
2661        normalization_bounds = _volume_normalization_bounds(self._image) if encodes else None
2662
2663        if self._execution == "process":
2664            segment_block, num_workers = self._process_dispatch(params, normalization_bounds, protected_margin)
2665        else:
2666            segment_block, num_workers = self._thread_dispatch(params, normalization_bounds, protected_margin)
2667
2668        shape = self._image.shape[:self._ndim]
2669        n_tiles = int(np.prod([(size + tile - 1) // tile for size, tile in zip(shape, self._tile_shape)]))
2670        if pbar_init is not None:
2671            pbar_init(n_tiles, "APG: segmenting tiles")
2672
2673        def stitch(update):
2674            def segment_with_progress(block, block_id):
2675                result = segment_block(block, block_id)
2676                if update is not None:
2677                    update(1)
2678                return result
2679
2680            return bp.segmentation.stitch_segmentation(
2681                input=self._image,
2682                segmentation_function=segment_with_progress,
2683                shape=self._image.shape[:self._ndim],
2684                tile_shape=self._tile_shape,
2685                tile_overlap=self._halo,
2686                beta=self._beta,
2687                with_background=True,
2688                num_workers=num_workers,
2689                job_type="local",
2690            )
2691        output = _run_with_progress(stitch, pbar_update)
2692        return np.asarray(output).astype("uint32")
2693
2694    def _block_embedding_kwargs(self, block_id: int) -> dict:
2695        """The precomputed embeddings to initialize a block's generator with, if there are any."""
2696        if self._image_embeddings is None:
2697            return {}
2698        embeddings, i = _block_embeddings(
2699            self._image_embeddings, self._image.shape[:self._ndim], self._tile_shape, self._halo, block_id, self._i,
2700        )
2701        return {"image_embeddings": embeddings, "i": i}
2702
2703    def _thread_dispatch(self, params: dict, normalization_bounds, protected_margin: tuple):
2704        """Build the `segment_block` closure for `execution='thread'` (the default)."""
2705        if self._pool is None:
2706            self._pool = self._build_pool()
2707        available: "queue.Queue[AutomaticPromptGenerator]" = queue.Queue()
2708        for generator in self._pool:
2709            available.put(generator)
2710
2711        def segment_block(block: np.ndarray, block_id: int) -> np.ndarray:
2712            block = np.asarray(block)
2713            embedding_kwargs = self._block_embedding_kwargs(block_id)
2714            generator = available.get()
2715            # None (a worker alone on its device) skips the stream context entirely, keeping the
2716            # default stream - torch.cuda.stream(None) resolves the current device even when there
2717            # is no CUDA at all, which errors on a CPU/MPS-only machine.
2718            stream = getattr(generator, "_tile_stream", None)
2719            stream_context = torch.cuda.stream(stream) if stream is not None else contextlib.nullcontext()
2720            try:
2721                with stream_context:
2722                    generator.initialize(
2723                        block, ndim=self._ndim, verbose=self._verbose,
2724                        offload_to_cpu=self._offload_to_cpu, cache_all_slices=self._cache_all_slices,
2725                        normalization_bounds=normalization_bounds, **embedding_kwargs,
2726                    )
2727                    generator._pruning_protected_margin = protected_margin
2728                    result = generator.generate(**params)
2729                    if stream is not None:
2730                        # Block until this tile's queued GPU work is done before it is handed off:
2731                        # the caller reads 'result' outside the stream context, on another thread.
2732                        stream.synchronize()
2733                return result
2734            finally:
2735                generator.clear_state()
2736                available.put(generator)
2737
2738        return segment_block, len(self._pool)
2739
2740    def _process_dispatch(self, params: dict, normalization_bounds, protected_margin: tuple):
2741        """Build the `segment_block` closure for `execution='process'`.
2742
2743        Each call round-trips a block through its worker's task queue and a per-block reply queue,
2744        synchronously - the dispatching thread blocks on I/O while it waits, which releases the GIL,
2745        so several dispatch threads still overlap even though the real segmentation work now happens
2746        in another process entirely.
2747        """
2748        if self._processes is None:
2749            self._build_process_pool()
2750        available: "queue.Queue[int]" = queue.Queue()
2751        for worker_id in range(len(self._processes)):
2752            available.put(worker_id)
2753
2754        def segment_block(block: np.ndarray, block_id: int) -> np.ndarray:
2755            block = np.asarray(block)
2756            worker_id = available.get()
2757            if not self._processes[worker_id].is_alive():
2758                raise RuntimeError(f"process worker {worker_id} died before block {block_id} was dispatched.")
2759            result_queue = self._manager.Queue()
2760            try:
2761                self._task_queues[worker_id].put({
2762                    "block": block, "ndim": self._ndim, "protected_margin": protected_margin,
2763                    "params": params, "normalization_bounds": normalization_bounds,
2764                    "offload_to_cpu": self._offload_to_cpu, "cache_all_slices": self._cache_all_slices,
2765                    "embedding_kwargs": self._block_embedding_kwargs(block_id), "result_queue": result_queue,
2766                })
2767                try:
2768                    status, payload = result_queue.get(timeout=self._process_timeout)
2769                except queue.Empty:
2770                    raise RuntimeError(
2771                        f"process worker {worker_id} timed out after {self._process_timeout:.0f}s on "
2772                        f"block {block_id}."
2773                    )
2774                if status == "err":
2775                    raise RuntimeError(f"process worker {worker_id} failed on block {block_id}: {payload}")
2776                return payload
2777            finally:
2778                available.put(worker_id)
2779
2780        return segment_block, len(self._processes)
2781
2782    def get_state(self) -> dict:
2783        """Return the input, the tile/block geometry and the embeddings, so `set_state` can restore them."""
2784        return {
2785            "image": self._image, "ndim": self._ndim, "tile_shape": self._tile_shape, "halo": self._halo,
2786            "image_embeddings": self._image_embeddings, "i": self._i,
2787        }
2788
2789    def set_state(self, state: dict) -> None:
2790        """Restore the input, the tile/block geometry and the embeddings `initialize` stored.
2791
2792        Args:
2793            state: The state, as returned by `get_state`.
2794        """
2795        if "image" not in state:
2796            raise ValueError("A tiled prompt-generator state must hold its 'image'.")
2797        self._image = state["image"]
2798        self._ndim = state.get("ndim", 2)
2799        self._tile_shape = state.get("tile_shape")
2800        self._halo = state.get("halo")
2801        self._image_embeddings = state.get("image_embeddings")
2802        self._i = state.get("i")
2803
2804    def clear_state(self) -> None:
2805        """Clear the stored input, tile/block geometry and embeddings. The device pool stays alive."""
2806        self._image = None
2807        self._ndim = None
2808        self._tile_shape = None
2809        self._halo = None
2810        self._image_embeddings = None
2811        self._i = None

Generates an instance segmentation with automatically generated prompts, tile or block by tile.

Like AutomaticPromptGenerator, but every tile (an image) or XYZ block (a volume) is segmented independently at native resolution, with a halo, and the results are stitched by bioimage_py.segmentation.stitch_segmentation's multicut over the halo overlap rather than by giving each candidate to exactly one tile. A volume is blocked in Z too, so an object crossing a Z seam is reconciled the same way one crossing a Y or X seam is: independently predicted in both neighbouring blocks and merged by how well their halo predictions agree, instead of being routed to a single owning tile - which a full-depth tile column cannot do for a Z seam at all. This trades some redundant halo computation (every tile/block re-encodes and re-propagates its own halo) for correctness at every seam, including ones the previous tile-column design could not represent. See finetuning/v2/evaluation/apg_3d_blockwise_ab.py for the measurements.

Every resolved device gets its own persistent (decoder, model) copy, built once and reused across every tile/block for the life of the generator, so generate keeps every device busy on a different tile/block concurrently rather than rebuilding the model per tile.

Arguments:
  • model: The UniSAM2 model (see get_unisam2_model / get_decoder).
  • predictor: The SAM2 image predictor for the interactive branch of the same model, or its video predictor for a volume.
  • device: The device the model lives on, used to resolve inference_device=None.
  • inference_device: The device(s) to run tiles/blocks on concurrently, resolved the same way as UniSAM2InstanceSegmentation's: None fans out over every visible GPU when the model is on CUDA, a single device stays on it, a sequence pins one pool member per device.
  • beta: The multicut boundary bias passed to stitch_segmentation; > 0.5 biases towards over-segmentation (cutting), < 0.5 towards under-segmentation (merging).
  • workers_per_device: How many independent (decoder, model) copies to build per resolved device. generate still gives each worker one tile/block at a time, so this only helps when a single worker leaves a device's compute or memory underused, e.g. a small model on a large GPU. Not supported together with execution='process'.
  • execution: How a tile/block's own segmentation runs. 'thread' (the default) runs every worker in this process on a concurrent.futures.ThreadPoolExecutor, sharing one Python interpreter. 'process' instead gives every device its own persistent OS process, with its own interpreter and CUDA context, so one device's per-frame propagation bookkeeping never blocks another's behind the GIL - measured at 1.5-4x faster than 'thread' once the pool is warm (bigger blocks and more of them widen the gap), with no quality change (see finetuning/v2/evaluation). The first generate call after building the generator pays extra for it, though: every worker process loads its own model from disk instead of reusing an in-memory copy the way 'thread''s pool does, which cost ~10-15s total across 4 workers in that same measurement. Worth it for a generator that runs many volumes, not necessarily for a single one-off call. Requires model_builder.
  • model_builder: Required for execution='process'. A callable (device) -> (model, predictor) that builds a fresh model and predictor pair on a device string - every worker process calls this itself rather than receiving model/predictor from the parent, because a live CUDA model cannot cross a process boundary safely.
  • process_timeout: execution='process' only. Seconds a block waits for its worker before raising, rather than hanging forever if a worker process has died or wedged.
TiledAutomaticPromptGenerator( model: torch.nn.modules.module.Module, predictor, device: Union[str, torch.device, NoneType] = None, inference_device: Union[str, torch.device, Sequence[Union[str, torch.device]], NoneType] = <object object>, beta: float = 0.5, workers_per_device: int = 1, execution: str = 'thread', model_builder: Optional[Callable[[str], tuple]] = None, process_timeout: float = 600.0)
2426    def __init__(
2427        self,
2428        model: torch.nn.Module,
2429        predictor,
2430        device: Optional[Union[str, torch.device]] = None,
2431        inference_device: Devices = USE_MODEL_DEVICE,
2432        beta: float = DEFAULT_STITCHING_BETA,
2433        workers_per_device: int = 1,
2434        execution: str = "thread",
2435        model_builder: Optional[Callable[[str], tuple]] = None,
2436        process_timeout: float = 600.0,
2437    ) -> None:
2438        self._model = model
2439        self._predictor = predictor
2440        self._device = device
2441        self._inference_device = device if inference_device is USE_MODEL_DEVICE else inference_device
2442        self._beta = beta
2443        if workers_per_device < 1:
2444            raise ValueError(f"'workers_per_device' must be >= 1, got {workers_per_device}.")
2445        self._workers_per_device = int(workers_per_device)
2446        if execution not in ("thread", "process"):
2447            raise ValueError(f"'execution' must be 'thread' or 'process', got {execution!r}.")
2448        if execution == "process":
2449            if workers_per_device != 1:
2450                raise ValueError("'workers_per_device' > 1 is not supported with execution='process'.")
2451            if model_builder is None:
2452                raise ValueError(
2453                    "execution='process' needs 'model_builder', a callable (device) -> (model, "
2454                    "predictor) every worker process calls to build its own model copy - a live CUDA "
2455                    "model cannot cross a process boundary safely."
2456                )
2457        self._execution = execution
2458        self._model_builder = model_builder
2459        self._process_timeout = float(process_timeout)
2460        self._pool: Optional[List[AutomaticPromptGenerator]] = None
2461        self._process_devices: Optional[List[str]] = None
2462        self._task_queues: Optional[list] = None
2463        self._processes: Optional[list] = None
2464        self._manager = None
2465        self._image = None
2466        self._ndim = None
2467        self._tile_shape = None
2468        self._halo = None
2469        self._verbose = False
2470        self._offload_to_cpu = None
2471        self._cache_all_slices = False
2472        self._image_embeddings = None
2473        self._i = None
def close(self) -> None:
2547    def close(self) -> None:
2548        """Stop the process pool, if `execution='process'` built one. A no-op otherwise.
2549
2550        Not required for correctness - every worker process is a daemon, so it exits with the main
2551        process - but lets a caller reclaim the devices deterministically before that.
2552        """
2553        if self._processes is None:
2554            return
2555        for task_queue in self._task_queues:
2556            task_queue.put(None)
2557        for process in self._processes:
2558            process.join(timeout=10)
2559            if process.is_alive():
2560                process.terminate()
2561        self._manager.shutdown()
2562        self._processes = None
2563        self._task_queues = None
2564        self._process_devices = None
2565        self._manager = None

Stop the process pool, if execution='process' built one. A no-op otherwise.

Not required for correctness - every worker process is a daemon, so it exits with the main process - but lets a caller reclaim the devices deterministically before that.

def initialize( self, image: numpy.ndarray, ndim: int = 2, tile_shape: Optional[tuple] = None, halo: Optional[tuple] = None, verbose: bool = False, offload_to_cpu: Optional[bool] = None, cache_all_slices: bool = False, image_embeddings: Optional[dict] = None, i: Optional[int] = None) -> None:
2567    def initialize(
2568        self,
2569        image: np.ndarray,
2570        ndim: int = 2,
2571        tile_shape: Optional[tuple] = None,
2572        halo: Optional[tuple] = None,
2573        verbose: bool = False,
2574        offload_to_cpu: Optional[bool] = None,
2575        cache_all_slices: bool = False,
2576        image_embeddings: Optional[dict] = None,
2577        i: Optional[int] = None,
2578    ) -> None:
2579        """Store the input and the tile/block geometry; the actual segmentation happens in `generate`.
2580
2581        Unlike `AutomaticPromptGenerator`, nothing is encoded here: each tile/block is encoded from
2582        scratch inside `generate`, since every tile/block needs its own encoder pass over its halo.
2583        If you give precomputed tiled `image_embeddings`, every tile/block reads its embeddings from
2584        them, and the encoder does not run.
2585
2586        Args:
2587            image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
2588            ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
2589            tile_shape: The inner tile/block shape, (y, x) for an image, always the full (z, y, x)
2590                for a volume - it is blocked in z too, not tiled in-plane only, so an object crossing
2591                a z seam is reconciled by the halo-overlap multicut the same way a y/x one is. Pass
2592                the full volume depth as the z entry for in-plane-only tiling (one whole-depth block
2593                per xy tile).
2594            halo: The halo added on each side of a tile/block, matching `tile_shape`'s axes.
2595            verbose: Whether each tile/block's generator prints progress while it segments it.
2596            offload_to_cpu: Volumes only, forwarded to every tile/block's own
2597                `AutomaticPromptGenerator.initialize`.
2598            cache_all_slices: Volumes only, forwarded the same way.
2599            image_embeddings: The optional precomputed tiled embeddings of the input. With `i`, the
2600                embeddings of the volume that contains the input slice. Their in-plane tile shape
2601                and halo must be the ones of `tile_shape` and `halo`.
2602            i: The index of the input slice in the volume of `image_embeddings`.
2603        """
2604        if ndim not in (2, 3):
2605            raise ValueError(f"Tiled prompt generation supports 2d and 3d inputs, got ndim={ndim}.")
2606        if tile_shape is None or halo is None:
2607            raise ValueError("Both 'tile_shape' and 'halo' have to be passed for the tiled generator.")
2608        if len(tile_shape) != ndim or len(halo) != ndim:
2609            raise ValueError(
2610                f"'tile_shape' and 'halo' must have {ndim} entries for a {ndim}d input, one per spatial "
2611                "axis - always (z, y, x) for a volume, never in-plane only."
2612            )
2613        tile_shape = tuple(int(t) for t in tile_shape)
2614        halo = tuple(int(h) for h in halo)
2615        if image_embeddings is not None:
2616            _check_tiled_embeddings(image_embeddings, image.shape[:ndim], tile_shape, halo, i)
2617        self._image = image
2618        self._ndim = ndim
2619        self._tile_shape = tile_shape
2620        self._halo = halo
2621        self._verbose = verbose
2622        self._offload_to_cpu = offload_to_cpu
2623        self._cache_all_slices = cache_all_slices
2624        self._image_embeddings = image_embeddings
2625        self._i = None if image_embeddings is None else i

Store the input and the tile/block geometry; the actual segmentation happens in generate.

Unlike AutomaticPromptGenerator, nothing is encoded here: each tile/block is encoded from scratch inside generate, since every tile/block needs its own encoder pass over its halo. If you give precomputed tiled image_embeddings, every tile/block reads its embeddings from them, and the encoder does not run.

Arguments:
  • image: The input image, shape (Y, X) or (Y, X, C), or the input volume, shape (Z, Y, X).
  • ndim: The number of spatial dimensions, 2 or 3. A volume requires a video predictor.
  • tile_shape: The inner tile/block shape, (y, x) for an image, always the full (z, y, x) for a volume - it is blocked in z too, not tiled in-plane only, so an object crossing a z seam is reconciled by the halo-overlap multicut the same way a y/x one is. Pass the full volume depth as the z entry for in-plane-only tiling (one whole-depth block per xy tile).
  • halo: The halo added on each side of a tile/block, matching tile_shape's axes.
  • verbose: Whether each tile/block's generator prints progress while it segments it.
  • offload_to_cpu: Volumes only, forwarded to every tile/block's own AutomaticPromptGenerator.initialize.
  • cache_all_slices: Volumes only, forwarded the same way.
  • image_embeddings: The optional precomputed tiled embeddings of the input. With i, the embeddings of the volume that contains the input slice. Their in-plane tile shape and halo must be the ones of tile_shape and halo.
  • i: The index of the input slice in the volume of image_embeddings.
@torch.no_grad()
def generate(self, *, pbar_init=None, pbar_update=None, **params) -> numpy.ndarray:
2627    @torch.no_grad()
2628    def generate(self, *, pbar_init=None, pbar_update=None, **params) -> np.ndarray:
2629        """Segment every tile/block independently and stitch them by halo-overlap multicut.
2630
2631        `propagation_waves` reaches every tile/block unchanged, but each one propagates with its
2632        own halo as a protected margin (see `AutomaticPromptGenerator._is_protected_from_pruning`):
2633        a candidate whose anchor frame or mask reaches into that margin is never pruned as a
2634        within-tile duplicate, since it is exactly the kind of prediction the halo-overlap multicut
2635        compares against the neighbouring tile/block.
2636
2637        For a volume, every tile/block is also normalized against percentile bounds computed once
2638        over the whole image (`normalization_bounds`, see `AutomaticPromptGenerator.initialize`),
2639        never its own local crop - the same statistics an untiled `AutomaticPromptGenerator` would
2640        use, so a tile's brightness/contrast does not depend on which tile it happens to be.
2641
2642        Args:
2643            pbar_init: Initialize progress with the number of tiles and a description.
2644            pbar_update: Advance progress after each completed tile, on the calling thread.
2645            params: Keyword arguments for `AutomaticPromptGenerator.generate`, applied identically
2646                to every tile/block.
2647
2648        Returns:
2649            The stitched instance segmentation, uint32 array with the shape of the input.
2650        """
2651        if self._image is None:
2652            raise RuntimeError("The segmenter has not been initialized. Call 'initialize' first.")
2653        if bp is None:
2654            raise RuntimeError("Tiled automatic prompt generation requires 'bioimage_py'. Install bioimage-py.")
2655
2656        params = dict(params)
2657        protected_margin = tuple(self._halo)
2658        # Computed once over the whole image/volume so every tile/block shares one normalization
2659        # instead of each estimating its own percentiles from its own, smaller, biased crop.
2660        encodes = self._ndim == 3 and self._image_embeddings is None  # Only the encoder uses the bounds.
2661        normalization_bounds = _volume_normalization_bounds(self._image) if encodes else None
2662
2663        if self._execution == "process":
2664            segment_block, num_workers = self._process_dispatch(params, normalization_bounds, protected_margin)
2665        else:
2666            segment_block, num_workers = self._thread_dispatch(params, normalization_bounds, protected_margin)
2667
2668        shape = self._image.shape[:self._ndim]
2669        n_tiles = int(np.prod([(size + tile - 1) // tile for size, tile in zip(shape, self._tile_shape)]))
2670        if pbar_init is not None:
2671            pbar_init(n_tiles, "APG: segmenting tiles")
2672
2673        def stitch(update):
2674            def segment_with_progress(block, block_id):
2675                result = segment_block(block, block_id)
2676                if update is not None:
2677                    update(1)
2678                return result
2679
2680            return bp.segmentation.stitch_segmentation(
2681                input=self._image,
2682                segmentation_function=segment_with_progress,
2683                shape=self._image.shape[:self._ndim],
2684                tile_shape=self._tile_shape,
2685                tile_overlap=self._halo,
2686                beta=self._beta,
2687                with_background=True,
2688                num_workers=num_workers,
2689                job_type="local",
2690            )
2691        output = _run_with_progress(stitch, pbar_update)
2692        return np.asarray(output).astype("uint32")

Segment every tile/block independently and stitch them by halo-overlap multicut.

propagation_waves reaches every tile/block unchanged, but each one propagates with its own halo as a protected margin (see AutomaticPromptGenerator._is_protected_from_pruning): a candidate whose anchor frame or mask reaches into that margin is never pruned as a within-tile duplicate, since it is exactly the kind of prediction the halo-overlap multicut compares against the neighbouring tile/block.

For a volume, every tile/block is also normalized against percentile bounds computed once over the whole image (normalization_bounds, see AutomaticPromptGenerator.initialize), never its own local crop - the same statistics an untiled AutomaticPromptGenerator would use, so a tile's brightness/contrast does not depend on which tile it happens to be.

Arguments:
  • pbar_init: Initialize progress with the number of tiles and a description.
  • pbar_update: Advance progress after each completed tile, on the calling thread.
  • params: Keyword arguments for AutomaticPromptGenerator.generate, applied identically to every tile/block.
Returns:

The stitched instance segmentation, uint32 array with the shape of the input.

def get_state(self) -> dict:
2782    def get_state(self) -> dict:
2783        """Return the input, the tile/block geometry and the embeddings, so `set_state` can restore them."""
2784        return {
2785            "image": self._image, "ndim": self._ndim, "tile_shape": self._tile_shape, "halo": self._halo,
2786            "image_embeddings": self._image_embeddings, "i": self._i,
2787        }

Return the input, the tile/block geometry and the embeddings, so set_state can restore them.

def set_state(self, state: dict) -> None:
2789    def set_state(self, state: dict) -> None:
2790        """Restore the input, the tile/block geometry and the embeddings `initialize` stored.
2791
2792        Args:
2793            state: The state, as returned by `get_state`.
2794        """
2795        if "image" not in state:
2796            raise ValueError("A tiled prompt-generator state must hold its 'image'.")
2797        self._image = state["image"]
2798        self._ndim = state.get("ndim", 2)
2799        self._tile_shape = state.get("tile_shape")
2800        self._halo = state.get("halo")
2801        self._image_embeddings = state.get("image_embeddings")
2802        self._i = state.get("i")

Restore the input, the tile/block geometry and the embeddings initialize stored.

Arguments:
  • state: The state, as returned by get_state.
def clear_state(self) -> None:
2804    def clear_state(self) -> None:
2805        """Clear the stored input, tile/block geometry and embeddings. The device pool stays alive."""
2806        self._image = None
2807        self._ndim = None
2808        self._tile_shape = None
2809        self._halo = None
2810        self._image_embeddings = None
2811        self._i = None

Clear the stored input, tile/block geometry and embeddings. The device pool stays alive.