micro_sam.v2.prompt_based_segmentation
1import gc 2import queue 3import ctypes 4import hashlib 5import platform 6import threading 7import contextlib 8from copy import copy 9from concurrent import futures 10from dataclasses import dataclass 11from typing import Callable, List, Optional, Tuple, Union 12 13import numpy as np 14 15import torch 16 17from micro_sam.v2.util import Devices 18from micro_sam.util import device_type 19from micro_sam.v1.prompt_based_segmentation import _process_box, _compute_logits_from_mask 20from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_spatial_numpy, ResizeLongestSideTransforms 21 22 23@dataclass(frozen=True) 24class _PromptOperation: 25 """One successful mutation of a SAM2 video-predictor prompt state. 26 27 The active prompt maps below are sufficient for deduplication, but not for reconstruction: 28 SAM2 uses the preceding decoder logits when a point set is replaced, and batching points changes 29 the decoder result. Replaying these operations verbatim preserves both pieces of state. 30 """ 31 32 kind: str 33 frame_id: int 34 object_id: int 35 clear_old_points: bool = True 36 points: Optional[np.ndarray] = None # (y, x), before conversion to SAM2's (x, y). 37 point_labels: Optional[np.ndarray] = None 38 box: Optional[np.ndarray] = None # (y0, x0, y1, x1), before SAM2 box processing. 39 mask_signature: Optional[str] = None 40 mask: Optional[np.ndarray] = None # Prepared in SAM2's padded square frame. 41 42 def copied(self): 43 """Return a snapshot whose arrays cannot be changed through caller-owned inputs.""" 44 return _PromptOperation( 45 kind=self.kind, frame_id=self.frame_id, object_id=self.object_id, 46 clear_old_points=self.clear_old_points, 47 points=None if self.points is None else self.points.copy(), 48 point_labels=None if self.point_labels is None else self.point_labels.copy(), 49 box=None if self.box is None else self.box.copy(), 50 mask_signature=self.mask_signature, 51 mask=None if self.mask is None else self.mask.copy(), 52 ) 53 54 55def _trim_cpu_heap(): 56 """Return freed CPU heap to the OS on glibc-based Linux. It does nothing elsewhere. 57 58 'gc.collect' drops the Python references and frees the tensors, but glibc keeps the freed pages 59 in its arenas rather than returning them to the OS, so RSS stays high on native CPU systems (the 60 low-RAM target). 'malloc_trim' releases that free heap, so clearing the embedding cache actually 61 lowers RSS. 62 """ 63 if platform.system() != "Linux": 64 return 65 try: 66 ctypes.CDLL("libc.so.6").malloc_trim(0) 67 except (OSError, AttributeError): 68 pass 69 70 71def _device_context(device): 72 """Make a worker thread's default CUDA device the one its tile's state lives on.""" 73 device = torch.device(device) 74 return torch.cuda.device(device) if device.type == "cuda" else contextlib.nullcontext() 75 76 77def map_jobs_over_devices(devices, jobs: List, function: Callable, update_progress=None) -> List: 78 """Run independent jobs over one worker per device, each taking the next job once it is free. 79 80 The results come back in the order the jobs were given, never the order the devices finished in, 81 because a caller that merges them may break ties by position. 82 83 Args: 84 devices: The devices to spread the jobs over, one worker each. 85 jobs: The jobs, passed to `function` one at a time. 86 function: Called as `function(worker_id, job)`, with the index of the device it runs on. 87 update_progress: Optional callback, called with 1 after every finished job. 88 89 Returns: 90 One result per job, in the order the jobs were given. 91 """ 92 jobs = list(jobs) 93 if not jobs: 94 return [] 95 96 results = [None] * len(jobs) 97 n_workers = min(len(devices), len(jobs)) 98 if n_workers < 2: 99 for index, job in enumerate(jobs): 100 results[index] = function(0, job) 101 if update_progress is not None: 102 update_progress(1) 103 return results 104 105 pending = queue.Queue() 106 for index, job in enumerate(jobs): 107 pending.put((index, job)) 108 109 def run_worker(worker_id): 110 with _device_context(devices[worker_id]): 111 while True: 112 try: 113 index, job = pending.get_nowait() 114 except queue.Empty: 115 break 116 results[index] = function(worker_id, job) 117 if update_progress is not None: 118 update_progress(1) 119 120 with futures.ThreadPoolExecutor(max_workers=n_workers) as pool: 121 for task in [pool.submit(run_worker, worker_id) for worker_id in range(n_workers)]: 122 task.result() 123 return results 124 125 126def _free_device_memory(): 127 """Return freed tensor memory to the allocator / OS after clearing cached embeddings. 128 129 Covers GPU (empty the CUDA / MPS caching allocator) and native CPU systems (trim the glibc heap 130 so RSS actually drops, not just the Python-level references). 131 """ 132 gc.collect() 133 if torch.cuda.is_available(): 134 torch.cuda.empty_cache() 135 elif getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available(): 136 torch.mps.empty_cache() 137 _trim_cpu_heap() 138 139 140def _crop_to_original_shape(mask, shape): 141 """Crop a SAM2 video-predictor mask back to the original slice shape. 142 143 The video predictor pads non-square frames to a square of side max(H, W) (padding appended at the 144 bottom/right) and returns masks at that padded size. The image content occupies the top-left 145 [0:H, 0:W] region, so cropping recovers the original (H, W) mask. For square volumes this is a no-op. 146 """ 147 return mask[:shape[0], :shape[1]] 148 149 150def _tile_index_for(tiling, halo, y, x): 151 """Return the id of the tile whose inner (halo-free) block contains the point (y, x).""" 152 for tile_id in range(tiling.number_of_blocks): 153 inner = tiling.get_block_with_halo(tile_id, list(halo)).inner_block 154 if inner.begin[0] <= y < inner.end[0] and inner.begin[1] <= x < inner.end[1]: 155 return tile_id 156 return 0 157 158 159def _inner_block_slices(tiling, halo, tile_id): 160 """Return the (local, global) inner-block slices for placing a tile result into the full array.""" 161 block = tiling.get_block_with_halo(tile_id, list(halo)) 162 local = tuple(slice(b, e) for b, e in zip(block.inner_block_local.begin, block.inner_block_local.end)) 163 glob = tuple(slice(b, e) for b, e in zip(block.inner_block.begin, block.inner_block.end)) 164 return local, glob 165 166 167def _box_to_tiles(tiling, halo, box): 168 """Assign a box to every tile whose inner block it overlaps, clipped to the tile's outer block. 169 170 A single box can span several tiles (e.g. at a 4-tile junction); each tile segments the box's 171 portion that falls in it and the results are unioned. The box and the returned clipped boxes are 172 in (y0, x0, y1, x1) order. 173 174 Returns: 175 Mapping from tile id to the clipped box (in global coordinates). 176 """ 177 y0, x0, y1, x1 = box 178 assignments = {} 179 for tile_id in range(tiling.number_of_blocks): 180 block = tiling.get_block_with_halo(tile_id, list(halo)) 181 inner, outer = block.inner_block, block.outer_block 182 # Skip tiles whose inner (halo-free) block the box does not overlap. 183 if y1 <= inner.begin[0] or y0 >= inner.end[0] or x1 <= inner.begin[1] or x0 >= inner.end[1]: 184 continue 185 assignments[tile_id] = np.array([ 186 max(y0, outer.begin[0]), max(x0, outer.begin[1]), 187 min(y1, outer.end[0]), min(x1, outer.end[1]), 188 ]) 189 return assignments 190 191 192def _crop_mask_to_tile(tiling, halo, tile_id, mask): 193 """Crop a full-plane 2d mask to a tile's outer (halo-included) block, so it stays aligned with 194 the tile's sub-volume.""" 195 outer = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 196 y0, x0 = int(outer.begin[0]), int(outer.begin[1]) 197 y1, x1 = int(outer.end[0]), int(outer.end[1]) 198 return np.asarray(mask)[y0:y1, x0:x1] 199 200 201def _clone_image_predictor(predictor, model: torch.nn.Module): 202 """Copy an image predictor onto a replica model, with per-image state cleared.""" 203 from micro_sam.v2.util import configure_image_predictor 204 205 replica = copy(predictor) 206 replica.__dict__.pop("_micro_sam_predictor_devices", None) # do not share the source cache 207 replica.model = model 208 replica.reset_predictor() 209 return configure_image_predictor(replica) 210 211 212def _get_image_predictor_devices(predictor, devices: Devices) -> List[Tuple]: 213 """Create and cache one image-predictor replica per selected device.""" 214 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 215 216 resolved_devices = _resolve_devices(predictor.model, devices) 217 cache_key = tuple(str(device) for device in resolved_devices) 218 cached = getattr(predictor, "_micro_sam_predictor_devices", None) 219 if cached is not None and cached[0] == cache_key: 220 return cached[1] 221 222 predictor_devices = [ 223 (predictor if model is predictor.model else _clone_image_predictor(predictor, model), device) 224 for model, device in _prepare_models(predictor.model, resolved_devices) 225 ] 226 predictor._micro_sam_predictor_devices = (cache_key, predictor_devices) 227 return predictor_devices 228 229 230def promptable_segmentation_2d( 231 predictor, 232 image: Optional[np.ndarray] = None, 233 points: Optional[np.ndarray] = None, 234 labels: Optional[np.ndarray] = None, 235 boxes: Optional[np.ndarray] = None, 236 masks: Optional[np.ndarray] = None, 237 batched: Optional[bool] = None, 238): 239 """@private""" 240 from micro_sam.v2.util import configure_image_predictor 241 configure_image_predictor(predictor) 242 243 if image is not None: 244 if image.ndim == 3 and image.shape[0] == 3 and image.shape[-1] != 3: 245 # Channel-last RGB; 'to_image' handles grayscale and channel-last inputs. 246 image = image.transpose(1, 2, 0) 247 248 from micro_sam.v2.normalization import to_image 249 from micro_sam.v2.util import encode_image 250 encode_image(predictor, to_image(image)) 251 252 have_points = points is not None and len(points) > 0 253 have_boxes = boxes is not None and len(boxes) > 0 254 if have_points: 255 assert len(points) == len(labels) 256 257 if not have_points and not have_boxes: 258 return 259 260 # Batched multi-object segmentation: each positive point and each box defines a separate object. 261 if batched: 262 return _batched_promptable_segmentation_2d(predictor, points, labels, boxes, masks) 263 264 # SAM2 concatenates boxes and points along the prompt axis, so boxes cannot share a point batch. 265 if have_points and have_boxes and len(boxes) > 1: 266 print("Point prompts can only be combined with a single box/shape prompt. Skipping segmentation.") 267 return None 268 269 # A polygon or ellipse yields a filled mask, which SAM2 takes as a low-res logit prompt. 270 if masks is not None and any(m is not None for m in masks): 271 return _promptable_segmentation_2d_with_masks(predictor, points, labels, boxes, masks) 272 273 kwargs = {} 274 if have_points: 275 kwargs["point_coords"] = points[:, ::-1].copy() # Contiguous, which torch wants. 276 kwargs["point_labels"] = labels 277 if have_boxes: 278 shape = predictor._orig_hw[0] 279 kwargs["box"] = np.array([_process_box(b, shape) for b in boxes]) 280 281 masks, scores, logits = predictor.predict( 282 multimask_output=False, # NOTE: Hard-coded to 'False' atm. 283 **kwargs 284 ) 285 286 n_points = len(points) if have_points else 0 287 n_boxes = len(boxes) if have_boxes else 0 288 289 if n_points > 1 or n_boxes > 1: # Has more than one object, expected instance segmentation. 290 out = np.zeros(masks.shape[-2:]) 291 for i, curr_mask in enumerate(masks, start=1): 292 out[curr_mask.squeeze() > 0] = i 293 else: 294 out = masks.squeeze() 295 296 # HACK: Hard-code the expected data type for labels for napari labels layer: uint8 297 out = out.astype("uint8") 298 299 return out 300 301 302def _promptable_segmentation_2d_with_masks(predictor, points, labels, boxes, masks): 303 """Single-image promptable segmentation that uses polygon/ellipse mask prompts. 304 305 A napari polygon or ellipse yields both a bounding box and a filled mask (from 306 'shape_layer_to_prompts'); the mask is passed to SAM2 as a low-res logit prompt ('mask_input') 307 alongside its box, mirroring the SAM v1 behaviour. Objects are segmented one at a time (as in v1) 308 so a mask prompt only conditions its own object. 309 """ 310 shape = predictor._orig_hw[0] 311 have_points = points is not None and len(points) > 0 312 have_boxes = boxes is not None and len(boxes) > 0 313 314 def _predict_one(box=None, mask=None, extra_points=None, extra_labels=None): 315 kwargs = {"multimask_output": False} 316 if box is not None: 317 kwargs["box"] = np.array([_process_box(box, shape)]) 318 if mask is not None: 319 kwargs["mask_input"] = _compute_logits_from_mask(mask) 320 if extra_points is not None and len(extra_points) > 0: 321 kwargs["point_coords"] = extra_points[:, ::-1].copy() 322 kwargs["point_labels"] = extra_labels 323 out_masks, _, _ = predictor.predict(**kwargs) 324 return out_masks.squeeze() 325 326 # Points with a single shape; the caller has already rejected more than one box. 327 if have_points and have_boxes: 328 seg = _predict_one(box=boxes[0], mask=masks[0], extra_points=points, extra_labels=labels) 329 return (seg > 0).astype("uint8") 330 331 # One object per shape (each box, with its mask if it is a polygon/ellipse). 332 out = np.zeros(tuple(shape), dtype="uint8") 333 for seg_id, (box, mask) in enumerate(zip(boxes, masks), 1): 334 seg = _predict_one(box=box, mask=mask) 335 out[seg > 0] = seg_id 336 return out 337 338 339def _batched_promptable_segmentation_2d(predictor, points, labels, boxes, masks=None): 340 """Batched 2D segmentation where each positive point and each box defines a separate object. 341 342 Negative points are shared as negative prompts for every object. A box that comes from a 343 polygon/ellipse (its entry in 'masks' is not None) also carries a soft mask-logit cue. This 344 matches the batched convention of the SAM v1 annotator and the 3D unified segment widget. 345 """ 346 shape = predictor._orig_hw[0] 347 348 points = np.zeros((0, 2)) if points is None else np.asarray(points) 349 labels = np.zeros((0,), dtype=int) if labels is None else np.asarray(labels) 350 positive_points = points[labels == 1] 351 negative_points = points[labels != 1] 352 n_neg = len(negative_points) 353 354 seg = np.zeros(tuple(shape), dtype="uint32") 355 object_id = 0 356 357 def _assign(masks): 358 nonlocal object_id 359 masks = np.asarray(masks) 360 if masks.ndim == 3: # A single object is returned as (C, H, W); add the object dimension. 361 masks = masks[None] 362 for curr_mask in masks: 363 object_id += 1 364 seg[curr_mask[0] > 0] = object_id 365 366 # One object per positive point, each combined with the shared negative points. 367 if len(positive_points) > 0: 368 obj_points, obj_labels = [], [] 369 for pos in positive_points: 370 pts = np.concatenate([pos[None], negative_points], axis=0) if n_neg else pos[None] 371 lbs = np.concatenate([[1], np.zeros(n_neg, dtype=int)]) if n_neg else np.array([1]) 372 obj_points.append(pts) 373 obj_labels.append(lbs) 374 # Reverse the last axis to convert (row, col) to the (x, y) convention SAM2 expects. 375 batched_points = np.stack(obj_points)[..., ::-1].copy() 376 batched_labels = np.stack(obj_labels) 377 # Keep 'masks': the box branch below needs the mask prompts, not this prediction. 378 point_masks, _, _ = predictor.predict( 379 point_coords=batched_points, point_labels=batched_labels, multimask_output=False, 380 ) 381 _assign(point_masks) 382 383 # One object per box, each combined with the shared negative points. 384 if boxes is not None and len(boxes) > 0: 385 have_box_masks = masks is not None and any(m is not None for m in masks) 386 if have_box_masks: 387 # A batched predict shares one 'mask_input', so each box needs its own pass. 388 for bidx, box in enumerate(boxes): 389 kwargs = {"box": np.array([_process_box(box, shape)]), "multimask_output": False} 390 if masks[bidx] is not None: 391 kwargs["mask_input"] = _compute_logits_from_mask(np.asarray(masks[bidx])) 392 if n_neg: 393 kwargs["point_coords"] = negative_points[None][..., ::-1].copy() 394 kwargs["point_labels"] = np.zeros((1, n_neg), dtype=int) 395 out_masks, _, _ = predictor.predict(**kwargs) 396 _assign(out_masks) 397 else: 398 processed_boxes = np.array([_process_box(b, shape) for b in boxes]) 399 kwargs = {"box": processed_boxes, "multimask_output": False} 400 if n_neg: 401 neg = np.repeat(negative_points[None], len(processed_boxes), axis=0)[..., ::-1].copy() 402 kwargs["point_coords"] = neg 403 kwargs["point_labels"] = np.zeros((len(processed_boxes), n_neg), dtype=int) 404 out_masks, _, _ = predictor.predict(**kwargs) 405 _assign(out_masks) 406 407 if object_id == 0: 408 return None 409 410 return seg 411 412 413def tiled_promptable_segmentation_2d( 414 predictor, 415 image_embeddings: dict, 416 points: Optional[np.ndarray] = None, 417 labels: Optional[np.ndarray] = None, 418 boxes: Optional[np.ndarray] = None, 419 masks: Optional[np.ndarray] = None, 420 batched: Optional[bool] = None, 421 devices: Devices = None, 422): 423 """Tiled 2d promptable segmentation for the SAM2 image predictor. 424 425 Routes the prompts to the tile-column they fall in, sets that tile's precomputed embeddings on 426 the predictor (via `set_precomputed`), runs `promptable_segmentation_2d` on the tile, and 427 stitches the per-tile mask into the full image. Points are in (y, x) order, as passed by the 428 annotator. Same return convention as `promptable_segmentation_2d`. 429 430 Independent active tiles run concurrently on persistent predictor replicas. By default all 431 visible CUDA devices are used; pass `devices` to select or restrict them. 432 """ 433 from bioimage_cpp.utils import Blocking 434 from micro_sam.v2.util import set_precomputed 435 436 feats = image_embeddings["features"] 437 shape = tuple(int(s) for s in feats.attrs["shape"]) 438 tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"]) 439 halo = tuple(int(s) for s in feats.attrs["halo"]) 440 tiling = Blocking([0, 0], list(shape), list(tile_shape)) 441 442 have_points = points is not None and len(points) > 0 443 have_boxes = boxes is not None and len(boxes) > 0 444 if not have_points and not have_boxes: 445 return None 446 447 # Grouped by tile, so an object is segmented in every tile that holds one of its prompts. 448 # Points are (y, x), boxes (y0, x0, y1, x1), and a mask is cropped to the tile's outer block. 449 tile_points, tile_labels, tile_boxes, tile_masks, tile_box_ids = {}, {}, {}, {}, {} 450 if have_points: 451 for point, label in zip(np.asarray(points), np.asarray(labels)): 452 tid = _tile_index_for(tiling, halo, int(round(point[0])), int(round(point[1]))) 453 tile_points.setdefault(tid, []).append(point) 454 tile_labels.setdefault(tid, []).append(label) 455 if have_boxes: 456 for bidx, box in enumerate(boxes): 457 box_mask = masks[bidx] if masks is not None else None 458 # A box can span several tiles. Segment its clipped portion in each (boxes are y0,x0,y1,x1). 459 for tid, clipped in _box_to_tiles(tiling, halo, np.asarray(box)).items(): 460 tile_boxes.setdefault(tid, []).append(clipped) 461 tile_box_ids.setdefault(tid, []).append(bidx + 1) 462 tile_masks.setdefault(tid, []).append( 463 None if box_mask is None else _crop_mask_to_tile(tiling, halo, tid, box_mask) 464 ) 465 466 tile_jobs = {} 467 for tile_id in sorted(set(tile_points) | set(tile_boxes)): 468 tpoints = np.asarray(tile_points.get(tile_id, [])).reshape(-1, 2) 469 tlabels = np.asarray(tile_labels.get(tile_id, []), dtype=int) 470 tboxes = tile_boxes.get(tile_id, []) 471 # A tile with only negative points has nothing to segment. 472 if not ((tlabels == 1).any() or len(tboxes) > 0): 473 continue 474 475 outer = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 476 y0, x0 = int(outer.begin[0]), int(outer.begin[1]) 477 local_points = (tpoints - np.array([y0, x0])) if len(tpoints) else tpoints 478 local_boxes = [b - np.array([y0, x0, y0, x0]) for b in tboxes] if tboxes else None 479 local_masks = tile_masks.get(tile_id) if tboxes else None 480 tile_jobs[tile_id] = local_points, tlabels, local_boxes, local_masks 481 482 predictor_devices = _get_image_predictor_devices(predictor, devices) 483 # Spread the active tiles round-robin. Their ids are sparse, so mapping by 'tile_id % n_devices' 484 # would run e.g. the tiles 0, 2, 4 on one device and leave the others idle. 485 groups = {} 486 for position, tile_id in enumerate(sorted(tile_jobs)): 487 worker_id = position % len(predictor_devices) 488 groups.setdefault(worker_id, []).append(tile_id) 489 490 def run_group(worker_id, tile_ids): 491 local_predictor, _ = predictor_devices[worker_id] 492 results = [] 493 for tile_id in tile_ids: 494 local_points, local_labels, local_boxes, local_masks = tile_jobs[tile_id] 495 set_precomputed(local_predictor, image_embeddings, tile_id=tile_id) 496 tile_seg = promptable_segmentation_2d( 497 local_predictor, image=None, points=local_points, labels=local_labels, 498 boxes=local_boxes, masks=local_masks, batched=batched, 499 ) 500 results.append((tile_id, tile_seg)) 501 return results 502 503 if len(groups) < 2: 504 results = run_group(*next(iter(groups.items()))) if groups else [] 505 else: 506 results = [] 507 with futures.ThreadPoolExecutor(max_workers=len(groups)) as pool: 508 tasks = [pool.submit(run_group, worker_id, tile_ids) for worker_id, tile_ids in groups.items()] 509 for task in tasks: 510 results.extend(task.result()) 511 512 out = np.zeros(shape, dtype="uint32") 513 found = False 514 for tile_id, tile_seg in sorted(results): 515 if tile_seg is None: 516 continue 517 518 local, glob = _inner_block_slices(tiling, halo, tile_id) 519 region = tile_seg[local] 520 # The tile counts its boxes from 1, so map them back to the global box ids. 521 if not batched and tile_id in tile_box_ids: 522 region = np.array([0] + tile_box_ids[tile_id], dtype="uint32")[region] 523 # Unioned by id, so an object spanning tiles is merged across the boundary. 524 sub = out[glob] 525 positive = region > 0 526 sub[positive] = region[positive] 527 found = True 528 529 return out if found else None 530 531 532class PromptableSegmentation3D: 533 """Promptable segmentation class for volumetric data. 534 """ 535 # On the class, so that an instance built without '__init__' still reads it. 536 release_stale_mask_memory = False 537 538 def __init__( 539 self, predictor, volume, volume_embeddings, device=None, 540 offload_state_to_cpu=None, max_cached_frames=None, release_stale_mask_memory=False, 541 ): 542 from micro_sam.v2.util import _get_device 543 self.predictor = predictor 544 self.volume = volume 545 self.volume_embeddings = volume_embeddings 546 # 'device=None' uses the predictor's auto-detected device. 547 self.device = device 548 # Bounds device memory on cuda. Off on mps: unified memory saves nothing, and SAM2's 549 # non-blocking transfer back races there, which gives intermittent garbage masks. 550 is_mps = device_type(_get_device(device)) == "mps" 551 self.offload_state_to_cpu = (not is_mps) if offload_state_to_cpu is None else offload_state_to_cpu 552 # A pass walks every slice, so a feature cache shorter than the volume is never hit. 553 self.max_cached_frames = max_cached_frames 554 # Saves device memory, but only for a caller that resets the tracking before prompting again. 555 self.release_stale_mask_memory = release_stale_mask_memory 556 557 if self.volume.ndim not in (3, 4): 558 raise AssertionError(f"The volume must be (Z, Y, X) or (Z, Y, X, C), got shape {self.volume.shape}") 559 560 self.init_predictor() 561 562 # What the SAM2 state already holds, so a re-run pushes only the newly placed prompts. 563 self._pushed_points = {} # (object_id, frame_id) -> set of (y, x, label) 564 self._pushed_boxes = {} # (object_id, frame_id) -> set of box corner tuples 565 self._pushed_masks = {} # (object_id, frame_id) -> mask digest -> prepared mask 566 # Successful predictor calls in their original order and batching. The active maps above 567 # deliberately omit prompts that SAM2 replaced; the history retains their decoder effects. 568 self._prompt_history = [] 569 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 570 self._prompt_signatures = set() 571 self._image_style_trafo = None # Built lazily for the per-slice mask refinement. 572 573 def init_predictor(self): 574 self.inference_state = self.predictor.init_state( 575 volume=self.volume, volume_embeddings=self.volume_embeddings, device=self.device, 576 offload_state_to_cpu=self.offload_state_to_cpu, max_cached_frames=self.max_cached_frames, 577 ) 578 579 def _clear_pushed_prompts(self): 580 # The dedup bookkeeping describes the SAM2 state, so it must never outlive it. 581 self._pushed_points = {} 582 self._pushed_boxes = {} 583 self._pushed_masks = {} 584 self._prompt_history = [] 585 self._prompt_signatures = set() 586 587 def _anchor_per_object(self): 588 """The earliest slice each object is conditioned on, keyed by its object id.""" 589 anchors = {} 590 for key in (*self._pushed_points, *self._pushed_boxes, *self._pushed_masks): 591 object_id, frame_id = key 592 anchors[object_id] = min(anchors.get(object_id, frame_id), frame_id) 593 return anchors 594 595 def _replay_prompts(self, snapshot, object_ids): 596 """Replay these objects' successful predictor operations onto a fresh state. 597 598 The snapshot is taken before the first replay, because resetting the state also clears the 599 history this reads, and a later group's prompts would be gone by then. Preserving operation 600 order, point batching and replacement flags is necessary because SAM2 feeds the previous 601 decoder logits into the next point/box operation. 602 """ 603 self.reset_predictor() 604 skip_output = getattr(self.predictor, "skip_prompt_output", None) 605 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 606 for operation in snapshot: 607 if operation.object_id in object_ids: 608 self._apply_prompt_operation(operation) 609 610 def _apply_prompt_operation(self, operation): 611 """Apply and record one predictor operation, updating active state only after it succeeds.""" 612 operation = operation.copied() 613 key = (operation.object_id, operation.frame_id) 614 615 if operation.kind == "points_or_box": 616 if operation.box is not None and not operation.clear_old_points: 617 raise ValueError("SAM2 requires 'clear_old_points=True' whenever a box is given.") 618 kwargs = {} 619 if operation.points is not None and len(operation.points): 620 if operation.point_labels is None or len(operation.points) != len(operation.point_labels): 621 raise AssertionError("The number of points and labels do not match.") 622 # SAM2 expects (x, y). This unconditional copy also removes negative strides for a 623 # single point, whose reversed view numpy can otherwise still call contiguous. 624 kwargs["points"] = np.array(operation.points[:, ::-1], dtype="float32") 625 kwargs["labels"] = np.array(operation.point_labels, dtype="int32") 626 if operation.box is not None: 627 kwargs["box"] = np.array([_process_box(operation.box, self.volume.shape[1:3])]) 628 if not kwargs: 629 return 630 631 self.predictor.add_new_points_or_box( 632 inference_state=self.inference_state, 633 frame_idx=operation.frame_id, 634 obj_id=operation.object_id, 635 clear_old_points=operation.clear_old_points, 636 **kwargs, 637 ) 638 639 # Mirror SAM2's mutually exclusive active input maps. A replacement discards the active 640 # point/box set, but its earlier decoder effect remains in '_prompt_history'. 641 if operation.clear_old_points: 642 self._pushed_points.pop(key, None) 643 self._pushed_boxes.pop(key, None) 644 self._pushed_masks.pop(key, None) 645 if operation.points is not None and len(operation.points): 646 seen = self._pushed_points.setdefault(key, set()) 647 for (y, x), label in zip(operation.points, operation.point_labels): 648 seen.add((int(round(float(y))), int(round(float(x))), int(label))) 649 if operation.box is not None: 650 signature = tuple(np.round(operation.box).astype(int).tolist()) 651 self._pushed_boxes.setdefault(key, set()).add(signature) 652 653 elif operation.kind == "mask": 654 if operation.mask is None or operation.mask_signature is None: 655 raise ValueError("A mask operation requires a prepared mask and its signature.") 656 self.predictor.add_new_mask( 657 inference_state=self.inference_state, 658 frame_idx=operation.frame_id, 659 obj_id=operation.object_id, 660 mask=operation.mask, 661 ) 662 self._pushed_points.pop(key, None) 663 self._pushed_boxes.pop(key, None) 664 self._pushed_masks[key] = {operation.mask_signature: operation.mask.copy()} 665 else: 666 raise ValueError(f"Unknown prompt operation kind '{operation.kind}'.") 667 668 self._prompt_history.append(operation) 669 670 def sync_prompt_state(self, signatures): 671 """Discard the persistent state when prompts were removed or changed since the last round. 672 673 The dedup in 'add_*_prompts' only detects added prompts. Additive refinement (the current 674 prompts are a superset of the previous ones) therefore keeps the state and pushes just the 675 new prompts, while a removal, relabel or move replays everything from scratch. 676 677 Args: 678 signatures: Hashable descriptors of every prompt currently in the annotation layers. 679 """ 680 signatures = set(signatures) 681 if not self._prompt_signatures.issubset(signatures): 682 self.reset_predictor() 683 self._prompt_signatures = signatures 684 685 def release(self): 686 """Drop the tracked objects and the cached slice features, keeping the allocator's cache. 687 688 What a caller that builds another state of the same size on this device right afterwards 689 needs: the blocks go back to the caching allocator, which hands them to the next state. 690 Emptying that cache instead would make every rebuild pay for a fresh allocation. 691 """ 692 self.predictor.reset_state(self.inference_state) 693 self._clear_pushed_prompts() 694 # 'reset_state' clears the tracking outputs, not the cached features or the encoding they share. 695 self.inference_state["cached_features"] = {} 696 self.inference_state.pop("shared_pos_enc", None) 697 698 def reset_predictor(self): 699 self.release() 700 _free_device_memory() 701 702 def reset_tracking(self): 703 """Clear the tracked objects, keeping the features of the volume they were tracked on. 704 705 What a further propagation pass over the same volume needs, and all it needs: those features 706 are a function of the volume's embeddings, not of the objects. `reset_predictor` drops them 707 as well and hands the memory back to the allocator, which together cost more than the passes 708 themselves once there are many. The cache stays bounded by MAX_CACHED_FRAMES either way. 709 """ 710 self.predictor.reset_state(self.inference_state) 711 self._clear_pushed_prompts() 712 713 def get_progress_total(self, z_range=None): 714 """Return the number of slice propagation steps for the requested z range. 715 716 Objects conditioned on different slices take one propagation pass each, see 'propagate_prompts'. 717 """ 718 slices = int(self.volume.shape[0]) if z_range is None else int(z_range[1] - z_range[0] + 1) 719 return slices * max(1, len(set(self._anchor_per_object().values()))) 720 721 def _broadcast(self, value, n): 722 """Broadcast a scalar frame/object id to a length-'n' list (or validate a length-1 or -'n' 723 sequence). Guards against the earlier bug where a single frame id zipped against several 724 points silently dropped all but the first point.""" 725 if isinstance(value, (list, tuple, np.ndarray)): 726 values = [int(v) for v in value] 727 if len(values) == 1: 728 values = values * n 729 if len(values) != n: 730 raise ValueError(f"Expected 1 or {n} ids, got {len(values)}.") 731 return values 732 return [int(value)] * n 733 734 def add_point_prompts( 735 self, 736 frame_ids: Union[int, List[int]], 737 points: np.ndarray, 738 point_labels: np.ndarray, 739 object_id: Optional[Union[List[int], int]] = None, 740 multiple_objects: bool = False, # Enables multi-object segmentation. 741 ): 742 """Add point prompts (in (y, x) order) to the persistent SAM2 state, one object at a time. 743 744 Several points can be added in a single call. A point already pushed in an earlier call (same 745 object, frame, rounded position and label) is skipped, so re-running with the full prompt set 746 only pushes newly placed points. New points are appended ('clear_old_points=False') so they 747 correct the running segmentation instead of replacing it. 748 """ 749 if multiple_objects and object_id is not None: 750 raise ValueError("Cannot enable multi-object segmentation and also pass a fixed object id.") 751 if points is None or len(points) == 0: 752 return 753 754 points = np.asarray(points) 755 point_labels = np.asarray(point_labels) 756 if points.ndim != 2 or points.shape[1] != 2: 757 raise ValueError("'points' must have shape (N, 2).") 758 if len(points) != len(point_labels): 759 raise AssertionError("The number of points and labels do not match.") 760 761 n = len(points) 762 frame_ids = self._broadcast(frame_ids, n) 763 object_ids = self._broadcast(1 if object_id is None else object_id, n) 764 765 # The per-prompt masks are not read here, and consolidating them costs more than the prompt. 766 skip_output = getattr(self.predictor, "skip_prompt_output", None) 767 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 768 for frame_id, (y, x), label, obj_id in zip(frame_ids, points, point_labels, object_ids): 769 signature = (int(round(float(y))), int(round(float(x))), int(label)) 770 if signature in self._pushed_points.get((obj_id, frame_id), set()): 771 continue 772 self._apply_prompt_operation( 773 _PromptOperation( 774 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 775 clear_old_points=False, 776 points=np.array([[y, x]], dtype="float32"), 777 point_labels=np.array([label], dtype="int32"), 778 ) 779 ) 780 781 def add_prompt_set( 782 self, 783 frame_id: int, 784 points: Optional[np.ndarray] = None, 785 point_labels: Optional[np.ndarray] = None, 786 box: Optional[np.ndarray] = None, 787 object_id: int = 1, 788 clear_old_points: bool = True, 789 ): 790 """Condition one object on a whole prompt set at once, in a single SAM2 call. 791 792 'add_point_prompts' pushes one point at a time, and 'add_box_prompts' pushes a box and then 793 replays the points it had to clear. That is what an annotator placing corrections needs: each 794 push returns the running segmentation, and re-running only sends what is new. A caller that 795 has the whole set up front pays for it, because every push re-runs the mask decoder on the 796 conditioning frame - eight of them for a box and seven points. SAM2 takes the set in one 797 call instead, with the box as the first two coordinates, which is also the order it wants. 798 799 The prompts are recorded in the same bookkeeping the incremental methods use, so the anchor 800 of each object and a replay onto a fresh state still see them. 801 802 Args: 803 frame_id: The slice to condition. 804 points: The points, (N, 2) in (y, x) order. None conditions on the box alone. 805 point_labels: One label per point: 1 positive, 0 negative. 806 box: An optional box, in (y0, x0, y1, x1) order. 807 object_id: The object being conditioned. 808 clear_old_points: Whether the push replaces what this object already carries on the 809 frame. SAM2 requires it whenever a box is given. False appends, which is how a 810 points-only push is added after a box. 811 """ 812 has_points = points is not None and len(points) > 0 813 if not has_points and box is None: 814 return 815 frame_id, object_id = int(frame_id), int(object_id) 816 if box is not None and not clear_old_points: 817 # Validate before touching bookkeeping or invoking SAM2, whose implementation rejects 818 # this combination as well. 819 raise ValueError("SAM2 requires 'clear_old_points=True' whenever a box is given.") 820 821 normalized_points, normalized_labels = None, None 822 if has_points: 823 points = np.asarray(points, dtype="float32").reshape(-1, 2) 824 if point_labels is None: 825 raise ValueError("'point_labels' is required when points are given.") 826 point_labels = np.asarray(point_labels, dtype="int32").reshape(-1) 827 if len(points) != len(point_labels): 828 raise AssertionError("The number of points and labels do not match.") 829 normalized_points, normalized_labels = points, point_labels 830 normalized_box = None if box is None else np.asarray(box, dtype="float32").reshape(4) 831 832 # The preview mask is discarded, as in the incremental methods. 833 skip_output = getattr(self.predictor, "skip_prompt_output", None) 834 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 835 self._apply_prompt_operation( 836 _PromptOperation( 837 kind="points_or_box", frame_id=frame_id, object_id=object_id, 838 clear_old_points=bool(clear_old_points), 839 points=normalized_points, point_labels=normalized_labels, box=normalized_box, 840 ) 841 ) 842 843 def add_box_prompts( 844 self, 845 frame_ids: Union[int, List[int]], 846 boxes: Optional[np.ndarray] = None, 847 object_id: Optional[Union[int, List[int]]] = None, 848 ): 849 """Add box prompts (in (y0, x0, y1, x1) order) to the persistent SAM2 state. 850 851 A box is pushed at most once per (object, frame); re-running with the same box is a no-op. 852 SAM2 requires the box before any point on the same object/frame, so a box clears existing 853 points ('clear_old_points=True'); we re-add any already-pushed points afterwards so a box and 854 its correction points combine regardless of the order they were drawn in. 855 """ 856 if boxes is None or len(boxes) == 0: 857 return 858 859 boxes = [np.asarray(b) for b in boxes] 860 n = len(boxes) 861 frame_ids = self._broadcast(frame_ids, n) 862 object_ids = self._broadcast(1 if object_id is None else object_id, n) 863 864 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 865 # consolidating it costs a pass over every object of the state. 866 skip_output = getattr(self.predictor, "skip_prompt_output", None) 867 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 868 for frame_id, box, obj_id in zip(frame_ids, boxes, object_ids): 869 key = (obj_id, frame_id) 870 signature = tuple(np.round(box).astype(int).tolist()) 871 if signature in self._pushed_boxes.get(key, set()): 872 continue 873 existing_points = sorted(self._pushed_points.get(key, set())) 874 self._apply_prompt_operation( 875 _PromptOperation( 876 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 877 clear_old_points=True, box=np.asarray(box, dtype="float32").reshape(4), 878 ) 879 ) 880 for y, x, label in existing_points: 881 self._apply_prompt_operation( 882 _PromptOperation( 883 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 884 clear_old_points=False, 885 points=np.array([[y, x]], dtype="float32"), 886 point_labels=np.array([label], dtype="int32"), 887 ) 888 ) 889 890 def _prepare_mask(self, mask): 891 """Bring a full-resolution 2d boolean mask into the padded-square frame the video predictor 892 sees, so SAM2's own (direct) resize inside 'add_new_mask' is a no-op and the mask stays 893 aligned with the resize-longest-side + pad the frames use.""" 894 mask = np.asarray(mask).astype(bool) 895 target = self.predictor.image_size 896 if mask.shape[-2:] == (target, target): 897 return mask 898 prepared, _ = resize_longest_side_and_pad_spatial_numpy(mask, target, is_label=True) 899 return prepared.astype(bool) 900 901 def add_mask_prompts( 902 self, 903 frame_ids: Union[int, List[int]], 904 masks: Optional[List[np.ndarray]] = None, 905 object_id: Optional[Union[int, List[int]]] = None, 906 refine: bool = True, 907 ): 908 """Add mask prompts (full-resolution 2d boolean masks) to the persistent SAM2 state. 909 910 A napari polygon or ellipse is filled into a mask (from 'shape_layer_to_prompts'). We first 911 refine the drawn shape into the object on its seed frame (box + soft mask-logit cue, as in 912 the per-slice path), then seed propagation with the refined mask - so the seed slice matches 913 the per-slice result instead of reproducing the raw outline. SAM2's video predictor conditions 914 a frame on either a mask or points/box (not both), so a mask prompt does not combine with 915 points on the same object/frame. A mask already pushed (same object, frame, content) is 916 skipped so re-runs only add newly drawn masks. 917 918 Args: 919 frame_ids: The slice each mask conditions, one per mask or one for all of them. 920 masks: The masks, at the volume's full resolution. 921 object_id: The object each mask belongs to, one per mask or one for all of them. 922 refine: Whether to refine each mask into the object on its frame first. True for a shape 923 somebody drew; False for a mask that is already a prediction for this frame, which a 924 second refinement would only pull away from what it was accepted as. 925 """ 926 if masks is None or len(masks) == 0: 927 return 928 929 masks = [np.asarray(m) for m in masks] 930 n = len(masks) 931 frame_ids = self._broadcast(frame_ids, n) 932 object_ids = self._broadcast(1 if object_id is None else object_id, n) 933 934 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 935 # consolidating it costs a pass over every object of the state. 936 skip_output = getattr(self.predictor, "skip_prompt_output", None) 937 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 938 for frame_id, mask, obj_id in zip(frame_ids, masks, object_ids): 939 key = (obj_id, frame_id) 940 # A stable digest, so the signature does not change between processes. 941 signature = hashlib.sha1(np.ascontiguousarray(mask).tobytes()).hexdigest() 942 if signature in self._pushed_masks.get(key, {}): 943 continue 944 945 # Refined on the seed frame first, so the propagation starts from the object rather 946 # than from the drawn shape. The box is the filled mask's extent. 947 ys, xs = np.nonzero(mask) 948 if len(ys) == 0: 949 continue 950 if refine: 951 box = np.array([xs.min(), ys.min(), xs.max(), ys.max()], dtype="float32") # (x0,y0,x1,y1) 952 mask = self._image_style_predict(frame_id, box=box, mask=mask) 953 954 prepared = self._prepare_mask(mask) 955 self._apply_prompt_operation( 956 _PromptOperation( 957 kind="mask", frame_id=frame_id, object_id=obj_id, 958 mask_signature=signature, mask=prepared, 959 ) 960 ) 961 962 def _propagate_in_direction( 963 self, 964 reverse, 965 update_progress=None, 966 early_stop_patience=None, 967 z_range=None, 968 seen_frames=None, 969 mask_threshold=0.0, 970 return_logits=False, 971 ): 972 """Run SAM2 propagation in one temporal direction, optionally stopping early. 973 974 Each step of the SAM2 video predictor runs the full memory attention and mask decoder 975 for one frame, which is the dominant cost of volumetric segmentation (especially on CPU). 976 Early stopping reads the masks we already compute and breaks out of the propagation once 977 the object has clearly left the volume, so we do not keep running the network on frames 978 that no longer contain the object. 979 980 Args: 981 reverse: Propagate backwards in time (towards lower slice indices) if True. 982 update_progress: Optional callback invoked with the number of newly processed frames. 983 early_stop_patience: If given, stop this direction after this many consecutive frames 984 in which every tracked object's mask is empty (i.e. the object has left the volume). 985 'None' disables early stopping and propagates to the end of the volume. 986 z_range: If given, an inclusive '(z_min, z_max)' bound on the slice indices propagation 987 may cover. Propagation stops at the range edge in this direction. 'None' propagates 988 to the end of the volume. 989 seen_frames: Optional set of already-counted frame indices, shared across both directions, 990 so a frame processed in both (the conditioning frame) advances 'update_progress' once. 991 mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too. 992 return_logits: Return the float32 mask logits instead of the boolean masks. 993 994 Returns: 995 Mapping from frame index to per-object boolean masks (or logits), in the order frames were yielded. 996 """ 997 video_segments = {} 998 consecutive_empty = 0 999 for out_frame_idx, out_obj_ids, out_mask_logits in self.predictor.propagate_in_video( 1000 self.inference_state, reverse=reverse, release_stale_mask_memory=self.release_stale_mask_memory, 1001 ): 1002 # Hard z-range bound: stop once propagation would leave the user-selected slice range. 1003 if z_range is not None and not (z_range[0] <= out_frame_idx <= z_range[1]): 1004 break 1005 1006 # One transfer for the whole frame, rather than a host round trip per object. 1007 if return_logits: 1008 logits = out_mask_logits.float().cpu().numpy() 1009 binary = logits > mask_threshold 1010 else: 1011 binary = (out_mask_logits > mask_threshold).cpu().numpy() 1012 frame_output = logits if return_logits else binary 1013 video_segments[out_frame_idx] = {obj_id: frame_output[i] for i, obj_id in enumerate(out_obj_ids)} 1014 # Counted once across both directions, which both yield the conditioning frame. 1015 if update_progress is not None and (seen_frames is None or out_frame_idx not in seen_frames): 1016 update_progress(1) 1017 if seen_frames is not None: 1018 seen_frames.add(out_frame_idx) 1019 1020 # A run of empty frames, not one: SAM2 can drop a mask momentarily and recover it. 1021 if early_stop_patience is not None: 1022 frame_is_empty = not binary.any() 1023 consecutive_empty = consecutive_empty + 1 if frame_is_empty else 0 1024 if consecutive_empty >= early_stop_patience: 1025 break 1026 1027 # The edge slice is stored, so stop before the predictor pays for a discarded frame. 1028 if z_range is not None and out_frame_idx == (z_range[0] if reverse else z_range[1]): 1029 break 1030 1031 return video_segments 1032 1033 def propagate_prompts( 1034 self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0, return_logits=False 1035 ): 1036 """Propagate the pushed prompts through the volume, one pass per conditioned slice. 1037 1038 SAM2 propagates every object of a state from the earliest slice any of them is conditioned on, 1039 and skips the backward pass entirely when that slice is 0. Objects anchored later would be 1040 tracked - and have those results written into their memory - before they are conditioned, and 1041 would never be propagated backwards at all. So objects that share an anchor are propagated 1042 together and the rest get a state of their own. 1043 1044 SAM2 builds its memory from the sigmoid of the logits, not from the thresholded masks. So 1045 thresholding the returned logits at 't' gives the masks of 'mask_threshold=t', except on the 1046 slices that early stopping skipped. SAM2 sets all logits of a slice to -1024 where it predicts 1047 that the object is absent, so a negative threshold does not recover such slices. 1048 1049 Args: 1050 update_progress: Optional callback invoked with the number of newly processed slices. 1051 early_stop_patience: Stop a direction after this many consecutive empty slices. 1052 'None' propagates to the end of the volume. 1053 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1054 mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too. 1055 return_logits: Return the float32 mask logits instead of the boolean masks. This keeps 1056 4 bytes per pixel, object and slice, so use it only for a few objects. 1057 1058 Returns: 1059 Mapping from slice index to {object id: mask (1, H, W)}. The video predictor pads non-square 1060 slices to a square, so crop each mask to '[:, :H, :W]' of the original slice shape. 1061 """ 1062 propagate_kwargs = dict( 1063 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1064 mask_threshold=mask_threshold, return_logits=return_logits, 1065 ) 1066 groups = {} 1067 for object_id, frame in self._anchor_per_object().items(): 1068 groups.setdefault(frame, []).append(object_id) 1069 if len(groups) <= 1: 1070 return self._propagate_both_directions(**propagate_kwargs) 1071 1072 # The active maps intentionally omit replaced prompts. Reconstruct from successful calls so 1073 # point batches, replacement boundaries and the previous-logit chain stay unchanged. 1074 snapshot = tuple(operation.copied() for operation in self._prompt_history) 1075 prompt_signatures = set(self._prompt_signatures) 1076 video_segments = {} 1077 for object_ids in groups.values(): 1078 self._replay_prompts(snapshot, set(object_ids)) 1079 for frame, per_object in self._propagate_both_directions(**propagate_kwargs).items(): 1080 video_segments.setdefault(frame, {}).update(per_object) 1081 1082 self._replay_prompts(snapshot, set().union(*groups.values())) 1083 self._prompt_signatures = prompt_signatures 1084 return video_segments 1085 1086 def _propagate_both_directions(self, **propagate_kwargs): 1087 # Shared across both directions, so the conditioning frame is counted once. 1088 seen_frames = set() 1089 forward_video_segments = self._propagate_in_direction( 1090 reverse=False, seen_frames=seen_frames, **propagate_kwargs 1091 ) 1092 1093 reverse_video_segments = {} 1094 if len(forward_video_segments) < self.volume.shape[0]: # Only if the forward pass fell short. 1095 reverse_video_segments = self._propagate_in_direction( 1096 reverse=True, seen_frames=seen_frames, **propagate_kwargs 1097 ) 1098 # Reversed, so it stitches onto the forward propagation. 1099 reverse_video_segments = dict(reversed(list(reverse_video_segments.items()))) 1100 1101 video_segments = {**reverse_video_segments, **forward_video_segments} 1102 return video_segments 1103 1104 def _image_features_for_frame(self, frame_idx): 1105 """Build (image_embed, high_res_feats) for one slice from its precomputed features. 1106 1107 Mirrors 'SAM2ImagePredictor.set_image', including the no-memory embedding that marks a 1108 memory-free image prediction. Couples to SAM2 predictor internals ('_get_image_feature', 1109 'no_mem_embed'), consistent with how the video-predictor subclass already uses them. 1110 """ 1111 predictor = self.predictor 1112 _, _, vision_feats, _, feat_sizes = predictor._get_image_feature(self.inference_state, int(frame_idx), 1) 1113 if predictor.directly_add_no_mem_embed: 1114 vision_feats[-1] = vision_feats[-1] + predictor.no_mem_embed 1115 feats = [ 1116 feat.permute(1, 2, 0).view(1, -1, *fs) for feat, fs in zip(vision_feats[::-1], feat_sizes[::-1]) 1117 ][::-1] 1118 return feats[-1], feats[:-1] 1119 1120 def _image_style_predict(self, frame_idx, box=None, mask=None, points=None, labels=None): 1121 """Image-predictor-style single-slice prediction using this slice's precomputed features. 1122 1123 Runs the SAM2 prompt encoder + mask decoder with a box + soft mask-logit cue (and any 1124 correction points), so the decoder refines the prompt into the object. This reproduces the 1125 2d behaviour, unlike the video predictor's 'add_new_mask', which hard-conditions on the drawn 1126 mask and returns it unchanged. Returns a full-resolution boolean segmentation for the slice. 1127 """ 1128 predictor = self.predictor 1129 device = self.inference_state["device"] 1130 orig_hw = tuple(int(s) for s in self.volume.shape[1:3]) 1131 image_size = predictor.image_size 1132 scale = float(image_size) / max(orig_hw) # Resize-longest, into the model frame. 1133 1134 image_embed, high_res_feats = self._image_features_for_frame(frame_idx) 1135 1136 # Box (labels 2, 3) plus any correction points, in (x, y), scaled into the model frame. 1137 coords, labs = [], [] 1138 if box is not None: 1139 box = np.asarray(box, dtype="float32").reshape(2, 2) * scale 1140 coords.append(torch.as_tensor(box, dtype=torch.float, device=device)) 1141 labs.append(torch.tensor([2, 3], dtype=torch.int, device=device)) 1142 if points is not None and len(points) > 0: 1143 pts = np.asarray(points, dtype="float32") * scale 1144 coords.append(torch.as_tensor(pts, dtype=torch.float, device=device)) 1145 labs.append(torch.as_tensor(np.asarray(labels), dtype=torch.int, device=device)) 1146 concat_points = (torch.cat(coords)[None], torch.cat(labs)[None]) if coords else None 1147 1148 # Soft low-res mask logits (1, 256, 256) from the filled shape, matching the frame's resize+pad. 1149 mask_input = None 1150 if mask is not None: 1151 logits = _compute_logits_from_mask(np.asarray(mask)) 1152 mask_input = torch.as_tensor(logits, dtype=torch.float, device=device)[None] 1153 1154 sparse, dense = predictor.sam_prompt_encoder(points=concat_points, boxes=None, masks=mask_input) 1155 low_res_masks, _, _, _ = predictor.sam_mask_decoder( 1156 image_embeddings=image_embed, 1157 image_pe=predictor.sam_prompt_encoder.get_dense_pe(), 1158 sparse_prompt_embeddings=sparse, 1159 dense_prompt_embeddings=dense, 1160 multimask_output=False, 1161 repeat_image=False, 1162 high_res_features=high_res_feats, 1163 ) 1164 1165 if self._image_style_trafo is None: 1166 self._image_style_trafo = ResizeLongestSideTransforms(resolution=image_size, mask_threshold=0.0) 1167 seg = self._image_style_trafo.postprocess_masks(low_res_masks, orig_hw) 1168 return (seg.squeeze() > 0.0).cpu().numpy().astype("uint32") 1169 1170 def _refine_slice_from_mask(self, frame_idx, boxes=None, masks=None, points=None, labels=None): 1171 """Per-slice refinement entry: pair the filled mask with its own box (the shape layer's 1172 'boxes'/'masks' are index-aligned) and refine it into the object via '_image_style_predict'.""" 1173 idx = next(i for i, m in enumerate(masks) if m is not None) 1174 box = boxes[idx] if boxes is not None and idx < len(boxes) else None 1175 return self._image_style_predict(frame_idx, box=box, mask=masks[idx], points=points, labels=labels) 1176 1177 def segment_slice( 1178 self, 1179 frame_idx: int, 1180 points: Optional[np.ndarray] = None, 1181 labels: Optional[np.ndarray] = None, 1182 boxes: Optional[List] = None, 1183 masks: Optional[List] = None, 1184 object_id: int = 1, 1185 ): 1186 """Segment a single slice using SAM2 video predictor. 1187 1188 Args: 1189 frame_idx: Slice index to segment. 1190 points: Point prompts (N, 2) array. 1191 labels: Point labels (N,) array. 1192 boxes: List of box prompts. 1193 masks: List of mask prompts (can be None). 1194 object_id: Object ID to use for the segmentation (default: 1). 1195 1196 Returns: 1197 Segmentation mask for the slice (2D array), or None if no valid prompts provided. 1198 """ 1199 have_points = points is not None and len(points) > 0 1200 have_boxes = boxes is not None and len(boxes) > 0 1201 have_masks = masks is not None and any(m is not None for m in masks) 1202 1203 if not have_points and not have_boxes and not have_masks: 1204 return None 1205 1206 try: 1207 if have_masks: 1208 # Refined the way the 2d predictor does, rather than through 'add_new_mask', which 1209 # hard-conditions on the drawn shape and returns it verbatim. 1210 seg = self._refine_slice_from_mask( 1211 frame_idx, boxes=boxes, masks=masks, 1212 points=points if have_points else None, labels=labels if have_points else None, 1213 ) 1214 else: 1215 box = boxes[0] if have_boxes else None 1216 _, out_obj_ids, out_mask_logits = self.predictor.add_new_points_or_box( 1217 inference_state=self.inference_state, 1218 frame_idx=frame_idx, 1219 obj_id=object_id, 1220 points=points if have_points else None, 1221 labels=labels if have_points else None, 1222 box=box, 1223 ) 1224 1225 mask_logits = out_mask_logits[0] # (num_objects, 1, H, W), so this is the first object. 1226 seg = (mask_logits.squeeze() > 0.0).cpu().numpy() 1227 1228 # Crop back to the original slice shape (the video predictor pads non-square frames). 1229 seg = _crop_to_original_shape(seg, self.volume.shape[1:3]).astype("uint32") 1230 1231 finally: 1232 # Clear this object's prompts and their bookkeeping, so the next round starts fresh. 1233 self.predictor.reset_state(self.inference_state) 1234 self._clear_pushed_prompts() 1235 1236 return seg 1237 1238 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1239 """Propagate the pushed prompts and paint the objects into one label volume. 1240 1241 Where objects overlap, the object with the higher id wins. 1242 1243 Args: 1244 update_progress: Optional callback invoked with the number of newly processed slices. 1245 early_stop_patience: Stop a direction after this many consecutive empty slices. 1246 'None' propagates to the end of the volume. 1247 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1248 mask_threshold: The logit threshold that binarizes the masks. 1249 1250 Returns: 1251 The label volume, with the shape of the input volume. 1252 """ 1253 video_segments = self.propagate_prompts( 1254 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1255 mask_threshold=mask_threshold, 1256 ) 1257 1258 # Indexed by slice id, so the frames early stopping skipped stay background rather than 1259 # shifting the rest out of alignment. 1260 shape = self.volume.shape[1:3] 1261 segmentation = np.zeros((self.volume.shape[0],) + tuple(shape), dtype="uint64") 1262 for slice_idx, instances in video_segments.items(): 1263 per_slice_seg = segmentation[slice_idx] 1264 for instance_idx, instance_mask in instances.items(): 1265 mask = _crop_to_original_shape(instance_mask.squeeze(), shape) 1266 per_slice_seg[mask] = instance_idx 1267 1268 return segmentation 1269 1270 1271class ReplicatedPromptableSegmentation3D: 1272 """One `PromptableSegmentation3D` per inference device over the same volume, for independent passes. 1273 1274 Automatic prompt generation propagates a volume in passes that share nothing but the volume and 1275 its embeddings: each conditions its own objects on one slice and tracks them to both ends. So a 1276 pass goes to whichever device is free, with one video-predictor state per device rather than one 1277 in total. `TiledPromptableSegmentation3D` spreads tiles for the same reason; this spreads the 1278 passes of a volume that is not tiled, where one state covers the whole volume. 1279 1280 Device memory is the cost: a state per device instead of a state in total. Pass a single device 1281 to give that back. 1282 1283 Args: 1284 predictor: The SAM2 video predictor. 1285 volume: The input volume, shape (Z, Y, X). 1286 volume_embeddings: The precomputed 3d embeddings. 1287 devices: Devices the passes are spread over. By default all visible CUDA devices are used 1288 when the predictor is on CUDA. Pass a single device to pin the propagation to it. 1289 """ 1290 1291 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1292 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1293 1294 self._predictor_devices = _prepare_models(predictor, _resolve_devices(predictor, devices)) 1295 self.volume = volume 1296 self.volume_embeddings = volume_embeddings 1297 self._kwargs = kwargs 1298 # Built lazily, so a run with fewer passes than devices never pays for a state it cannot use. 1299 self._segmenters = {} 1300 1301 def _get_segmenter(self, worker_id): 1302 if worker_id not in self._segmenters: 1303 predictor, device = self._predictor_devices[worker_id] 1304 self._segmenters[worker_id] = PromptableSegmentation3D( 1305 predictor, self.volume, self.volume_embeddings, device=device, **self._kwargs 1306 ) 1307 return self._segmenters[worker_id] 1308 1309 @property 1310 def predictor_devices(self): 1311 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1312 return self._predictor_devices 1313 1314 def map_passes(self, jobs: List, function: Callable, update_progress=None) -> List: 1315 """Run one job per pass, one worker per device, each taking the next job once it is free. 1316 1317 `function` is called as `function(segmenter, job)` with the worker's own state, so a job may 1318 prompt and propagate it freely. The results keep the order the jobs were given in, which the 1319 merge needs: it breaks score ties by record order. 1320 """ 1321 devices = [device for _, device in self._predictor_devices] 1322 return map_jobs_over_devices( 1323 devices, jobs, lambda worker_id, job: function(self._get_segmenter(worker_id), job), 1324 update_progress=update_progress, 1325 ) 1326 1327 def reset_predictor(self): 1328 """Free every worker's video-predictor state.""" 1329 for segmenter in self._segmenters.values(): 1330 segmenter.reset_predictor() 1331 self._segmenters = {} 1332 1333 1334class TiledPromptableSegmentation3D: 1335 """Tiled promptable segmentation for volumetric data. 1336 1337 Routes each prompt to the in-plane tile-column it falls in, runs a per-tile 1338 `PromptableSegmentation3D` on the tile's sub-volume (reusing the precomputed tiled embeddings), 1339 and stitches the per-tile results into the full volume. Exposes the same interface as 1340 `PromptableSegmentation3D`, so it is a drop-in replacement when the embeddings are tiled. 1341 1342 Args: 1343 predictor: The SAM2 video predictor. 1344 volume: The input volume, shape (Z, Y, X). 1345 volume_embeddings: The precomputed tiled 3d embeddings (with per-tile `features`/`pos_enc`/ 1346 `fpn` groups and `shape`/`tile_shape`/`halo` attrs). See `precompute_image_embeddings`. 1347 devices: Devices used for independent tile columns. By default all visible CUDA devices 1348 are used when the predictor is on CUDA. Pass a single device to pin inference to it. 1349 """ 1350 1351 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1352 from bioimage_cpp.utils import Blocking 1353 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1354 1355 resolved_devices = _resolve_devices(predictor, devices) 1356 self._predictor_devices = _prepare_models(predictor, resolved_devices) 1357 1358 self.predictor = predictor 1359 self.volume = volume 1360 self.volume_embeddings = volume_embeddings 1361 self._kwargs = kwargs 1362 1363 feats = volume_embeddings["features"] 1364 self.shape = tuple(int(s) for s in feats.attrs["shape"]) 1365 self.tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"]) 1366 self.halo = tuple(int(s) for s in feats.attrs["halo"]) 1367 self.tiling = Blocking([0, 0], list(self.shape[1:]), list(self.tile_shape)) 1368 1369 # State per (tile, worker), built lazily for the tiles that actually receive prompts. Keyed by 1370 # the worker as well, so 'map_tile_jobs' can put a tile's passes on several devices at once. 1371 self._segmenters = {} 1372 # Device assigned to each active tile, see '_worker_id'. 1373 self._tile_workers = {} 1374 # The worker a thread is running as, which overrides the per-tile assignment while it is set. 1375 self._active_worker = threading.local() 1376 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 1377 self._prompt_signatures = set() 1378 1379 def init_predictor(self): 1380 # Per-tile inference states are created lazily in '_get_segmenter'. 1381 pass 1382 1383 def sync_prompt_state(self, signatures): 1384 """Discard the per-tile states when prompts were removed or changed since the last round. 1385 1386 See `PromptableSegmentation3D.sync_prompt_state`. The prompt set is compared once for the 1387 whole volume, because a moved prompt can change which tile it belongs to. 1388 1389 Args: 1390 signatures: Hashable descriptors of every prompt currently in the annotation layers. 1391 """ 1392 signatures = set(signatures) 1393 if not self._prompt_signatures.issubset(signatures): 1394 self.reset_predictor() 1395 self._prompt_signatures = signatures 1396 1397 def reset_predictor(self): 1398 # Each holds an inference state and an embedding cache; they are rebuilt lazily. 1399 for segmenter in self._segmenters.values(): 1400 segmenter.reset_predictor() 1401 self._segmenters = {} 1402 self._tile_workers = {} 1403 self._prompt_signatures = set() 1404 _free_device_memory() 1405 1406 def get_progress_total(self, z_range=None): 1407 """Return tile-slice propagation steps for the currently active tiles.""" 1408 return sum(segmenter.get_progress_total(z_range) for segmenter in self._segmenters.values()) 1409 1410 def _tile_index(self, y, x): 1411 """Return the id of the tile whose inner (halo-free) block contains the point (y, x).""" 1412 for tile_id in range(self.tiling.number_of_blocks): 1413 inner = self.tiling.get_block_with_halo(tile_id, list(self.halo)).inner_block 1414 if inner.begin[0] <= y < inner.end[0] and inner.begin[1] <= x < inner.end[1]: 1415 return tile_id 1416 return 0 1417 1418 def _worker_id(self, tile_id): 1419 """Return the device a tile is bound to, assigned round-robin when the tile is first used. 1420 1421 The tile state (inference state + embedding cache) lives on one device, so the affinity is 1422 kept for the tile's lifetime. Assigning by 'tile_id % n_devices' instead would leave devices 1423 idle, because the active tile ids are sparse (e.g. the tiles 0, 2, 4 share one residue). 1424 1425 A thread running as a worker uses that worker's device instead, so two workers can hold the 1426 same tile without either reaching into the other's state. 1427 """ 1428 bound = getattr(self._active_worker, "index", None) 1429 if bound is not None: 1430 return bound 1431 if tile_id not in self._tile_workers: 1432 self._tile_workers[tile_id] = len(self._tile_workers) % len(self._predictor_devices) 1433 return self._tile_workers[tile_id] 1434 1435 @contextlib.contextmanager 1436 def _as_worker(self, worker_id): 1437 """Run this thread as one worker: its device, and its own state for whatever tile it touches.""" 1438 self._active_worker.index = worker_id 1439 try: 1440 with _device_context(self._predictor_devices[worker_id][1]): 1441 yield 1442 finally: 1443 self._active_worker.index = None 1444 1445 def _outer_offset(self, tile_id): 1446 """Return the (y0, x0) origin of the tile's outer (halo-included) block.""" 1447 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1448 return int(outer.begin[0]), int(outer.begin[1]) 1449 1450 def _get_segmenter(self, tile_id): 1451 key = (tile_id, self._worker_id(tile_id)) 1452 if key not in self._segmenters: 1453 from micro_sam.v2.util import _load_list_datasets 1454 1455 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1456 bb = (slice(int(outer.begin[0]), int(outer.end[0])), slice(int(outer.begin[1]), int(outer.end[1]))) 1457 sub_volume = np.ascontiguousarray(self.volume[:, bb[0], bb[1]]) 1458 1459 feats = self.volume_embeddings["features"] 1460 tile_dataset = feats[str(tile_id)] 1461 # Lazy, so the tile-column is streamed a frame at a time rather than materialised. 1462 tile_embeddings = { 1463 "features": tile_dataset, 1464 "pos_enc": _load_list_datasets(self.volume_embeddings["pos_enc"], str(tile_id), lazy_loading=True), 1465 "fpn": _load_list_datasets(self.volume_embeddings["fpn"], str(tile_id), lazy_loading=True), 1466 "input_size": tile_dataset.attrs["input_size"], 1467 "original_size": tile_dataset.attrs["original_size"], 1468 } 1469 predictor, device = self._predictor_devices[key[1]] 1470 self._segmenters[key] = PromptableSegmentation3D( 1471 predictor, sub_volume, tile_embeddings, device=device, **self._kwargs 1472 ) 1473 return self._segmenters[key] 1474 1475 def _inner_slices(self, tile_id): 1476 """Return the (local, global) inner-block slices for placing a tile result into the volume.""" 1477 block = self.tiling.get_block_with_halo(tile_id, list(self.halo)) 1478 local = tuple(slice(b, e) for b, e in zip(block.inner_block_local.begin, block.inner_block_local.end)) 1479 glob = tuple(slice(b, e) for b, e in zip(block.inner_block.begin, block.inner_block.end)) 1480 return local, glob 1481 1482 def map_tiles( 1483 self, tile_ids: List[int], function: Callable, update_progress: Optional[Callable[[int], None]] = None, 1484 ) -> List[Tuple]: 1485 """Run one job per tile, one worker per device, each pulling the next tile once it is free. 1486 1487 A tile that already holds a state keeps the device that state lives on. An unassigned tile is 1488 bound to whichever worker picks it up, so tiles with very different costs (as in automatic 1489 prompt generation, where a tile costs what its candidates cost) balance over the devices 1490 instead of being dealt out round-robin before their cost is known. 1491 """ 1492 tile_ids = list(tile_ids) 1493 if not tile_ids: 1494 return [] 1495 1496 preassigned = {} 1497 unassigned = queue.Queue() 1498 for tile_id in tile_ids: 1499 if tile_id in self._tile_workers: 1500 preassigned.setdefault(self._tile_workers[tile_id], []).append(tile_id) 1501 else: 1502 unassigned.put(tile_id) 1503 1504 def run_worker(worker_id, worker_update=None): 1505 def call(tile_id): 1506 return function(tile_id) if worker_update is None else function(tile_id, worker_update) 1507 1508 results = [] 1509 with self._as_worker(worker_id): 1510 for tile_id in preassigned.get(worker_id, []): 1511 results.append((tile_id, call(tile_id))) 1512 while True: 1513 try: 1514 tile_id = unassigned.get_nowait() 1515 except queue.Empty: 1516 break 1517 self._tile_workers[tile_id] = worker_id 1518 results.append((tile_id, call(tile_id))) 1519 return results 1520 1521 if len(self._predictor_devices) < 2: 1522 return sorted(run_worker(0, update_progress), key=lambda result: result[0]) 1523 1524 progress_queue = queue.Queue() 1525 1526 def forward_progress(): 1527 increment = 0 1528 while True: 1529 try: 1530 increment += int(progress_queue.get_nowait()) 1531 except queue.Empty: 1532 break 1533 if increment: 1534 update_progress(increment) 1535 1536 results = [] 1537 n_workers = len(self._predictor_devices) 1538 with futures.ThreadPoolExecutor(max_workers=n_workers) as pool: 1539 worker_update = progress_queue.put if update_progress is not None else None 1540 tasks = [pool.submit(run_worker, worker_id, worker_update) for worker_id in range(n_workers)] 1541 pending = set(tasks) 1542 while pending: 1543 done, pending = futures.wait(pending, timeout=0.05, return_when=futures.FIRST_COMPLETED) 1544 forward_progress() 1545 for task in done: 1546 results.extend(task.result()) 1547 forward_progress() 1548 return sorted(results, key=lambda result: result[0]) 1549 1550 @property 1551 def predictor_devices(self): 1552 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1553 return self._predictor_devices 1554 1555 @property 1556 def active_tiles(self) -> List[int]: 1557 """The tiles that currently hold a state, in ascending order.""" 1558 return sorted({tile_id for tile_id, _ in self._segmenters}) 1559 1560 def map_tile_jobs(self, jobs: List, function: Callable, update_progress=None) -> List: 1561 """Run jobs that each name a tile, one worker per device, each on its own state for that tile. 1562 1563 Unlike `map_tiles`, several jobs of one tile can run at once: a job prompts the state of its 1564 tile *on its worker's device*, so a single tile whose work dwarfs the others spreads over the 1565 devices instead of pinning them to one. The extra states are what it costs, and a job that 1566 moves to a new device re-reads that tile's features, so give a job enough work to pay for it. 1567 1568 `function` is called as `function(job)`, and `update_progress` from the worker rather than 1569 from the caller's thread - unlike `map_tiles`, whose callback the GUI drives. 1570 """ 1571 devices = [device for _, device in self._predictor_devices] 1572 1573 def run(worker_id, job): 1574 with self._as_worker(worker_id): 1575 return function(job) 1576 1577 return map_jobs_over_devices(devices, jobs, run, update_progress=update_progress) 1578 1579 def reset_tile_tracking(self, tile_id: int) -> None: 1580 """Reset one tile's tracked objects, keeping its cached encoding. A no-op before its first use.""" 1581 segmenter = self._segmenters.get((tile_id, self._worker_id(tile_id))) 1582 if segmenter is not None: 1583 segmenter.reset_tracking() 1584 1585 def propagate_tile(self, tile_id: int, update_progress=None, early_stop_patience=None, z_range=None): 1586 """Propagate one tile's prompts, returning its own segments and its outer (halo-included) block. 1587 1588 Never merges across tiles, unlike `predict`, which stitches by object identity: it is for a 1589 caller whose object ids are tile-local, e.g. automatic prompt generation, where a candidate 1590 belongs to exactly one tile and its id would otherwise collide with another tile's. 1591 """ 1592 video_segments = self._get_segmenter(tile_id).propagate_prompts( 1593 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1594 ) 1595 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1596 bounding_box = tuple(slice(int(b), int(e)) for b, e in zip(outer.begin, outer.end)) 1597 return video_segments, bounding_box 1598 1599 def release_tile(self, tile_id: int) -> None: 1600 """Free one tile's video-predictor state, leaving the other tiles' states alive. 1601 1602 Keeps the CUDA cache rather than emptying it: the next state on this device is the same size, 1603 so the allocator reuses the blocks, and a collection from every worker after every job costs 1604 more than it frees - it holds the interpreter lock while the other devices wait for work. 1605 """ 1606 segmenter = self._segmenters.pop((tile_id, self._worker_id(tile_id)), None) 1607 self._tile_workers.pop(tile_id, None) 1608 if segmenter is not None: 1609 segmenter.release() 1610 1611 def segment_slice(self, frame_idx, points=None, labels=None, boxes=None, masks=None, object_id=1): 1612 """Segment a single slice. Points are (x, y), boxes (x0, y0, x1, y1), as passed by the annotator. 1613 1614 Groups the prompts by the tile they fall in, segments every tile with a positive cue, and 1615 unions the per-tile masks - so an object spanning tiles is segmented on both sides. 1616 """ 1617 have_points = points is not None and len(points) > 0 1618 have_boxes = boxes is not None and len(boxes) > 0 1619 have_masks = masks is not None and any(m is not None for m in masks) 1620 if not have_points and not have_boxes and not have_masks: 1621 return None 1622 1623 tile_points, tile_labels, tile_boxes, tile_masks = {}, {}, {}, {} 1624 if have_points: 1625 for point, label in zip(np.asarray(points), np.asarray(labels)): 1626 tid = self._tile_index(int(round(point[1])), int(round(point[0]))) # (y, x) from (x, y) 1627 tile_points.setdefault(tid, []).append(point) 1628 tile_labels.setdefault(tid, []).append(label) 1629 if have_boxes: 1630 for bidx, box in enumerate(boxes): 1631 box = np.asarray(box) # (x0, y0, x1, y1) 1632 box_yx = np.array([box[1], box[0], box[3], box[2]]) 1633 box_mask = masks[bidx] if masks is not None else None 1634 for tid, clipped in _box_to_tiles(self.tiling, self.halo, box_yx).items(): 1635 tile_boxes.setdefault(tid, []).append(np.array([clipped[1], clipped[0], clipped[3], clipped[2]])) 1636 tile_masks.setdefault(tid, []).append( 1637 None if box_mask is None else _crop_mask_to_tile(self.tiling, self.halo, tid, box_mask) 1638 ) 1639 1640 tile_jobs = {} 1641 for tile_id in sorted(set(tile_points) | set(tile_boxes)): 1642 tpoints = np.asarray(tile_points.get(tile_id, [])).reshape(-1, 2) 1643 tlabels = np.asarray(tile_labels.get(tile_id, []), dtype=int) 1644 tboxes = tile_boxes.get(tile_id, []) 1645 if not ((tlabels == 1).any() or len(tboxes) > 0): 1646 continue 1647 y0, x0 = self._outer_offset(tile_id) 1648 local_points = (tpoints - np.array([x0, y0])) if len(tpoints) else None 1649 local_boxes = [b - np.array([x0, y0, x0, y0]) for b in tboxes] if tboxes else None 1650 local_masks = tile_masks.get(tile_id) if tboxes else None 1651 tile_jobs[tile_id] = ( 1652 local_points, 1653 tlabels if len(tlabels) else None, 1654 local_boxes, 1655 local_masks, 1656 ) 1657 1658 def segment_tile(tile_id): 1659 local_points, local_labels, local_boxes, local_masks = tile_jobs[tile_id] 1660 return self._get_segmenter(tile_id).segment_slice( 1661 frame_idx, points=local_points, labels=local_labels, 1662 boxes=local_boxes, masks=local_masks, object_id=object_id, 1663 ) 1664 1665 out = np.zeros(self.shape[1:], dtype="uint32") 1666 found = False 1667 for tile_id, tile_seg in self.map_tiles(sorted(tile_jobs), segment_tile): 1668 if tile_seg is None: 1669 continue 1670 local, glob = self._inner_slices(tile_id) 1671 region = tile_seg[local] 1672 sub = out[glob] 1673 positive = region > 0 1674 sub[positive] = region[positive] 1675 found = True 1676 1677 return out if found else None 1678 1679 def add_point_prompts(self, frame_ids, points, point_labels, object_id=None, multiple_objects=False): 1680 """Add point prompts. Points are in (y, x) order. Each is routed to the tile it falls in, so 1681 an object with prompts in several tiles is added to each of those tiles.""" 1682 if points is None or len(points) == 0: 1683 return 1684 if object_id is None: 1685 object_id = 1 1686 1687 tile_points, tile_labels = {}, {} 1688 for point, label in zip(np.asarray(points), np.asarray(point_labels)): 1689 tid = self._tile_index(int(round(point[0])), int(round(point[1]))) 1690 tile_points.setdefault(tid, []).append(point) 1691 tile_labels.setdefault(tid, []).append(label) 1692 1693 for tile_id, tpoints in tile_points.items(): 1694 y0, x0 = self._outer_offset(tile_id) 1695 local_points = np.asarray(tpoints) - np.array([y0, x0]) 1696 self._get_segmenter(tile_id).add_point_prompts( 1697 frame_ids=frame_ids, points=local_points, point_labels=np.asarray(tile_labels[tile_id]), 1698 object_id=object_id, multiple_objects=multiple_objects, 1699 ) 1700 1701 def add_box_prompts(self, frame_ids, boxes=None, object_id=None): 1702 """Add box prompts (y0, x0, y1, x1). A box spanning several tiles is added, clipped, to each.""" 1703 if boxes is None or len(boxes) == 0: 1704 return 1705 # One object id per box. Default to a single object (id 1) when not batched. 1706 if object_id is None: 1707 object_id = [1] * len(boxes) 1708 elif not isinstance(object_id, list): 1709 object_id = [object_id] * len(boxes) 1710 # Group the (clipped) boxes and their object ids by the tile each falls in. 1711 tile_boxes, tile_ids = {}, {} 1712 for box, obj_id in zip(boxes, object_id): 1713 for tid, clipped in _box_to_tiles(self.tiling, self.halo, np.asarray(box)).items(): 1714 tile_boxes.setdefault(tid, []).append(clipped) 1715 tile_ids.setdefault(tid, []).append(obj_id) 1716 for tile_id, tboxes in tile_boxes.items(): 1717 y0, x0 = self._outer_offset(tile_id) 1718 local_boxes = [b - np.array([y0, x0, y0, x0]) for b in tboxes] 1719 self._get_segmenter(tile_id).add_box_prompts( 1720 frame_ids=frame_ids, boxes=np.array(local_boxes), object_id=tile_ids[tile_id], 1721 ) 1722 1723 def add_mask_prompts(self, frame_ids, masks=None, object_id=None, refine=True): 1724 """Add mask prompts. Each mask is routed to the tiles its filled region overlaps, cropped to 1725 each tile's outer block, and added there (so a mask spanning tiles is added on both sides).""" 1726 if masks is None or len(masks) == 0: 1727 return 1728 masks = [np.asarray(m) for m in masks] 1729 # One object id per mask. Default to a single object (id 1) when not batched. 1730 if object_id is None: 1731 object_id = [1] * len(masks) 1732 elif not isinstance(object_id, list): 1733 object_id = [object_id] * len(masks) 1734 1735 for mask, obj_id in zip(masks, object_id): 1736 ys, xs = np.nonzero(mask) 1737 if len(ys) == 0: 1738 continue 1739 box_yx = np.array([ys.min(), xs.min(), ys.max() + 1, xs.max() + 1]) 1740 for tid in _box_to_tiles(self.tiling, self.halo, box_yx): 1741 self._get_segmenter(tid).add_mask_prompts( 1742 frame_ids=frame_ids, masks=[_crop_mask_to_tile(self.tiling, self.halo, tid, mask)], 1743 object_id=obj_id, refine=refine, 1744 ) 1745 1746 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1747 """Propagate the prompts in every active tile and stitch the results into the full volume. 1748 1749 Object ids are preserved across tiles (the inner blocks are disjoint), so an object that was 1750 prompted in several tiles keeps one id and is merged across the tile boundaries. 1751 'mask_threshold' is the logit threshold that binarizes the masks. 1752 """ 1753 segmentation = np.zeros(self.shape, dtype="uint64") 1754 1755 def predict_tile(tile_id, tile_update=None): 1756 return self._get_segmenter(tile_id).predict( 1757 update_progress=tile_update, early_stop_patience=early_stop_patience, z_range=z_range, 1758 mask_threshold=mask_threshold, 1759 ) 1760 1761 for tile_id, tile_seg in self.map_tiles( 1762 self.active_tiles, predict_tile, update_progress=update_progress, 1763 ): 1764 local, glob = self._inner_slices(tile_id) 1765 inner = tile_seg[(slice(None),) + local] 1766 region = segmentation[(slice(None),) + glob] 1767 positive = inner != 0 1768 region[positive] = inner[positive] 1769 return segmentation
78def map_jobs_over_devices(devices, jobs: List, function: Callable, update_progress=None) -> List: 79 """Run independent jobs over one worker per device, each taking the next job once it is free. 80 81 The results come back in the order the jobs were given, never the order the devices finished in, 82 because a caller that merges them may break ties by position. 83 84 Args: 85 devices: The devices to spread the jobs over, one worker each. 86 jobs: The jobs, passed to `function` one at a time. 87 function: Called as `function(worker_id, job)`, with the index of the device it runs on. 88 update_progress: Optional callback, called with 1 after every finished job. 89 90 Returns: 91 One result per job, in the order the jobs were given. 92 """ 93 jobs = list(jobs) 94 if not jobs: 95 return [] 96 97 results = [None] * len(jobs) 98 n_workers = min(len(devices), len(jobs)) 99 if n_workers < 2: 100 for index, job in enumerate(jobs): 101 results[index] = function(0, job) 102 if update_progress is not None: 103 update_progress(1) 104 return results 105 106 pending = queue.Queue() 107 for index, job in enumerate(jobs): 108 pending.put((index, job)) 109 110 def run_worker(worker_id): 111 with _device_context(devices[worker_id]): 112 while True: 113 try: 114 index, job = pending.get_nowait() 115 except queue.Empty: 116 break 117 results[index] = function(worker_id, job) 118 if update_progress is not None: 119 update_progress(1) 120 121 with futures.ThreadPoolExecutor(max_workers=n_workers) as pool: 122 for task in [pool.submit(run_worker, worker_id) for worker_id in range(n_workers)]: 123 task.result() 124 return results
Run independent jobs over one worker per device, each taking the next job once it is free.
The results come back in the order the jobs were given, never the order the devices finished in, because a caller that merges them may break ties by position.
Arguments:
- devices: The devices to spread the jobs over, one worker each.
- jobs: The jobs, passed to
functionone at a time. - function: Called as
function(worker_id, job), with the index of the device it runs on. - update_progress: Optional callback, called with 1 after every finished job.
Returns:
One result per job, in the order the jobs were given.
414def tiled_promptable_segmentation_2d( 415 predictor, 416 image_embeddings: dict, 417 points: Optional[np.ndarray] = None, 418 labels: Optional[np.ndarray] = None, 419 boxes: Optional[np.ndarray] = None, 420 masks: Optional[np.ndarray] = None, 421 batched: Optional[bool] = None, 422 devices: Devices = None, 423): 424 """Tiled 2d promptable segmentation for the SAM2 image predictor. 425 426 Routes the prompts to the tile-column they fall in, sets that tile's precomputed embeddings on 427 the predictor (via `set_precomputed`), runs `promptable_segmentation_2d` on the tile, and 428 stitches the per-tile mask into the full image. Points are in (y, x) order, as passed by the 429 annotator. Same return convention as `promptable_segmentation_2d`. 430 431 Independent active tiles run concurrently on persistent predictor replicas. By default all 432 visible CUDA devices are used; pass `devices` to select or restrict them. 433 """ 434 from bioimage_cpp.utils import Blocking 435 from micro_sam.v2.util import set_precomputed 436 437 feats = image_embeddings["features"] 438 shape = tuple(int(s) for s in feats.attrs["shape"]) 439 tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"]) 440 halo = tuple(int(s) for s in feats.attrs["halo"]) 441 tiling = Blocking([0, 0], list(shape), list(tile_shape)) 442 443 have_points = points is not None and len(points) > 0 444 have_boxes = boxes is not None and len(boxes) > 0 445 if not have_points and not have_boxes: 446 return None 447 448 # Grouped by tile, so an object is segmented in every tile that holds one of its prompts. 449 # Points are (y, x), boxes (y0, x0, y1, x1), and a mask is cropped to the tile's outer block. 450 tile_points, tile_labels, tile_boxes, tile_masks, tile_box_ids = {}, {}, {}, {}, {} 451 if have_points: 452 for point, label in zip(np.asarray(points), np.asarray(labels)): 453 tid = _tile_index_for(tiling, halo, int(round(point[0])), int(round(point[1]))) 454 tile_points.setdefault(tid, []).append(point) 455 tile_labels.setdefault(tid, []).append(label) 456 if have_boxes: 457 for bidx, box in enumerate(boxes): 458 box_mask = masks[bidx] if masks is not None else None 459 # A box can span several tiles. Segment its clipped portion in each (boxes are y0,x0,y1,x1). 460 for tid, clipped in _box_to_tiles(tiling, halo, np.asarray(box)).items(): 461 tile_boxes.setdefault(tid, []).append(clipped) 462 tile_box_ids.setdefault(tid, []).append(bidx + 1) 463 tile_masks.setdefault(tid, []).append( 464 None if box_mask is None else _crop_mask_to_tile(tiling, halo, tid, box_mask) 465 ) 466 467 tile_jobs = {} 468 for tile_id in sorted(set(tile_points) | set(tile_boxes)): 469 tpoints = np.asarray(tile_points.get(tile_id, [])).reshape(-1, 2) 470 tlabels = np.asarray(tile_labels.get(tile_id, []), dtype=int) 471 tboxes = tile_boxes.get(tile_id, []) 472 # A tile with only negative points has nothing to segment. 473 if not ((tlabels == 1).any() or len(tboxes) > 0): 474 continue 475 476 outer = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 477 y0, x0 = int(outer.begin[0]), int(outer.begin[1]) 478 local_points = (tpoints - np.array([y0, x0])) if len(tpoints) else tpoints 479 local_boxes = [b - np.array([y0, x0, y0, x0]) for b in tboxes] if tboxes else None 480 local_masks = tile_masks.get(tile_id) if tboxes else None 481 tile_jobs[tile_id] = local_points, tlabels, local_boxes, local_masks 482 483 predictor_devices = _get_image_predictor_devices(predictor, devices) 484 # Spread the active tiles round-robin. Their ids are sparse, so mapping by 'tile_id % n_devices' 485 # would run e.g. the tiles 0, 2, 4 on one device and leave the others idle. 486 groups = {} 487 for position, tile_id in enumerate(sorted(tile_jobs)): 488 worker_id = position % len(predictor_devices) 489 groups.setdefault(worker_id, []).append(tile_id) 490 491 def run_group(worker_id, tile_ids): 492 local_predictor, _ = predictor_devices[worker_id] 493 results = [] 494 for tile_id in tile_ids: 495 local_points, local_labels, local_boxes, local_masks = tile_jobs[tile_id] 496 set_precomputed(local_predictor, image_embeddings, tile_id=tile_id) 497 tile_seg = promptable_segmentation_2d( 498 local_predictor, image=None, points=local_points, labels=local_labels, 499 boxes=local_boxes, masks=local_masks, batched=batched, 500 ) 501 results.append((tile_id, tile_seg)) 502 return results 503 504 if len(groups) < 2: 505 results = run_group(*next(iter(groups.items()))) if groups else [] 506 else: 507 results = [] 508 with futures.ThreadPoolExecutor(max_workers=len(groups)) as pool: 509 tasks = [pool.submit(run_group, worker_id, tile_ids) for worker_id, tile_ids in groups.items()] 510 for task in tasks: 511 results.extend(task.result()) 512 513 out = np.zeros(shape, dtype="uint32") 514 found = False 515 for tile_id, tile_seg in sorted(results): 516 if tile_seg is None: 517 continue 518 519 local, glob = _inner_block_slices(tiling, halo, tile_id) 520 region = tile_seg[local] 521 # The tile counts its boxes from 1, so map them back to the global box ids. 522 if not batched and tile_id in tile_box_ids: 523 region = np.array([0] + tile_box_ids[tile_id], dtype="uint32")[region] 524 # Unioned by id, so an object spanning tiles is merged across the boundary. 525 sub = out[glob] 526 positive = region > 0 527 sub[positive] = region[positive] 528 found = True 529 530 return out if found else None
Tiled 2d promptable segmentation for the SAM2 image predictor.
Routes the prompts to the tile-column they fall in, sets that tile's precomputed embeddings on
the predictor (via set_precomputed), runs promptable_segmentation_2d on the tile, and
stitches the per-tile mask into the full image. Points are in (y, x) order, as passed by the
annotator. Same return convention as promptable_segmentation_2d.
Independent active tiles run concurrently on persistent predictor replicas. By default all
visible CUDA devices are used; pass devices to select or restrict them.
533class PromptableSegmentation3D: 534 """Promptable segmentation class for volumetric data. 535 """ 536 # On the class, so that an instance built without '__init__' still reads it. 537 release_stale_mask_memory = False 538 539 def __init__( 540 self, predictor, volume, volume_embeddings, device=None, 541 offload_state_to_cpu=None, max_cached_frames=None, release_stale_mask_memory=False, 542 ): 543 from micro_sam.v2.util import _get_device 544 self.predictor = predictor 545 self.volume = volume 546 self.volume_embeddings = volume_embeddings 547 # 'device=None' uses the predictor's auto-detected device. 548 self.device = device 549 # Bounds device memory on cuda. Off on mps: unified memory saves nothing, and SAM2's 550 # non-blocking transfer back races there, which gives intermittent garbage masks. 551 is_mps = device_type(_get_device(device)) == "mps" 552 self.offload_state_to_cpu = (not is_mps) if offload_state_to_cpu is None else offload_state_to_cpu 553 # A pass walks every slice, so a feature cache shorter than the volume is never hit. 554 self.max_cached_frames = max_cached_frames 555 # Saves device memory, but only for a caller that resets the tracking before prompting again. 556 self.release_stale_mask_memory = release_stale_mask_memory 557 558 if self.volume.ndim not in (3, 4): 559 raise AssertionError(f"The volume must be (Z, Y, X) or (Z, Y, X, C), got shape {self.volume.shape}") 560 561 self.init_predictor() 562 563 # What the SAM2 state already holds, so a re-run pushes only the newly placed prompts. 564 self._pushed_points = {} # (object_id, frame_id) -> set of (y, x, label) 565 self._pushed_boxes = {} # (object_id, frame_id) -> set of box corner tuples 566 self._pushed_masks = {} # (object_id, frame_id) -> mask digest -> prepared mask 567 # Successful predictor calls in their original order and batching. The active maps above 568 # deliberately omit prompts that SAM2 replaced; the history retains their decoder effects. 569 self._prompt_history = [] 570 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 571 self._prompt_signatures = set() 572 self._image_style_trafo = None # Built lazily for the per-slice mask refinement. 573 574 def init_predictor(self): 575 self.inference_state = self.predictor.init_state( 576 volume=self.volume, volume_embeddings=self.volume_embeddings, device=self.device, 577 offload_state_to_cpu=self.offload_state_to_cpu, max_cached_frames=self.max_cached_frames, 578 ) 579 580 def _clear_pushed_prompts(self): 581 # The dedup bookkeeping describes the SAM2 state, so it must never outlive it. 582 self._pushed_points = {} 583 self._pushed_boxes = {} 584 self._pushed_masks = {} 585 self._prompt_history = [] 586 self._prompt_signatures = set() 587 588 def _anchor_per_object(self): 589 """The earliest slice each object is conditioned on, keyed by its object id.""" 590 anchors = {} 591 for key in (*self._pushed_points, *self._pushed_boxes, *self._pushed_masks): 592 object_id, frame_id = key 593 anchors[object_id] = min(anchors.get(object_id, frame_id), frame_id) 594 return anchors 595 596 def _replay_prompts(self, snapshot, object_ids): 597 """Replay these objects' successful predictor operations onto a fresh state. 598 599 The snapshot is taken before the first replay, because resetting the state also clears the 600 history this reads, and a later group's prompts would be gone by then. Preserving operation 601 order, point batching and replacement flags is necessary because SAM2 feeds the previous 602 decoder logits into the next point/box operation. 603 """ 604 self.reset_predictor() 605 skip_output = getattr(self.predictor, "skip_prompt_output", None) 606 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 607 for operation in snapshot: 608 if operation.object_id in object_ids: 609 self._apply_prompt_operation(operation) 610 611 def _apply_prompt_operation(self, operation): 612 """Apply and record one predictor operation, updating active state only after it succeeds.""" 613 operation = operation.copied() 614 key = (operation.object_id, operation.frame_id) 615 616 if operation.kind == "points_or_box": 617 if operation.box is not None and not operation.clear_old_points: 618 raise ValueError("SAM2 requires 'clear_old_points=True' whenever a box is given.") 619 kwargs = {} 620 if operation.points is not None and len(operation.points): 621 if operation.point_labels is None or len(operation.points) != len(operation.point_labels): 622 raise AssertionError("The number of points and labels do not match.") 623 # SAM2 expects (x, y). This unconditional copy also removes negative strides for a 624 # single point, whose reversed view numpy can otherwise still call contiguous. 625 kwargs["points"] = np.array(operation.points[:, ::-1], dtype="float32") 626 kwargs["labels"] = np.array(operation.point_labels, dtype="int32") 627 if operation.box is not None: 628 kwargs["box"] = np.array([_process_box(operation.box, self.volume.shape[1:3])]) 629 if not kwargs: 630 return 631 632 self.predictor.add_new_points_or_box( 633 inference_state=self.inference_state, 634 frame_idx=operation.frame_id, 635 obj_id=operation.object_id, 636 clear_old_points=operation.clear_old_points, 637 **kwargs, 638 ) 639 640 # Mirror SAM2's mutually exclusive active input maps. A replacement discards the active 641 # point/box set, but its earlier decoder effect remains in '_prompt_history'. 642 if operation.clear_old_points: 643 self._pushed_points.pop(key, None) 644 self._pushed_boxes.pop(key, None) 645 self._pushed_masks.pop(key, None) 646 if operation.points is not None and len(operation.points): 647 seen = self._pushed_points.setdefault(key, set()) 648 for (y, x), label in zip(operation.points, operation.point_labels): 649 seen.add((int(round(float(y))), int(round(float(x))), int(label))) 650 if operation.box is not None: 651 signature = tuple(np.round(operation.box).astype(int).tolist()) 652 self._pushed_boxes.setdefault(key, set()).add(signature) 653 654 elif operation.kind == "mask": 655 if operation.mask is None or operation.mask_signature is None: 656 raise ValueError("A mask operation requires a prepared mask and its signature.") 657 self.predictor.add_new_mask( 658 inference_state=self.inference_state, 659 frame_idx=operation.frame_id, 660 obj_id=operation.object_id, 661 mask=operation.mask, 662 ) 663 self._pushed_points.pop(key, None) 664 self._pushed_boxes.pop(key, None) 665 self._pushed_masks[key] = {operation.mask_signature: operation.mask.copy()} 666 else: 667 raise ValueError(f"Unknown prompt operation kind '{operation.kind}'.") 668 669 self._prompt_history.append(operation) 670 671 def sync_prompt_state(self, signatures): 672 """Discard the persistent state when prompts were removed or changed since the last round. 673 674 The dedup in 'add_*_prompts' only detects added prompts. Additive refinement (the current 675 prompts are a superset of the previous ones) therefore keeps the state and pushes just the 676 new prompts, while a removal, relabel or move replays everything from scratch. 677 678 Args: 679 signatures: Hashable descriptors of every prompt currently in the annotation layers. 680 """ 681 signatures = set(signatures) 682 if not self._prompt_signatures.issubset(signatures): 683 self.reset_predictor() 684 self._prompt_signatures = signatures 685 686 def release(self): 687 """Drop the tracked objects and the cached slice features, keeping the allocator's cache. 688 689 What a caller that builds another state of the same size on this device right afterwards 690 needs: the blocks go back to the caching allocator, which hands them to the next state. 691 Emptying that cache instead would make every rebuild pay for a fresh allocation. 692 """ 693 self.predictor.reset_state(self.inference_state) 694 self._clear_pushed_prompts() 695 # 'reset_state' clears the tracking outputs, not the cached features or the encoding they share. 696 self.inference_state["cached_features"] = {} 697 self.inference_state.pop("shared_pos_enc", None) 698 699 def reset_predictor(self): 700 self.release() 701 _free_device_memory() 702 703 def reset_tracking(self): 704 """Clear the tracked objects, keeping the features of the volume they were tracked on. 705 706 What a further propagation pass over the same volume needs, and all it needs: those features 707 are a function of the volume's embeddings, not of the objects. `reset_predictor` drops them 708 as well and hands the memory back to the allocator, which together cost more than the passes 709 themselves once there are many. The cache stays bounded by MAX_CACHED_FRAMES either way. 710 """ 711 self.predictor.reset_state(self.inference_state) 712 self._clear_pushed_prompts() 713 714 def get_progress_total(self, z_range=None): 715 """Return the number of slice propagation steps for the requested z range. 716 717 Objects conditioned on different slices take one propagation pass each, see 'propagate_prompts'. 718 """ 719 slices = int(self.volume.shape[0]) if z_range is None else int(z_range[1] - z_range[0] + 1) 720 return slices * max(1, len(set(self._anchor_per_object().values()))) 721 722 def _broadcast(self, value, n): 723 """Broadcast a scalar frame/object id to a length-'n' list (or validate a length-1 or -'n' 724 sequence). Guards against the earlier bug where a single frame id zipped against several 725 points silently dropped all but the first point.""" 726 if isinstance(value, (list, tuple, np.ndarray)): 727 values = [int(v) for v in value] 728 if len(values) == 1: 729 values = values * n 730 if len(values) != n: 731 raise ValueError(f"Expected 1 or {n} ids, got {len(values)}.") 732 return values 733 return [int(value)] * n 734 735 def add_point_prompts( 736 self, 737 frame_ids: Union[int, List[int]], 738 points: np.ndarray, 739 point_labels: np.ndarray, 740 object_id: Optional[Union[List[int], int]] = None, 741 multiple_objects: bool = False, # Enables multi-object segmentation. 742 ): 743 """Add point prompts (in (y, x) order) to the persistent SAM2 state, one object at a time. 744 745 Several points can be added in a single call. A point already pushed in an earlier call (same 746 object, frame, rounded position and label) is skipped, so re-running with the full prompt set 747 only pushes newly placed points. New points are appended ('clear_old_points=False') so they 748 correct the running segmentation instead of replacing it. 749 """ 750 if multiple_objects and object_id is not None: 751 raise ValueError("Cannot enable multi-object segmentation and also pass a fixed object id.") 752 if points is None or len(points) == 0: 753 return 754 755 points = np.asarray(points) 756 point_labels = np.asarray(point_labels) 757 if points.ndim != 2 or points.shape[1] != 2: 758 raise ValueError("'points' must have shape (N, 2).") 759 if len(points) != len(point_labels): 760 raise AssertionError("The number of points and labels do not match.") 761 762 n = len(points) 763 frame_ids = self._broadcast(frame_ids, n) 764 object_ids = self._broadcast(1 if object_id is None else object_id, n) 765 766 # The per-prompt masks are not read here, and consolidating them costs more than the prompt. 767 skip_output = getattr(self.predictor, "skip_prompt_output", None) 768 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 769 for frame_id, (y, x), label, obj_id in zip(frame_ids, points, point_labels, object_ids): 770 signature = (int(round(float(y))), int(round(float(x))), int(label)) 771 if signature in self._pushed_points.get((obj_id, frame_id), set()): 772 continue 773 self._apply_prompt_operation( 774 _PromptOperation( 775 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 776 clear_old_points=False, 777 points=np.array([[y, x]], dtype="float32"), 778 point_labels=np.array([label], dtype="int32"), 779 ) 780 ) 781 782 def add_prompt_set( 783 self, 784 frame_id: int, 785 points: Optional[np.ndarray] = None, 786 point_labels: Optional[np.ndarray] = None, 787 box: Optional[np.ndarray] = None, 788 object_id: int = 1, 789 clear_old_points: bool = True, 790 ): 791 """Condition one object on a whole prompt set at once, in a single SAM2 call. 792 793 'add_point_prompts' pushes one point at a time, and 'add_box_prompts' pushes a box and then 794 replays the points it had to clear. That is what an annotator placing corrections needs: each 795 push returns the running segmentation, and re-running only sends what is new. A caller that 796 has the whole set up front pays for it, because every push re-runs the mask decoder on the 797 conditioning frame - eight of them for a box and seven points. SAM2 takes the set in one 798 call instead, with the box as the first two coordinates, which is also the order it wants. 799 800 The prompts are recorded in the same bookkeeping the incremental methods use, so the anchor 801 of each object and a replay onto a fresh state still see them. 802 803 Args: 804 frame_id: The slice to condition. 805 points: The points, (N, 2) in (y, x) order. None conditions on the box alone. 806 point_labels: One label per point: 1 positive, 0 negative. 807 box: An optional box, in (y0, x0, y1, x1) order. 808 object_id: The object being conditioned. 809 clear_old_points: Whether the push replaces what this object already carries on the 810 frame. SAM2 requires it whenever a box is given. False appends, which is how a 811 points-only push is added after a box. 812 """ 813 has_points = points is not None and len(points) > 0 814 if not has_points and box is None: 815 return 816 frame_id, object_id = int(frame_id), int(object_id) 817 if box is not None and not clear_old_points: 818 # Validate before touching bookkeeping or invoking SAM2, whose implementation rejects 819 # this combination as well. 820 raise ValueError("SAM2 requires 'clear_old_points=True' whenever a box is given.") 821 822 normalized_points, normalized_labels = None, None 823 if has_points: 824 points = np.asarray(points, dtype="float32").reshape(-1, 2) 825 if point_labels is None: 826 raise ValueError("'point_labels' is required when points are given.") 827 point_labels = np.asarray(point_labels, dtype="int32").reshape(-1) 828 if len(points) != len(point_labels): 829 raise AssertionError("The number of points and labels do not match.") 830 normalized_points, normalized_labels = points, point_labels 831 normalized_box = None if box is None else np.asarray(box, dtype="float32").reshape(4) 832 833 # The preview mask is discarded, as in the incremental methods. 834 skip_output = getattr(self.predictor, "skip_prompt_output", None) 835 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 836 self._apply_prompt_operation( 837 _PromptOperation( 838 kind="points_or_box", frame_id=frame_id, object_id=object_id, 839 clear_old_points=bool(clear_old_points), 840 points=normalized_points, point_labels=normalized_labels, box=normalized_box, 841 ) 842 ) 843 844 def add_box_prompts( 845 self, 846 frame_ids: Union[int, List[int]], 847 boxes: Optional[np.ndarray] = None, 848 object_id: Optional[Union[int, List[int]]] = None, 849 ): 850 """Add box prompts (in (y0, x0, y1, x1) order) to the persistent SAM2 state. 851 852 A box is pushed at most once per (object, frame); re-running with the same box is a no-op. 853 SAM2 requires the box before any point on the same object/frame, so a box clears existing 854 points ('clear_old_points=True'); we re-add any already-pushed points afterwards so a box and 855 its correction points combine regardless of the order they were drawn in. 856 """ 857 if boxes is None or len(boxes) == 0: 858 return 859 860 boxes = [np.asarray(b) for b in boxes] 861 n = len(boxes) 862 frame_ids = self._broadcast(frame_ids, n) 863 object_ids = self._broadcast(1 if object_id is None else object_id, n) 864 865 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 866 # consolidating it costs a pass over every object of the state. 867 skip_output = getattr(self.predictor, "skip_prompt_output", None) 868 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 869 for frame_id, box, obj_id in zip(frame_ids, boxes, object_ids): 870 key = (obj_id, frame_id) 871 signature = tuple(np.round(box).astype(int).tolist()) 872 if signature in self._pushed_boxes.get(key, set()): 873 continue 874 existing_points = sorted(self._pushed_points.get(key, set())) 875 self._apply_prompt_operation( 876 _PromptOperation( 877 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 878 clear_old_points=True, box=np.asarray(box, dtype="float32").reshape(4), 879 ) 880 ) 881 for y, x, label in existing_points: 882 self._apply_prompt_operation( 883 _PromptOperation( 884 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 885 clear_old_points=False, 886 points=np.array([[y, x]], dtype="float32"), 887 point_labels=np.array([label], dtype="int32"), 888 ) 889 ) 890 891 def _prepare_mask(self, mask): 892 """Bring a full-resolution 2d boolean mask into the padded-square frame the video predictor 893 sees, so SAM2's own (direct) resize inside 'add_new_mask' is a no-op and the mask stays 894 aligned with the resize-longest-side + pad the frames use.""" 895 mask = np.asarray(mask).astype(bool) 896 target = self.predictor.image_size 897 if mask.shape[-2:] == (target, target): 898 return mask 899 prepared, _ = resize_longest_side_and_pad_spatial_numpy(mask, target, is_label=True) 900 return prepared.astype(bool) 901 902 def add_mask_prompts( 903 self, 904 frame_ids: Union[int, List[int]], 905 masks: Optional[List[np.ndarray]] = None, 906 object_id: Optional[Union[int, List[int]]] = None, 907 refine: bool = True, 908 ): 909 """Add mask prompts (full-resolution 2d boolean masks) to the persistent SAM2 state. 910 911 A napari polygon or ellipse is filled into a mask (from 'shape_layer_to_prompts'). We first 912 refine the drawn shape into the object on its seed frame (box + soft mask-logit cue, as in 913 the per-slice path), then seed propagation with the refined mask - so the seed slice matches 914 the per-slice result instead of reproducing the raw outline. SAM2's video predictor conditions 915 a frame on either a mask or points/box (not both), so a mask prompt does not combine with 916 points on the same object/frame. A mask already pushed (same object, frame, content) is 917 skipped so re-runs only add newly drawn masks. 918 919 Args: 920 frame_ids: The slice each mask conditions, one per mask or one for all of them. 921 masks: The masks, at the volume's full resolution. 922 object_id: The object each mask belongs to, one per mask or one for all of them. 923 refine: Whether to refine each mask into the object on its frame first. True for a shape 924 somebody drew; False for a mask that is already a prediction for this frame, which a 925 second refinement would only pull away from what it was accepted as. 926 """ 927 if masks is None or len(masks) == 0: 928 return 929 930 masks = [np.asarray(m) for m in masks] 931 n = len(masks) 932 frame_ids = self._broadcast(frame_ids, n) 933 object_ids = self._broadcast(1 if object_id is None else object_id, n) 934 935 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 936 # consolidating it costs a pass over every object of the state. 937 skip_output = getattr(self.predictor, "skip_prompt_output", None) 938 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 939 for frame_id, mask, obj_id in zip(frame_ids, masks, object_ids): 940 key = (obj_id, frame_id) 941 # A stable digest, so the signature does not change between processes. 942 signature = hashlib.sha1(np.ascontiguousarray(mask).tobytes()).hexdigest() 943 if signature in self._pushed_masks.get(key, {}): 944 continue 945 946 # Refined on the seed frame first, so the propagation starts from the object rather 947 # than from the drawn shape. The box is the filled mask's extent. 948 ys, xs = np.nonzero(mask) 949 if len(ys) == 0: 950 continue 951 if refine: 952 box = np.array([xs.min(), ys.min(), xs.max(), ys.max()], dtype="float32") # (x0,y0,x1,y1) 953 mask = self._image_style_predict(frame_id, box=box, mask=mask) 954 955 prepared = self._prepare_mask(mask) 956 self._apply_prompt_operation( 957 _PromptOperation( 958 kind="mask", frame_id=frame_id, object_id=obj_id, 959 mask_signature=signature, mask=prepared, 960 ) 961 ) 962 963 def _propagate_in_direction( 964 self, 965 reverse, 966 update_progress=None, 967 early_stop_patience=None, 968 z_range=None, 969 seen_frames=None, 970 mask_threshold=0.0, 971 return_logits=False, 972 ): 973 """Run SAM2 propagation in one temporal direction, optionally stopping early. 974 975 Each step of the SAM2 video predictor runs the full memory attention and mask decoder 976 for one frame, which is the dominant cost of volumetric segmentation (especially on CPU). 977 Early stopping reads the masks we already compute and breaks out of the propagation once 978 the object has clearly left the volume, so we do not keep running the network on frames 979 that no longer contain the object. 980 981 Args: 982 reverse: Propagate backwards in time (towards lower slice indices) if True. 983 update_progress: Optional callback invoked with the number of newly processed frames. 984 early_stop_patience: If given, stop this direction after this many consecutive frames 985 in which every tracked object's mask is empty (i.e. the object has left the volume). 986 'None' disables early stopping and propagates to the end of the volume. 987 z_range: If given, an inclusive '(z_min, z_max)' bound on the slice indices propagation 988 may cover. Propagation stops at the range edge in this direction. 'None' propagates 989 to the end of the volume. 990 seen_frames: Optional set of already-counted frame indices, shared across both directions, 991 so a frame processed in both (the conditioning frame) advances 'update_progress' once. 992 mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too. 993 return_logits: Return the float32 mask logits instead of the boolean masks. 994 995 Returns: 996 Mapping from frame index to per-object boolean masks (or logits), in the order frames were yielded. 997 """ 998 video_segments = {} 999 consecutive_empty = 0 1000 for out_frame_idx, out_obj_ids, out_mask_logits in self.predictor.propagate_in_video( 1001 self.inference_state, reverse=reverse, release_stale_mask_memory=self.release_stale_mask_memory, 1002 ): 1003 # Hard z-range bound: stop once propagation would leave the user-selected slice range. 1004 if z_range is not None and not (z_range[0] <= out_frame_idx <= z_range[1]): 1005 break 1006 1007 # One transfer for the whole frame, rather than a host round trip per object. 1008 if return_logits: 1009 logits = out_mask_logits.float().cpu().numpy() 1010 binary = logits > mask_threshold 1011 else: 1012 binary = (out_mask_logits > mask_threshold).cpu().numpy() 1013 frame_output = logits if return_logits else binary 1014 video_segments[out_frame_idx] = {obj_id: frame_output[i] for i, obj_id in enumerate(out_obj_ids)} 1015 # Counted once across both directions, which both yield the conditioning frame. 1016 if update_progress is not None and (seen_frames is None or out_frame_idx not in seen_frames): 1017 update_progress(1) 1018 if seen_frames is not None: 1019 seen_frames.add(out_frame_idx) 1020 1021 # A run of empty frames, not one: SAM2 can drop a mask momentarily and recover it. 1022 if early_stop_patience is not None: 1023 frame_is_empty = not binary.any() 1024 consecutive_empty = consecutive_empty + 1 if frame_is_empty else 0 1025 if consecutive_empty >= early_stop_patience: 1026 break 1027 1028 # The edge slice is stored, so stop before the predictor pays for a discarded frame. 1029 if z_range is not None and out_frame_idx == (z_range[0] if reverse else z_range[1]): 1030 break 1031 1032 return video_segments 1033 1034 def propagate_prompts( 1035 self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0, return_logits=False 1036 ): 1037 """Propagate the pushed prompts through the volume, one pass per conditioned slice. 1038 1039 SAM2 propagates every object of a state from the earliest slice any of them is conditioned on, 1040 and skips the backward pass entirely when that slice is 0. Objects anchored later would be 1041 tracked - and have those results written into their memory - before they are conditioned, and 1042 would never be propagated backwards at all. So objects that share an anchor are propagated 1043 together and the rest get a state of their own. 1044 1045 SAM2 builds its memory from the sigmoid of the logits, not from the thresholded masks. So 1046 thresholding the returned logits at 't' gives the masks of 'mask_threshold=t', except on the 1047 slices that early stopping skipped. SAM2 sets all logits of a slice to -1024 where it predicts 1048 that the object is absent, so a negative threshold does not recover such slices. 1049 1050 Args: 1051 update_progress: Optional callback invoked with the number of newly processed slices. 1052 early_stop_patience: Stop a direction after this many consecutive empty slices. 1053 'None' propagates to the end of the volume. 1054 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1055 mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too. 1056 return_logits: Return the float32 mask logits instead of the boolean masks. This keeps 1057 4 bytes per pixel, object and slice, so use it only for a few objects. 1058 1059 Returns: 1060 Mapping from slice index to {object id: mask (1, H, W)}. The video predictor pads non-square 1061 slices to a square, so crop each mask to '[:, :H, :W]' of the original slice shape. 1062 """ 1063 propagate_kwargs = dict( 1064 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1065 mask_threshold=mask_threshold, return_logits=return_logits, 1066 ) 1067 groups = {} 1068 for object_id, frame in self._anchor_per_object().items(): 1069 groups.setdefault(frame, []).append(object_id) 1070 if len(groups) <= 1: 1071 return self._propagate_both_directions(**propagate_kwargs) 1072 1073 # The active maps intentionally omit replaced prompts. Reconstruct from successful calls so 1074 # point batches, replacement boundaries and the previous-logit chain stay unchanged. 1075 snapshot = tuple(operation.copied() for operation in self._prompt_history) 1076 prompt_signatures = set(self._prompt_signatures) 1077 video_segments = {} 1078 for object_ids in groups.values(): 1079 self._replay_prompts(snapshot, set(object_ids)) 1080 for frame, per_object in self._propagate_both_directions(**propagate_kwargs).items(): 1081 video_segments.setdefault(frame, {}).update(per_object) 1082 1083 self._replay_prompts(snapshot, set().union(*groups.values())) 1084 self._prompt_signatures = prompt_signatures 1085 return video_segments 1086 1087 def _propagate_both_directions(self, **propagate_kwargs): 1088 # Shared across both directions, so the conditioning frame is counted once. 1089 seen_frames = set() 1090 forward_video_segments = self._propagate_in_direction( 1091 reverse=False, seen_frames=seen_frames, **propagate_kwargs 1092 ) 1093 1094 reverse_video_segments = {} 1095 if len(forward_video_segments) < self.volume.shape[0]: # Only if the forward pass fell short. 1096 reverse_video_segments = self._propagate_in_direction( 1097 reverse=True, seen_frames=seen_frames, **propagate_kwargs 1098 ) 1099 # Reversed, so it stitches onto the forward propagation. 1100 reverse_video_segments = dict(reversed(list(reverse_video_segments.items()))) 1101 1102 video_segments = {**reverse_video_segments, **forward_video_segments} 1103 return video_segments 1104 1105 def _image_features_for_frame(self, frame_idx): 1106 """Build (image_embed, high_res_feats) for one slice from its precomputed features. 1107 1108 Mirrors 'SAM2ImagePredictor.set_image', including the no-memory embedding that marks a 1109 memory-free image prediction. Couples to SAM2 predictor internals ('_get_image_feature', 1110 'no_mem_embed'), consistent with how the video-predictor subclass already uses them. 1111 """ 1112 predictor = self.predictor 1113 _, _, vision_feats, _, feat_sizes = predictor._get_image_feature(self.inference_state, int(frame_idx), 1) 1114 if predictor.directly_add_no_mem_embed: 1115 vision_feats[-1] = vision_feats[-1] + predictor.no_mem_embed 1116 feats = [ 1117 feat.permute(1, 2, 0).view(1, -1, *fs) for feat, fs in zip(vision_feats[::-1], feat_sizes[::-1]) 1118 ][::-1] 1119 return feats[-1], feats[:-1] 1120 1121 def _image_style_predict(self, frame_idx, box=None, mask=None, points=None, labels=None): 1122 """Image-predictor-style single-slice prediction using this slice's precomputed features. 1123 1124 Runs the SAM2 prompt encoder + mask decoder with a box + soft mask-logit cue (and any 1125 correction points), so the decoder refines the prompt into the object. This reproduces the 1126 2d behaviour, unlike the video predictor's 'add_new_mask', which hard-conditions on the drawn 1127 mask and returns it unchanged. Returns a full-resolution boolean segmentation for the slice. 1128 """ 1129 predictor = self.predictor 1130 device = self.inference_state["device"] 1131 orig_hw = tuple(int(s) for s in self.volume.shape[1:3]) 1132 image_size = predictor.image_size 1133 scale = float(image_size) / max(orig_hw) # Resize-longest, into the model frame. 1134 1135 image_embed, high_res_feats = self._image_features_for_frame(frame_idx) 1136 1137 # Box (labels 2, 3) plus any correction points, in (x, y), scaled into the model frame. 1138 coords, labs = [], [] 1139 if box is not None: 1140 box = np.asarray(box, dtype="float32").reshape(2, 2) * scale 1141 coords.append(torch.as_tensor(box, dtype=torch.float, device=device)) 1142 labs.append(torch.tensor([2, 3], dtype=torch.int, device=device)) 1143 if points is not None and len(points) > 0: 1144 pts = np.asarray(points, dtype="float32") * scale 1145 coords.append(torch.as_tensor(pts, dtype=torch.float, device=device)) 1146 labs.append(torch.as_tensor(np.asarray(labels), dtype=torch.int, device=device)) 1147 concat_points = (torch.cat(coords)[None], torch.cat(labs)[None]) if coords else None 1148 1149 # Soft low-res mask logits (1, 256, 256) from the filled shape, matching the frame's resize+pad. 1150 mask_input = None 1151 if mask is not None: 1152 logits = _compute_logits_from_mask(np.asarray(mask)) 1153 mask_input = torch.as_tensor(logits, dtype=torch.float, device=device)[None] 1154 1155 sparse, dense = predictor.sam_prompt_encoder(points=concat_points, boxes=None, masks=mask_input) 1156 low_res_masks, _, _, _ = predictor.sam_mask_decoder( 1157 image_embeddings=image_embed, 1158 image_pe=predictor.sam_prompt_encoder.get_dense_pe(), 1159 sparse_prompt_embeddings=sparse, 1160 dense_prompt_embeddings=dense, 1161 multimask_output=False, 1162 repeat_image=False, 1163 high_res_features=high_res_feats, 1164 ) 1165 1166 if self._image_style_trafo is None: 1167 self._image_style_trafo = ResizeLongestSideTransforms(resolution=image_size, mask_threshold=0.0) 1168 seg = self._image_style_trafo.postprocess_masks(low_res_masks, orig_hw) 1169 return (seg.squeeze() > 0.0).cpu().numpy().astype("uint32") 1170 1171 def _refine_slice_from_mask(self, frame_idx, boxes=None, masks=None, points=None, labels=None): 1172 """Per-slice refinement entry: pair the filled mask with its own box (the shape layer's 1173 'boxes'/'masks' are index-aligned) and refine it into the object via '_image_style_predict'.""" 1174 idx = next(i for i, m in enumerate(masks) if m is not None) 1175 box = boxes[idx] if boxes is not None and idx < len(boxes) else None 1176 return self._image_style_predict(frame_idx, box=box, mask=masks[idx], points=points, labels=labels) 1177 1178 def segment_slice( 1179 self, 1180 frame_idx: int, 1181 points: Optional[np.ndarray] = None, 1182 labels: Optional[np.ndarray] = None, 1183 boxes: Optional[List] = None, 1184 masks: Optional[List] = None, 1185 object_id: int = 1, 1186 ): 1187 """Segment a single slice using SAM2 video predictor. 1188 1189 Args: 1190 frame_idx: Slice index to segment. 1191 points: Point prompts (N, 2) array. 1192 labels: Point labels (N,) array. 1193 boxes: List of box prompts. 1194 masks: List of mask prompts (can be None). 1195 object_id: Object ID to use for the segmentation (default: 1). 1196 1197 Returns: 1198 Segmentation mask for the slice (2D array), or None if no valid prompts provided. 1199 """ 1200 have_points = points is not None and len(points) > 0 1201 have_boxes = boxes is not None and len(boxes) > 0 1202 have_masks = masks is not None and any(m is not None for m in masks) 1203 1204 if not have_points and not have_boxes and not have_masks: 1205 return None 1206 1207 try: 1208 if have_masks: 1209 # Refined the way the 2d predictor does, rather than through 'add_new_mask', which 1210 # hard-conditions on the drawn shape and returns it verbatim. 1211 seg = self._refine_slice_from_mask( 1212 frame_idx, boxes=boxes, masks=masks, 1213 points=points if have_points else None, labels=labels if have_points else None, 1214 ) 1215 else: 1216 box = boxes[0] if have_boxes else None 1217 _, out_obj_ids, out_mask_logits = self.predictor.add_new_points_or_box( 1218 inference_state=self.inference_state, 1219 frame_idx=frame_idx, 1220 obj_id=object_id, 1221 points=points if have_points else None, 1222 labels=labels if have_points else None, 1223 box=box, 1224 ) 1225 1226 mask_logits = out_mask_logits[0] # (num_objects, 1, H, W), so this is the first object. 1227 seg = (mask_logits.squeeze() > 0.0).cpu().numpy() 1228 1229 # Crop back to the original slice shape (the video predictor pads non-square frames). 1230 seg = _crop_to_original_shape(seg, self.volume.shape[1:3]).astype("uint32") 1231 1232 finally: 1233 # Clear this object's prompts and their bookkeeping, so the next round starts fresh. 1234 self.predictor.reset_state(self.inference_state) 1235 self._clear_pushed_prompts() 1236 1237 return seg 1238 1239 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1240 """Propagate the pushed prompts and paint the objects into one label volume. 1241 1242 Where objects overlap, the object with the higher id wins. 1243 1244 Args: 1245 update_progress: Optional callback invoked with the number of newly processed slices. 1246 early_stop_patience: Stop a direction after this many consecutive empty slices. 1247 'None' propagates to the end of the volume. 1248 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1249 mask_threshold: The logit threshold that binarizes the masks. 1250 1251 Returns: 1252 The label volume, with the shape of the input volume. 1253 """ 1254 video_segments = self.propagate_prompts( 1255 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1256 mask_threshold=mask_threshold, 1257 ) 1258 1259 # Indexed by slice id, so the frames early stopping skipped stay background rather than 1260 # shifting the rest out of alignment. 1261 shape = self.volume.shape[1:3] 1262 segmentation = np.zeros((self.volume.shape[0],) + tuple(shape), dtype="uint64") 1263 for slice_idx, instances in video_segments.items(): 1264 per_slice_seg = segmentation[slice_idx] 1265 for instance_idx, instance_mask in instances.items(): 1266 mask = _crop_to_original_shape(instance_mask.squeeze(), shape) 1267 per_slice_seg[mask] = instance_idx 1268 1269 return segmentation
Promptable segmentation class for volumetric data.
539 def __init__( 540 self, predictor, volume, volume_embeddings, device=None, 541 offload_state_to_cpu=None, max_cached_frames=None, release_stale_mask_memory=False, 542 ): 543 from micro_sam.v2.util import _get_device 544 self.predictor = predictor 545 self.volume = volume 546 self.volume_embeddings = volume_embeddings 547 # 'device=None' uses the predictor's auto-detected device. 548 self.device = device 549 # Bounds device memory on cuda. Off on mps: unified memory saves nothing, and SAM2's 550 # non-blocking transfer back races there, which gives intermittent garbage masks. 551 is_mps = device_type(_get_device(device)) == "mps" 552 self.offload_state_to_cpu = (not is_mps) if offload_state_to_cpu is None else offload_state_to_cpu 553 # A pass walks every slice, so a feature cache shorter than the volume is never hit. 554 self.max_cached_frames = max_cached_frames 555 # Saves device memory, but only for a caller that resets the tracking before prompting again. 556 self.release_stale_mask_memory = release_stale_mask_memory 557 558 if self.volume.ndim not in (3, 4): 559 raise AssertionError(f"The volume must be (Z, Y, X) or (Z, Y, X, C), got shape {self.volume.shape}") 560 561 self.init_predictor() 562 563 # What the SAM2 state already holds, so a re-run pushes only the newly placed prompts. 564 self._pushed_points = {} # (object_id, frame_id) -> set of (y, x, label) 565 self._pushed_boxes = {} # (object_id, frame_id) -> set of box corner tuples 566 self._pushed_masks = {} # (object_id, frame_id) -> mask digest -> prepared mask 567 # Successful predictor calls in their original order and batching. The active maps above 568 # deliberately omit prompts that SAM2 replaced; the history retains their decoder effects. 569 self._prompt_history = [] 570 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 571 self._prompt_signatures = set() 572 self._image_style_trafo = None # Built lazily for the per-slice mask refinement.
671 def sync_prompt_state(self, signatures): 672 """Discard the persistent state when prompts were removed or changed since the last round. 673 674 The dedup in 'add_*_prompts' only detects added prompts. Additive refinement (the current 675 prompts are a superset of the previous ones) therefore keeps the state and pushes just the 676 new prompts, while a removal, relabel or move replays everything from scratch. 677 678 Args: 679 signatures: Hashable descriptors of every prompt currently in the annotation layers. 680 """ 681 signatures = set(signatures) 682 if not self._prompt_signatures.issubset(signatures): 683 self.reset_predictor() 684 self._prompt_signatures = signatures
Discard the persistent state when prompts were removed or changed since the last round.
The dedup in 'add_*_prompts' only detects added prompts. Additive refinement (the current prompts are a superset of the previous ones) therefore keeps the state and pushes just the new prompts, while a removal, relabel or move replays everything from scratch.
Arguments:
- signatures: Hashable descriptors of every prompt currently in the annotation layers.
686 def release(self): 687 """Drop the tracked objects and the cached slice features, keeping the allocator's cache. 688 689 What a caller that builds another state of the same size on this device right afterwards 690 needs: the blocks go back to the caching allocator, which hands them to the next state. 691 Emptying that cache instead would make every rebuild pay for a fresh allocation. 692 """ 693 self.predictor.reset_state(self.inference_state) 694 self._clear_pushed_prompts() 695 # 'reset_state' clears the tracking outputs, not the cached features or the encoding they share. 696 self.inference_state["cached_features"] = {} 697 self.inference_state.pop("shared_pos_enc", None)
Drop the tracked objects and the cached slice features, keeping the allocator's cache.
What a caller that builds another state of the same size on this device right afterwards needs: the blocks go back to the caching allocator, which hands them to the next state. Emptying that cache instead would make every rebuild pay for a fresh allocation.
703 def reset_tracking(self): 704 """Clear the tracked objects, keeping the features of the volume they were tracked on. 705 706 What a further propagation pass over the same volume needs, and all it needs: those features 707 are a function of the volume's embeddings, not of the objects. `reset_predictor` drops them 708 as well and hands the memory back to the allocator, which together cost more than the passes 709 themselves once there are many. The cache stays bounded by MAX_CACHED_FRAMES either way. 710 """ 711 self.predictor.reset_state(self.inference_state) 712 self._clear_pushed_prompts()
Clear the tracked objects, keeping the features of the volume they were tracked on.
What a further propagation pass over the same volume needs, and all it needs: those features
are a function of the volume's embeddings, not of the objects. reset_predictor drops them
as well and hands the memory back to the allocator, which together cost more than the passes
themselves once there are many. The cache stays bounded by MAX_CACHED_FRAMES either way.
714 def get_progress_total(self, z_range=None): 715 """Return the number of slice propagation steps for the requested z range. 716 717 Objects conditioned on different slices take one propagation pass each, see 'propagate_prompts'. 718 """ 719 slices = int(self.volume.shape[0]) if z_range is None else int(z_range[1] - z_range[0] + 1) 720 return slices * max(1, len(set(self._anchor_per_object().values())))
Return the number of slice propagation steps for the requested z range.
Objects conditioned on different slices take one propagation pass each, see 'propagate_prompts'.
735 def add_point_prompts( 736 self, 737 frame_ids: Union[int, List[int]], 738 points: np.ndarray, 739 point_labels: np.ndarray, 740 object_id: Optional[Union[List[int], int]] = None, 741 multiple_objects: bool = False, # Enables multi-object segmentation. 742 ): 743 """Add point prompts (in (y, x) order) to the persistent SAM2 state, one object at a time. 744 745 Several points can be added in a single call. A point already pushed in an earlier call (same 746 object, frame, rounded position and label) is skipped, so re-running with the full prompt set 747 only pushes newly placed points. New points are appended ('clear_old_points=False') so they 748 correct the running segmentation instead of replacing it. 749 """ 750 if multiple_objects and object_id is not None: 751 raise ValueError("Cannot enable multi-object segmentation and also pass a fixed object id.") 752 if points is None or len(points) == 0: 753 return 754 755 points = np.asarray(points) 756 point_labels = np.asarray(point_labels) 757 if points.ndim != 2 or points.shape[1] != 2: 758 raise ValueError("'points' must have shape (N, 2).") 759 if len(points) != len(point_labels): 760 raise AssertionError("The number of points and labels do not match.") 761 762 n = len(points) 763 frame_ids = self._broadcast(frame_ids, n) 764 object_ids = self._broadcast(1 if object_id is None else object_id, n) 765 766 # The per-prompt masks are not read here, and consolidating them costs more than the prompt. 767 skip_output = getattr(self.predictor, "skip_prompt_output", None) 768 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 769 for frame_id, (y, x), label, obj_id in zip(frame_ids, points, point_labels, object_ids): 770 signature = (int(round(float(y))), int(round(float(x))), int(label)) 771 if signature in self._pushed_points.get((obj_id, frame_id), set()): 772 continue 773 self._apply_prompt_operation( 774 _PromptOperation( 775 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 776 clear_old_points=False, 777 points=np.array([[y, x]], dtype="float32"), 778 point_labels=np.array([label], dtype="int32"), 779 ) 780 )
Add point prompts (in (y, x) order) to the persistent SAM2 state, one object at a time.
Several points can be added in a single call. A point already pushed in an earlier call (same object, frame, rounded position and label) is skipped, so re-running with the full prompt set only pushes newly placed points. New points are appended ('clear_old_points=False') so they correct the running segmentation instead of replacing it.
782 def add_prompt_set( 783 self, 784 frame_id: int, 785 points: Optional[np.ndarray] = None, 786 point_labels: Optional[np.ndarray] = None, 787 box: Optional[np.ndarray] = None, 788 object_id: int = 1, 789 clear_old_points: bool = True, 790 ): 791 """Condition one object on a whole prompt set at once, in a single SAM2 call. 792 793 'add_point_prompts' pushes one point at a time, and 'add_box_prompts' pushes a box and then 794 replays the points it had to clear. That is what an annotator placing corrections needs: each 795 push returns the running segmentation, and re-running only sends what is new. A caller that 796 has the whole set up front pays for it, because every push re-runs the mask decoder on the 797 conditioning frame - eight of them for a box and seven points. SAM2 takes the set in one 798 call instead, with the box as the first two coordinates, which is also the order it wants. 799 800 The prompts are recorded in the same bookkeeping the incremental methods use, so the anchor 801 of each object and a replay onto a fresh state still see them. 802 803 Args: 804 frame_id: The slice to condition. 805 points: The points, (N, 2) in (y, x) order. None conditions on the box alone. 806 point_labels: One label per point: 1 positive, 0 negative. 807 box: An optional box, in (y0, x0, y1, x1) order. 808 object_id: The object being conditioned. 809 clear_old_points: Whether the push replaces what this object already carries on the 810 frame. SAM2 requires it whenever a box is given. False appends, which is how a 811 points-only push is added after a box. 812 """ 813 has_points = points is not None and len(points) > 0 814 if not has_points and box is None: 815 return 816 frame_id, object_id = int(frame_id), int(object_id) 817 if box is not None and not clear_old_points: 818 # Validate before touching bookkeeping or invoking SAM2, whose implementation rejects 819 # this combination as well. 820 raise ValueError("SAM2 requires 'clear_old_points=True' whenever a box is given.") 821 822 normalized_points, normalized_labels = None, None 823 if has_points: 824 points = np.asarray(points, dtype="float32").reshape(-1, 2) 825 if point_labels is None: 826 raise ValueError("'point_labels' is required when points are given.") 827 point_labels = np.asarray(point_labels, dtype="int32").reshape(-1) 828 if len(points) != len(point_labels): 829 raise AssertionError("The number of points and labels do not match.") 830 normalized_points, normalized_labels = points, point_labels 831 normalized_box = None if box is None else np.asarray(box, dtype="float32").reshape(4) 832 833 # The preview mask is discarded, as in the incremental methods. 834 skip_output = getattr(self.predictor, "skip_prompt_output", None) 835 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 836 self._apply_prompt_operation( 837 _PromptOperation( 838 kind="points_or_box", frame_id=frame_id, object_id=object_id, 839 clear_old_points=bool(clear_old_points), 840 points=normalized_points, point_labels=normalized_labels, box=normalized_box, 841 ) 842 )
Condition one object on a whole prompt set at once, in a single SAM2 call.
'add_point_prompts' pushes one point at a time, and 'add_box_prompts' pushes a box and then replays the points it had to clear. That is what an annotator placing corrections needs: each push returns the running segmentation, and re-running only sends what is new. A caller that has the whole set up front pays for it, because every push re-runs the mask decoder on the conditioning frame - eight of them for a box and seven points. SAM2 takes the set in one call instead, with the box as the first two coordinates, which is also the order it wants.
The prompts are recorded in the same bookkeeping the incremental methods use, so the anchor of each object and a replay onto a fresh state still see them.
Arguments:
- frame_id: The slice to condition.
- points: The points, (N, 2) in (y, x) order. None conditions on the box alone.
- point_labels: One label per point: 1 positive, 0 negative.
- box: An optional box, in (y0, x0, y1, x1) order.
- object_id: The object being conditioned.
- clear_old_points: Whether the push replaces what this object already carries on the frame. SAM2 requires it whenever a box is given. False appends, which is how a points-only push is added after a box.
844 def add_box_prompts( 845 self, 846 frame_ids: Union[int, List[int]], 847 boxes: Optional[np.ndarray] = None, 848 object_id: Optional[Union[int, List[int]]] = None, 849 ): 850 """Add box prompts (in (y0, x0, y1, x1) order) to the persistent SAM2 state. 851 852 A box is pushed at most once per (object, frame); re-running with the same box is a no-op. 853 SAM2 requires the box before any point on the same object/frame, so a box clears existing 854 points ('clear_old_points=True'); we re-add any already-pushed points afterwards so a box and 855 its correction points combine regardless of the order they were drawn in. 856 """ 857 if boxes is None or len(boxes) == 0: 858 return 859 860 boxes = [np.asarray(b) for b in boxes] 861 n = len(boxes) 862 frame_ids = self._broadcast(frame_ids, n) 863 object_ids = self._broadcast(1 if object_id is None else object_id, n) 864 865 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 866 # consolidating it costs a pass over every object of the state. 867 skip_output = getattr(self.predictor, "skip_prompt_output", None) 868 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 869 for frame_id, box, obj_id in zip(frame_ids, boxes, object_ids): 870 key = (obj_id, frame_id) 871 signature = tuple(np.round(box).astype(int).tolist()) 872 if signature in self._pushed_boxes.get(key, set()): 873 continue 874 existing_points = sorted(self._pushed_points.get(key, set())) 875 self._apply_prompt_operation( 876 _PromptOperation( 877 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 878 clear_old_points=True, box=np.asarray(box, dtype="float32").reshape(4), 879 ) 880 ) 881 for y, x, label in existing_points: 882 self._apply_prompt_operation( 883 _PromptOperation( 884 kind="points_or_box", frame_id=frame_id, object_id=obj_id, 885 clear_old_points=False, 886 points=np.array([[y, x]], dtype="float32"), 887 point_labels=np.array([label], dtype="int32"), 888 ) 889 )
Add box prompts (in (y0, x0, y1, x1) order) to the persistent SAM2 state.
A box is pushed at most once per (object, frame); re-running with the same box is a no-op. SAM2 requires the box before any point on the same object/frame, so a box clears existing points ('clear_old_points=True'); we re-add any already-pushed points afterwards so a box and its correction points combine regardless of the order they were drawn in.
902 def add_mask_prompts( 903 self, 904 frame_ids: Union[int, List[int]], 905 masks: Optional[List[np.ndarray]] = None, 906 object_id: Optional[Union[int, List[int]]] = None, 907 refine: bool = True, 908 ): 909 """Add mask prompts (full-resolution 2d boolean masks) to the persistent SAM2 state. 910 911 A napari polygon or ellipse is filled into a mask (from 'shape_layer_to_prompts'). We first 912 refine the drawn shape into the object on its seed frame (box + soft mask-logit cue, as in 913 the per-slice path), then seed propagation with the refined mask - so the seed slice matches 914 the per-slice result instead of reproducing the raw outline. SAM2's video predictor conditions 915 a frame on either a mask or points/box (not both), so a mask prompt does not combine with 916 points on the same object/frame. A mask already pushed (same object, frame, content) is 917 skipped so re-runs only add newly drawn masks. 918 919 Args: 920 frame_ids: The slice each mask conditions, one per mask or one for all of them. 921 masks: The masks, at the volume's full resolution. 922 object_id: The object each mask belongs to, one per mask or one for all of them. 923 refine: Whether to refine each mask into the object on its frame first. True for a shape 924 somebody drew; False for a mask that is already a prediction for this frame, which a 925 second refinement would only pull away from what it was accepted as. 926 """ 927 if masks is None or len(masks) == 0: 928 return 929 930 masks = [np.asarray(m) for m in masks] 931 n = len(masks) 932 frame_ids = self._broadcast(frame_ids, n) 933 object_ids = self._broadcast(1 if object_id is None else object_id, n) 934 935 # As in 'add_point_prompts': the preview mask each push returns is discarded here, and 936 # consolidating it costs a pass over every object of the state. 937 skip_output = getattr(self.predictor, "skip_prompt_output", None) 938 with (skip_output() if skip_output is not None else contextlib.nullcontext()): 939 for frame_id, mask, obj_id in zip(frame_ids, masks, object_ids): 940 key = (obj_id, frame_id) 941 # A stable digest, so the signature does not change between processes. 942 signature = hashlib.sha1(np.ascontiguousarray(mask).tobytes()).hexdigest() 943 if signature in self._pushed_masks.get(key, {}): 944 continue 945 946 # Refined on the seed frame first, so the propagation starts from the object rather 947 # than from the drawn shape. The box is the filled mask's extent. 948 ys, xs = np.nonzero(mask) 949 if len(ys) == 0: 950 continue 951 if refine: 952 box = np.array([xs.min(), ys.min(), xs.max(), ys.max()], dtype="float32") # (x0,y0,x1,y1) 953 mask = self._image_style_predict(frame_id, box=box, mask=mask) 954 955 prepared = self._prepare_mask(mask) 956 self._apply_prompt_operation( 957 _PromptOperation( 958 kind="mask", frame_id=frame_id, object_id=obj_id, 959 mask_signature=signature, mask=prepared, 960 ) 961 )
Add mask prompts (full-resolution 2d boolean masks) to the persistent SAM2 state.
A napari polygon or ellipse is filled into a mask (from 'shape_layer_to_prompts'). We first refine the drawn shape into the object on its seed frame (box + soft mask-logit cue, as in the per-slice path), then seed propagation with the refined mask - so the seed slice matches the per-slice result instead of reproducing the raw outline. SAM2's video predictor conditions a frame on either a mask or points/box (not both), so a mask prompt does not combine with points on the same object/frame. A mask already pushed (same object, frame, content) is skipped so re-runs only add newly drawn masks.
Arguments:
- frame_ids: The slice each mask conditions, one per mask or one for all of them.
- masks: The masks, at the volume's full resolution.
- object_id: The object each mask belongs to, one per mask or one for all of them.
- refine: Whether to refine each mask into the object on its frame first. True for a shape somebody drew; False for a mask that is already a prediction for this frame, which a second refinement would only pull away from what it was accepted as.
1034 def propagate_prompts( 1035 self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0, return_logits=False 1036 ): 1037 """Propagate the pushed prompts through the volume, one pass per conditioned slice. 1038 1039 SAM2 propagates every object of a state from the earliest slice any of them is conditioned on, 1040 and skips the backward pass entirely when that slice is 0. Objects anchored later would be 1041 tracked - and have those results written into their memory - before they are conditioned, and 1042 would never be propagated backwards at all. So objects that share an anchor are propagated 1043 together and the rest get a state of their own. 1044 1045 SAM2 builds its memory from the sigmoid of the logits, not from the thresholded masks. So 1046 thresholding the returned logits at 't' gives the masks of 'mask_threshold=t', except on the 1047 slices that early stopping skipped. SAM2 sets all logits of a slice to -1024 where it predicts 1048 that the object is absent, so a negative threshold does not recover such slices. 1049 1050 Args: 1051 update_progress: Optional callback invoked with the number of newly processed slices. 1052 early_stop_patience: Stop a direction after this many consecutive empty slices. 1053 'None' propagates to the end of the volume. 1054 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1055 mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too. 1056 return_logits: Return the float32 mask logits instead of the boolean masks. This keeps 1057 4 bytes per pixel, object and slice, so use it only for a few objects. 1058 1059 Returns: 1060 Mapping from slice index to {object id: mask (1, H, W)}. The video predictor pads non-square 1061 slices to a square, so crop each mask to '[:, :H, :W]' of the original slice shape. 1062 """ 1063 propagate_kwargs = dict( 1064 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1065 mask_threshold=mask_threshold, return_logits=return_logits, 1066 ) 1067 groups = {} 1068 for object_id, frame in self._anchor_per_object().items(): 1069 groups.setdefault(frame, []).append(object_id) 1070 if len(groups) <= 1: 1071 return self._propagate_both_directions(**propagate_kwargs) 1072 1073 # The active maps intentionally omit replaced prompts. Reconstruct from successful calls so 1074 # point batches, replacement boundaries and the previous-logit chain stay unchanged. 1075 snapshot = tuple(operation.copied() for operation in self._prompt_history) 1076 prompt_signatures = set(self._prompt_signatures) 1077 video_segments = {} 1078 for object_ids in groups.values(): 1079 self._replay_prompts(snapshot, set(object_ids)) 1080 for frame, per_object in self._propagate_both_directions(**propagate_kwargs).items(): 1081 video_segments.setdefault(frame, {}).update(per_object) 1082 1083 self._replay_prompts(snapshot, set().union(*groups.values())) 1084 self._prompt_signatures = prompt_signatures 1085 return video_segments
Propagate the pushed prompts through the volume, one pass per conditioned slice.
SAM2 propagates every object of a state from the earliest slice any of them is conditioned on, and skips the backward pass entirely when that slice is 0. Objects anchored later would be tracked - and have those results written into their memory - before they are conditioned, and would never be propagated backwards at all. So objects that share an anchor are propagated together and the rest get a state of their own.
SAM2 builds its memory from the sigmoid of the logits, not from the thresholded masks. So thresholding the returned logits at 't' gives the masks of 'mask_threshold=t', except on the slices that early stopping skipped. SAM2 sets all logits of a slice to -1024 where it predicts that the object is absent, so a negative threshold does not recover such slices.
Arguments:
- update_progress: Optional callback invoked with the number of newly processed slices.
- early_stop_patience: Stop a direction after this many consecutive empty slices. 'None' propagates to the end of the volume.
- z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices.
- mask_threshold: The logit threshold that binarizes the masks. Early stopping uses it too.
- return_logits: Return the float32 mask logits instead of the boolean masks. This keeps 4 bytes per pixel, object and slice, so use it only for a few objects.
Returns:
Mapping from slice index to {object id: mask (1, H, W)}. The video predictor pads non-square slices to a square, so crop each mask to '[:, :H, :W]' of the original slice shape.
1178 def segment_slice( 1179 self, 1180 frame_idx: int, 1181 points: Optional[np.ndarray] = None, 1182 labels: Optional[np.ndarray] = None, 1183 boxes: Optional[List] = None, 1184 masks: Optional[List] = None, 1185 object_id: int = 1, 1186 ): 1187 """Segment a single slice using SAM2 video predictor. 1188 1189 Args: 1190 frame_idx: Slice index to segment. 1191 points: Point prompts (N, 2) array. 1192 labels: Point labels (N,) array. 1193 boxes: List of box prompts. 1194 masks: List of mask prompts (can be None). 1195 object_id: Object ID to use for the segmentation (default: 1). 1196 1197 Returns: 1198 Segmentation mask for the slice (2D array), or None if no valid prompts provided. 1199 """ 1200 have_points = points is not None and len(points) > 0 1201 have_boxes = boxes is not None and len(boxes) > 0 1202 have_masks = masks is not None and any(m is not None for m in masks) 1203 1204 if not have_points and not have_boxes and not have_masks: 1205 return None 1206 1207 try: 1208 if have_masks: 1209 # Refined the way the 2d predictor does, rather than through 'add_new_mask', which 1210 # hard-conditions on the drawn shape and returns it verbatim. 1211 seg = self._refine_slice_from_mask( 1212 frame_idx, boxes=boxes, masks=masks, 1213 points=points if have_points else None, labels=labels if have_points else None, 1214 ) 1215 else: 1216 box = boxes[0] if have_boxes else None 1217 _, out_obj_ids, out_mask_logits = self.predictor.add_new_points_or_box( 1218 inference_state=self.inference_state, 1219 frame_idx=frame_idx, 1220 obj_id=object_id, 1221 points=points if have_points else None, 1222 labels=labels if have_points else None, 1223 box=box, 1224 ) 1225 1226 mask_logits = out_mask_logits[0] # (num_objects, 1, H, W), so this is the first object. 1227 seg = (mask_logits.squeeze() > 0.0).cpu().numpy() 1228 1229 # Crop back to the original slice shape (the video predictor pads non-square frames). 1230 seg = _crop_to_original_shape(seg, self.volume.shape[1:3]).astype("uint32") 1231 1232 finally: 1233 # Clear this object's prompts and their bookkeeping, so the next round starts fresh. 1234 self.predictor.reset_state(self.inference_state) 1235 self._clear_pushed_prompts() 1236 1237 return seg
Segment a single slice using SAM2 video predictor.
Arguments:
- frame_idx: Slice index to segment.
- points: Point prompts (N, 2) array.
- labels: Point labels (N,) array.
- boxes: List of box prompts.
- masks: List of mask prompts (can be None).
- object_id: Object ID to use for the segmentation (default: 1).
Returns:
Segmentation mask for the slice (2D array), or None if no valid prompts provided.
1239 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1240 """Propagate the pushed prompts and paint the objects into one label volume. 1241 1242 Where objects overlap, the object with the higher id wins. 1243 1244 Args: 1245 update_progress: Optional callback invoked with the number of newly processed slices. 1246 early_stop_patience: Stop a direction after this many consecutive empty slices. 1247 'None' propagates to the end of the volume. 1248 z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices. 1249 mask_threshold: The logit threshold that binarizes the masks. 1250 1251 Returns: 1252 The label volume, with the shape of the input volume. 1253 """ 1254 video_segments = self.propagate_prompts( 1255 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1256 mask_threshold=mask_threshold, 1257 ) 1258 1259 # Indexed by slice id, so the frames early stopping skipped stay background rather than 1260 # shifting the rest out of alignment. 1261 shape = self.volume.shape[1:3] 1262 segmentation = np.zeros((self.volume.shape[0],) + tuple(shape), dtype="uint64") 1263 for slice_idx, instances in video_segments.items(): 1264 per_slice_seg = segmentation[slice_idx] 1265 for instance_idx, instance_mask in instances.items(): 1266 mask = _crop_to_original_shape(instance_mask.squeeze(), shape) 1267 per_slice_seg[mask] = instance_idx 1268 1269 return segmentation
Propagate the pushed prompts and paint the objects into one label volume.
Where objects overlap, the object with the higher id wins.
Arguments:
- update_progress: Optional callback invoked with the number of newly processed slices.
- early_stop_patience: Stop a direction after this many consecutive empty slices. 'None' propagates to the end of the volume.
- z_range: An optional inclusive '(z_min, z_max)' bound on the propagated slices.
- mask_threshold: The logit threshold that binarizes the masks.
Returns:
The label volume, with the shape of the input volume.
1272class ReplicatedPromptableSegmentation3D: 1273 """One `PromptableSegmentation3D` per inference device over the same volume, for independent passes. 1274 1275 Automatic prompt generation propagates a volume in passes that share nothing but the volume and 1276 its embeddings: each conditions its own objects on one slice and tracks them to both ends. So a 1277 pass goes to whichever device is free, with one video-predictor state per device rather than one 1278 in total. `TiledPromptableSegmentation3D` spreads tiles for the same reason; this spreads the 1279 passes of a volume that is not tiled, where one state covers the whole volume. 1280 1281 Device memory is the cost: a state per device instead of a state in total. Pass a single device 1282 to give that back. 1283 1284 Args: 1285 predictor: The SAM2 video predictor. 1286 volume: The input volume, shape (Z, Y, X). 1287 volume_embeddings: The precomputed 3d embeddings. 1288 devices: Devices the passes are spread over. By default all visible CUDA devices are used 1289 when the predictor is on CUDA. Pass a single device to pin the propagation to it. 1290 """ 1291 1292 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1293 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1294 1295 self._predictor_devices = _prepare_models(predictor, _resolve_devices(predictor, devices)) 1296 self.volume = volume 1297 self.volume_embeddings = volume_embeddings 1298 self._kwargs = kwargs 1299 # Built lazily, so a run with fewer passes than devices never pays for a state it cannot use. 1300 self._segmenters = {} 1301 1302 def _get_segmenter(self, worker_id): 1303 if worker_id not in self._segmenters: 1304 predictor, device = self._predictor_devices[worker_id] 1305 self._segmenters[worker_id] = PromptableSegmentation3D( 1306 predictor, self.volume, self.volume_embeddings, device=device, **self._kwargs 1307 ) 1308 return self._segmenters[worker_id] 1309 1310 @property 1311 def predictor_devices(self): 1312 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1313 return self._predictor_devices 1314 1315 def map_passes(self, jobs: List, function: Callable, update_progress=None) -> List: 1316 """Run one job per pass, one worker per device, each taking the next job once it is free. 1317 1318 `function` is called as `function(segmenter, job)` with the worker's own state, so a job may 1319 prompt and propagate it freely. The results keep the order the jobs were given in, which the 1320 merge needs: it breaks score ties by record order. 1321 """ 1322 devices = [device for _, device in self._predictor_devices] 1323 return map_jobs_over_devices( 1324 devices, jobs, lambda worker_id, job: function(self._get_segmenter(worker_id), job), 1325 update_progress=update_progress, 1326 ) 1327 1328 def reset_predictor(self): 1329 """Free every worker's video-predictor state.""" 1330 for segmenter in self._segmenters.values(): 1331 segmenter.reset_predictor() 1332 self._segmenters = {}
One PromptableSegmentation3D per inference device over the same volume, for independent passes.
Automatic prompt generation propagates a volume in passes that share nothing but the volume and
its embeddings: each conditions its own objects on one slice and tracks them to both ends. So a
pass goes to whichever device is free, with one video-predictor state per device rather than one
in total. TiledPromptableSegmentation3D spreads tiles for the same reason; this spreads the
passes of a volume that is not tiled, where one state covers the whole volume.
Device memory is the cost: a state per device instead of a state in total. Pass a single device to give that back.
Arguments:
- predictor: The SAM2 video predictor.
- volume: The input volume, shape (Z, Y, X).
- volume_embeddings: The precomputed 3d embeddings.
- devices: Devices the passes are spread over. By default all visible CUDA devices are used when the predictor is on CUDA. Pass a single device to pin the propagation to it.
1292 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1293 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1294 1295 self._predictor_devices = _prepare_models(predictor, _resolve_devices(predictor, devices)) 1296 self.volume = volume 1297 self.volume_embeddings = volume_embeddings 1298 self._kwargs = kwargs 1299 # Built lazily, so a run with fewer passes than devices never pays for a state it cannot use. 1300 self._segmenters = {}
1310 @property 1311 def predictor_devices(self): 1312 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1313 return self._predictor_devices
The (predictor, device) replica per inference device, for a caller that needs its own.
1315 def map_passes(self, jobs: List, function: Callable, update_progress=None) -> List: 1316 """Run one job per pass, one worker per device, each taking the next job once it is free. 1317 1318 `function` is called as `function(segmenter, job)` with the worker's own state, so a job may 1319 prompt and propagate it freely. The results keep the order the jobs were given in, which the 1320 merge needs: it breaks score ties by record order. 1321 """ 1322 devices = [device for _, device in self._predictor_devices] 1323 return map_jobs_over_devices( 1324 devices, jobs, lambda worker_id, job: function(self._get_segmenter(worker_id), job), 1325 update_progress=update_progress, 1326 )
Run one job per pass, one worker per device, each taking the next job once it is free.
function is called as function(segmenter, job) with the worker's own state, so a job may
prompt and propagate it freely. The results keep the order the jobs were given in, which the
merge needs: it breaks score ties by record order.
1335class TiledPromptableSegmentation3D: 1336 """Tiled promptable segmentation for volumetric data. 1337 1338 Routes each prompt to the in-plane tile-column it falls in, runs a per-tile 1339 `PromptableSegmentation3D` on the tile's sub-volume (reusing the precomputed tiled embeddings), 1340 and stitches the per-tile results into the full volume. Exposes the same interface as 1341 `PromptableSegmentation3D`, so it is a drop-in replacement when the embeddings are tiled. 1342 1343 Args: 1344 predictor: The SAM2 video predictor. 1345 volume: The input volume, shape (Z, Y, X). 1346 volume_embeddings: The precomputed tiled 3d embeddings (with per-tile `features`/`pos_enc`/ 1347 `fpn` groups and `shape`/`tile_shape`/`halo` attrs). See `precompute_image_embeddings`. 1348 devices: Devices used for independent tile columns. By default all visible CUDA devices 1349 are used when the predictor is on CUDA. Pass a single device to pin inference to it. 1350 """ 1351 1352 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1353 from bioimage_cpp.utils import Blocking 1354 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1355 1356 resolved_devices = _resolve_devices(predictor, devices) 1357 self._predictor_devices = _prepare_models(predictor, resolved_devices) 1358 1359 self.predictor = predictor 1360 self.volume = volume 1361 self.volume_embeddings = volume_embeddings 1362 self._kwargs = kwargs 1363 1364 feats = volume_embeddings["features"] 1365 self.shape = tuple(int(s) for s in feats.attrs["shape"]) 1366 self.tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"]) 1367 self.halo = tuple(int(s) for s in feats.attrs["halo"]) 1368 self.tiling = Blocking([0, 0], list(self.shape[1:]), list(self.tile_shape)) 1369 1370 # State per (tile, worker), built lazily for the tiles that actually receive prompts. Keyed by 1371 # the worker as well, so 'map_tile_jobs' can put a tile's passes on several devices at once. 1372 self._segmenters = {} 1373 # Device assigned to each active tile, see '_worker_id'. 1374 self._tile_workers = {} 1375 # The worker a thread is running as, which overrides the per-tile assignment while it is set. 1376 self._active_worker = threading.local() 1377 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 1378 self._prompt_signatures = set() 1379 1380 def init_predictor(self): 1381 # Per-tile inference states are created lazily in '_get_segmenter'. 1382 pass 1383 1384 def sync_prompt_state(self, signatures): 1385 """Discard the per-tile states when prompts were removed or changed since the last round. 1386 1387 See `PromptableSegmentation3D.sync_prompt_state`. The prompt set is compared once for the 1388 whole volume, because a moved prompt can change which tile it belongs to. 1389 1390 Args: 1391 signatures: Hashable descriptors of every prompt currently in the annotation layers. 1392 """ 1393 signatures = set(signatures) 1394 if not self._prompt_signatures.issubset(signatures): 1395 self.reset_predictor() 1396 self._prompt_signatures = signatures 1397 1398 def reset_predictor(self): 1399 # Each holds an inference state and an embedding cache; they are rebuilt lazily. 1400 for segmenter in self._segmenters.values(): 1401 segmenter.reset_predictor() 1402 self._segmenters = {} 1403 self._tile_workers = {} 1404 self._prompt_signatures = set() 1405 _free_device_memory() 1406 1407 def get_progress_total(self, z_range=None): 1408 """Return tile-slice propagation steps for the currently active tiles.""" 1409 return sum(segmenter.get_progress_total(z_range) for segmenter in self._segmenters.values()) 1410 1411 def _tile_index(self, y, x): 1412 """Return the id of the tile whose inner (halo-free) block contains the point (y, x).""" 1413 for tile_id in range(self.tiling.number_of_blocks): 1414 inner = self.tiling.get_block_with_halo(tile_id, list(self.halo)).inner_block 1415 if inner.begin[0] <= y < inner.end[0] and inner.begin[1] <= x < inner.end[1]: 1416 return tile_id 1417 return 0 1418 1419 def _worker_id(self, tile_id): 1420 """Return the device a tile is bound to, assigned round-robin when the tile is first used. 1421 1422 The tile state (inference state + embedding cache) lives on one device, so the affinity is 1423 kept for the tile's lifetime. Assigning by 'tile_id % n_devices' instead would leave devices 1424 idle, because the active tile ids are sparse (e.g. the tiles 0, 2, 4 share one residue). 1425 1426 A thread running as a worker uses that worker's device instead, so two workers can hold the 1427 same tile without either reaching into the other's state. 1428 """ 1429 bound = getattr(self._active_worker, "index", None) 1430 if bound is not None: 1431 return bound 1432 if tile_id not in self._tile_workers: 1433 self._tile_workers[tile_id] = len(self._tile_workers) % len(self._predictor_devices) 1434 return self._tile_workers[tile_id] 1435 1436 @contextlib.contextmanager 1437 def _as_worker(self, worker_id): 1438 """Run this thread as one worker: its device, and its own state for whatever tile it touches.""" 1439 self._active_worker.index = worker_id 1440 try: 1441 with _device_context(self._predictor_devices[worker_id][1]): 1442 yield 1443 finally: 1444 self._active_worker.index = None 1445 1446 def _outer_offset(self, tile_id): 1447 """Return the (y0, x0) origin of the tile's outer (halo-included) block.""" 1448 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1449 return int(outer.begin[0]), int(outer.begin[1]) 1450 1451 def _get_segmenter(self, tile_id): 1452 key = (tile_id, self._worker_id(tile_id)) 1453 if key not in self._segmenters: 1454 from micro_sam.v2.util import _load_list_datasets 1455 1456 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1457 bb = (slice(int(outer.begin[0]), int(outer.end[0])), slice(int(outer.begin[1]), int(outer.end[1]))) 1458 sub_volume = np.ascontiguousarray(self.volume[:, bb[0], bb[1]]) 1459 1460 feats = self.volume_embeddings["features"] 1461 tile_dataset = feats[str(tile_id)] 1462 # Lazy, so the tile-column is streamed a frame at a time rather than materialised. 1463 tile_embeddings = { 1464 "features": tile_dataset, 1465 "pos_enc": _load_list_datasets(self.volume_embeddings["pos_enc"], str(tile_id), lazy_loading=True), 1466 "fpn": _load_list_datasets(self.volume_embeddings["fpn"], str(tile_id), lazy_loading=True), 1467 "input_size": tile_dataset.attrs["input_size"], 1468 "original_size": tile_dataset.attrs["original_size"], 1469 } 1470 predictor, device = self._predictor_devices[key[1]] 1471 self._segmenters[key] = PromptableSegmentation3D( 1472 predictor, sub_volume, tile_embeddings, device=device, **self._kwargs 1473 ) 1474 return self._segmenters[key] 1475 1476 def _inner_slices(self, tile_id): 1477 """Return the (local, global) inner-block slices for placing a tile result into the volume.""" 1478 block = self.tiling.get_block_with_halo(tile_id, list(self.halo)) 1479 local = tuple(slice(b, e) for b, e in zip(block.inner_block_local.begin, block.inner_block_local.end)) 1480 glob = tuple(slice(b, e) for b, e in zip(block.inner_block.begin, block.inner_block.end)) 1481 return local, glob 1482 1483 def map_tiles( 1484 self, tile_ids: List[int], function: Callable, update_progress: Optional[Callable[[int], None]] = None, 1485 ) -> List[Tuple]: 1486 """Run one job per tile, one worker per device, each pulling the next tile once it is free. 1487 1488 A tile that already holds a state keeps the device that state lives on. An unassigned tile is 1489 bound to whichever worker picks it up, so tiles with very different costs (as in automatic 1490 prompt generation, where a tile costs what its candidates cost) balance over the devices 1491 instead of being dealt out round-robin before their cost is known. 1492 """ 1493 tile_ids = list(tile_ids) 1494 if not tile_ids: 1495 return [] 1496 1497 preassigned = {} 1498 unassigned = queue.Queue() 1499 for tile_id in tile_ids: 1500 if tile_id in self._tile_workers: 1501 preassigned.setdefault(self._tile_workers[tile_id], []).append(tile_id) 1502 else: 1503 unassigned.put(tile_id) 1504 1505 def run_worker(worker_id, worker_update=None): 1506 def call(tile_id): 1507 return function(tile_id) if worker_update is None else function(tile_id, worker_update) 1508 1509 results = [] 1510 with self._as_worker(worker_id): 1511 for tile_id in preassigned.get(worker_id, []): 1512 results.append((tile_id, call(tile_id))) 1513 while True: 1514 try: 1515 tile_id = unassigned.get_nowait() 1516 except queue.Empty: 1517 break 1518 self._tile_workers[tile_id] = worker_id 1519 results.append((tile_id, call(tile_id))) 1520 return results 1521 1522 if len(self._predictor_devices) < 2: 1523 return sorted(run_worker(0, update_progress), key=lambda result: result[0]) 1524 1525 progress_queue = queue.Queue() 1526 1527 def forward_progress(): 1528 increment = 0 1529 while True: 1530 try: 1531 increment += int(progress_queue.get_nowait()) 1532 except queue.Empty: 1533 break 1534 if increment: 1535 update_progress(increment) 1536 1537 results = [] 1538 n_workers = len(self._predictor_devices) 1539 with futures.ThreadPoolExecutor(max_workers=n_workers) as pool: 1540 worker_update = progress_queue.put if update_progress is not None else None 1541 tasks = [pool.submit(run_worker, worker_id, worker_update) for worker_id in range(n_workers)] 1542 pending = set(tasks) 1543 while pending: 1544 done, pending = futures.wait(pending, timeout=0.05, return_when=futures.FIRST_COMPLETED) 1545 forward_progress() 1546 for task in done: 1547 results.extend(task.result()) 1548 forward_progress() 1549 return sorted(results, key=lambda result: result[0]) 1550 1551 @property 1552 def predictor_devices(self): 1553 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1554 return self._predictor_devices 1555 1556 @property 1557 def active_tiles(self) -> List[int]: 1558 """The tiles that currently hold a state, in ascending order.""" 1559 return sorted({tile_id for tile_id, _ in self._segmenters}) 1560 1561 def map_tile_jobs(self, jobs: List, function: Callable, update_progress=None) -> List: 1562 """Run jobs that each name a tile, one worker per device, each on its own state for that tile. 1563 1564 Unlike `map_tiles`, several jobs of one tile can run at once: a job prompts the state of its 1565 tile *on its worker's device*, so a single tile whose work dwarfs the others spreads over the 1566 devices instead of pinning them to one. The extra states are what it costs, and a job that 1567 moves to a new device re-reads that tile's features, so give a job enough work to pay for it. 1568 1569 `function` is called as `function(job)`, and `update_progress` from the worker rather than 1570 from the caller's thread - unlike `map_tiles`, whose callback the GUI drives. 1571 """ 1572 devices = [device for _, device in self._predictor_devices] 1573 1574 def run(worker_id, job): 1575 with self._as_worker(worker_id): 1576 return function(job) 1577 1578 return map_jobs_over_devices(devices, jobs, run, update_progress=update_progress) 1579 1580 def reset_tile_tracking(self, tile_id: int) -> None: 1581 """Reset one tile's tracked objects, keeping its cached encoding. A no-op before its first use.""" 1582 segmenter = self._segmenters.get((tile_id, self._worker_id(tile_id))) 1583 if segmenter is not None: 1584 segmenter.reset_tracking() 1585 1586 def propagate_tile(self, tile_id: int, update_progress=None, early_stop_patience=None, z_range=None): 1587 """Propagate one tile's prompts, returning its own segments and its outer (halo-included) block. 1588 1589 Never merges across tiles, unlike `predict`, which stitches by object identity: it is for a 1590 caller whose object ids are tile-local, e.g. automatic prompt generation, where a candidate 1591 belongs to exactly one tile and its id would otherwise collide with another tile's. 1592 """ 1593 video_segments = self._get_segmenter(tile_id).propagate_prompts( 1594 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1595 ) 1596 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1597 bounding_box = tuple(slice(int(b), int(e)) for b, e in zip(outer.begin, outer.end)) 1598 return video_segments, bounding_box 1599 1600 def release_tile(self, tile_id: int) -> None: 1601 """Free one tile's video-predictor state, leaving the other tiles' states alive. 1602 1603 Keeps the CUDA cache rather than emptying it: the next state on this device is the same size, 1604 so the allocator reuses the blocks, and a collection from every worker after every job costs 1605 more than it frees - it holds the interpreter lock while the other devices wait for work. 1606 """ 1607 segmenter = self._segmenters.pop((tile_id, self._worker_id(tile_id)), None) 1608 self._tile_workers.pop(tile_id, None) 1609 if segmenter is not None: 1610 segmenter.release() 1611 1612 def segment_slice(self, frame_idx, points=None, labels=None, boxes=None, masks=None, object_id=1): 1613 """Segment a single slice. Points are (x, y), boxes (x0, y0, x1, y1), as passed by the annotator. 1614 1615 Groups the prompts by the tile they fall in, segments every tile with a positive cue, and 1616 unions the per-tile masks - so an object spanning tiles is segmented on both sides. 1617 """ 1618 have_points = points is not None and len(points) > 0 1619 have_boxes = boxes is not None and len(boxes) > 0 1620 have_masks = masks is not None and any(m is not None for m in masks) 1621 if not have_points and not have_boxes and not have_masks: 1622 return None 1623 1624 tile_points, tile_labels, tile_boxes, tile_masks = {}, {}, {}, {} 1625 if have_points: 1626 for point, label in zip(np.asarray(points), np.asarray(labels)): 1627 tid = self._tile_index(int(round(point[1])), int(round(point[0]))) # (y, x) from (x, y) 1628 tile_points.setdefault(tid, []).append(point) 1629 tile_labels.setdefault(tid, []).append(label) 1630 if have_boxes: 1631 for bidx, box in enumerate(boxes): 1632 box = np.asarray(box) # (x0, y0, x1, y1) 1633 box_yx = np.array([box[1], box[0], box[3], box[2]]) 1634 box_mask = masks[bidx] if masks is not None else None 1635 for tid, clipped in _box_to_tiles(self.tiling, self.halo, box_yx).items(): 1636 tile_boxes.setdefault(tid, []).append(np.array([clipped[1], clipped[0], clipped[3], clipped[2]])) 1637 tile_masks.setdefault(tid, []).append( 1638 None if box_mask is None else _crop_mask_to_tile(self.tiling, self.halo, tid, box_mask) 1639 ) 1640 1641 tile_jobs = {} 1642 for tile_id in sorted(set(tile_points) | set(tile_boxes)): 1643 tpoints = np.asarray(tile_points.get(tile_id, [])).reshape(-1, 2) 1644 tlabels = np.asarray(tile_labels.get(tile_id, []), dtype=int) 1645 tboxes = tile_boxes.get(tile_id, []) 1646 if not ((tlabels == 1).any() or len(tboxes) > 0): 1647 continue 1648 y0, x0 = self._outer_offset(tile_id) 1649 local_points = (tpoints - np.array([x0, y0])) if len(tpoints) else None 1650 local_boxes = [b - np.array([x0, y0, x0, y0]) for b in tboxes] if tboxes else None 1651 local_masks = tile_masks.get(tile_id) if tboxes else None 1652 tile_jobs[tile_id] = ( 1653 local_points, 1654 tlabels if len(tlabels) else None, 1655 local_boxes, 1656 local_masks, 1657 ) 1658 1659 def segment_tile(tile_id): 1660 local_points, local_labels, local_boxes, local_masks = tile_jobs[tile_id] 1661 return self._get_segmenter(tile_id).segment_slice( 1662 frame_idx, points=local_points, labels=local_labels, 1663 boxes=local_boxes, masks=local_masks, object_id=object_id, 1664 ) 1665 1666 out = np.zeros(self.shape[1:], dtype="uint32") 1667 found = False 1668 for tile_id, tile_seg in self.map_tiles(sorted(tile_jobs), segment_tile): 1669 if tile_seg is None: 1670 continue 1671 local, glob = self._inner_slices(tile_id) 1672 region = tile_seg[local] 1673 sub = out[glob] 1674 positive = region > 0 1675 sub[positive] = region[positive] 1676 found = True 1677 1678 return out if found else None 1679 1680 def add_point_prompts(self, frame_ids, points, point_labels, object_id=None, multiple_objects=False): 1681 """Add point prompts. Points are in (y, x) order. Each is routed to the tile it falls in, so 1682 an object with prompts in several tiles is added to each of those tiles.""" 1683 if points is None or len(points) == 0: 1684 return 1685 if object_id is None: 1686 object_id = 1 1687 1688 tile_points, tile_labels = {}, {} 1689 for point, label in zip(np.asarray(points), np.asarray(point_labels)): 1690 tid = self._tile_index(int(round(point[0])), int(round(point[1]))) 1691 tile_points.setdefault(tid, []).append(point) 1692 tile_labels.setdefault(tid, []).append(label) 1693 1694 for tile_id, tpoints in tile_points.items(): 1695 y0, x0 = self._outer_offset(tile_id) 1696 local_points = np.asarray(tpoints) - np.array([y0, x0]) 1697 self._get_segmenter(tile_id).add_point_prompts( 1698 frame_ids=frame_ids, points=local_points, point_labels=np.asarray(tile_labels[tile_id]), 1699 object_id=object_id, multiple_objects=multiple_objects, 1700 ) 1701 1702 def add_box_prompts(self, frame_ids, boxes=None, object_id=None): 1703 """Add box prompts (y0, x0, y1, x1). A box spanning several tiles is added, clipped, to each.""" 1704 if boxes is None or len(boxes) == 0: 1705 return 1706 # One object id per box. Default to a single object (id 1) when not batched. 1707 if object_id is None: 1708 object_id = [1] * len(boxes) 1709 elif not isinstance(object_id, list): 1710 object_id = [object_id] * len(boxes) 1711 # Group the (clipped) boxes and their object ids by the tile each falls in. 1712 tile_boxes, tile_ids = {}, {} 1713 for box, obj_id in zip(boxes, object_id): 1714 for tid, clipped in _box_to_tiles(self.tiling, self.halo, np.asarray(box)).items(): 1715 tile_boxes.setdefault(tid, []).append(clipped) 1716 tile_ids.setdefault(tid, []).append(obj_id) 1717 for tile_id, tboxes in tile_boxes.items(): 1718 y0, x0 = self._outer_offset(tile_id) 1719 local_boxes = [b - np.array([y0, x0, y0, x0]) for b in tboxes] 1720 self._get_segmenter(tile_id).add_box_prompts( 1721 frame_ids=frame_ids, boxes=np.array(local_boxes), object_id=tile_ids[tile_id], 1722 ) 1723 1724 def add_mask_prompts(self, frame_ids, masks=None, object_id=None, refine=True): 1725 """Add mask prompts. Each mask is routed to the tiles its filled region overlaps, cropped to 1726 each tile's outer block, and added there (so a mask spanning tiles is added on both sides).""" 1727 if masks is None or len(masks) == 0: 1728 return 1729 masks = [np.asarray(m) for m in masks] 1730 # One object id per mask. Default to a single object (id 1) when not batched. 1731 if object_id is None: 1732 object_id = [1] * len(masks) 1733 elif not isinstance(object_id, list): 1734 object_id = [object_id] * len(masks) 1735 1736 for mask, obj_id in zip(masks, object_id): 1737 ys, xs = np.nonzero(mask) 1738 if len(ys) == 0: 1739 continue 1740 box_yx = np.array([ys.min(), xs.min(), ys.max() + 1, xs.max() + 1]) 1741 for tid in _box_to_tiles(self.tiling, self.halo, box_yx): 1742 self._get_segmenter(tid).add_mask_prompts( 1743 frame_ids=frame_ids, masks=[_crop_mask_to_tile(self.tiling, self.halo, tid, mask)], 1744 object_id=obj_id, refine=refine, 1745 ) 1746 1747 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1748 """Propagate the prompts in every active tile and stitch the results into the full volume. 1749 1750 Object ids are preserved across tiles (the inner blocks are disjoint), so an object that was 1751 prompted in several tiles keeps one id and is merged across the tile boundaries. 1752 'mask_threshold' is the logit threshold that binarizes the masks. 1753 """ 1754 segmentation = np.zeros(self.shape, dtype="uint64") 1755 1756 def predict_tile(tile_id, tile_update=None): 1757 return self._get_segmenter(tile_id).predict( 1758 update_progress=tile_update, early_stop_patience=early_stop_patience, z_range=z_range, 1759 mask_threshold=mask_threshold, 1760 ) 1761 1762 for tile_id, tile_seg in self.map_tiles( 1763 self.active_tiles, predict_tile, update_progress=update_progress, 1764 ): 1765 local, glob = self._inner_slices(tile_id) 1766 inner = tile_seg[(slice(None),) + local] 1767 region = segmentation[(slice(None),) + glob] 1768 positive = inner != 0 1769 region[positive] = inner[positive] 1770 return segmentation
Tiled promptable segmentation for volumetric data.
Routes each prompt to the in-plane tile-column it falls in, runs a per-tile
PromptableSegmentation3D on the tile's sub-volume (reusing the precomputed tiled embeddings),
and stitches the per-tile results into the full volume. Exposes the same interface as
PromptableSegmentation3D, so it is a drop-in replacement when the embeddings are tiled.
Arguments:
- predictor: The SAM2 video predictor.
- volume: The input volume, shape (Z, Y, X).
- volume_embeddings: The precomputed tiled 3d embeddings (with per-tile
features/pos_enc/fpngroups andshape/tile_shape/haloattrs). Seeprecompute_image_embeddings. - devices: Devices used for independent tile columns. By default all visible CUDA devices are used when the predictor is on CUDA. Pass a single device to pin inference to it.
1352 def __init__(self, predictor, volume, volume_embeddings, devices: Devices = None, **kwargs): 1353 from bioimage_cpp.utils import Blocking 1354 from micro_sam.v2.batched_inference import _prepare_models, _resolve_devices 1355 1356 resolved_devices = _resolve_devices(predictor, devices) 1357 self._predictor_devices = _prepare_models(predictor, resolved_devices) 1358 1359 self.predictor = predictor 1360 self.volume = volume 1361 self.volume_embeddings = volume_embeddings 1362 self._kwargs = kwargs 1363 1364 feats = volume_embeddings["features"] 1365 self.shape = tuple(int(s) for s in feats.attrs["shape"]) 1366 self.tile_shape = tuple(int(s) for s in feats.attrs["tile_shape"]) 1367 self.halo = tuple(int(s) for s in feats.attrs["halo"]) 1368 self.tiling = Blocking([0, 0], list(self.shape[1:]), list(self.tile_shape)) 1369 1370 # State per (tile, worker), built lazily for the tiles that actually receive prompts. Keyed by 1371 # the worker as well, so 'map_tile_jobs' can put a tile's passes on several devices at once. 1372 self._segmenters = {} 1373 # Device assigned to each active tile, see '_worker_id'. 1374 self._tile_workers = {} 1375 # The worker a thread is running as, which overrides the per-tile assignment while it is set. 1376 self._active_worker = threading.local() 1377 # Signature of the prompt set of the previous round, see 'sync_prompt_state'. 1378 self._prompt_signatures = set()
1384 def sync_prompt_state(self, signatures): 1385 """Discard the per-tile states when prompts were removed or changed since the last round. 1386 1387 See `PromptableSegmentation3D.sync_prompt_state`. The prompt set is compared once for the 1388 whole volume, because a moved prompt can change which tile it belongs to. 1389 1390 Args: 1391 signatures: Hashable descriptors of every prompt currently in the annotation layers. 1392 """ 1393 signatures = set(signatures) 1394 if not self._prompt_signatures.issubset(signatures): 1395 self.reset_predictor() 1396 self._prompt_signatures = signatures
Discard the per-tile states when prompts were removed or changed since the last round.
See PromptableSegmentation3D.sync_prompt_state. The prompt set is compared once for the
whole volume, because a moved prompt can change which tile it belongs to.
Arguments:
- signatures: Hashable descriptors of every prompt currently in the annotation layers.
1398 def reset_predictor(self): 1399 # Each holds an inference state and an embedding cache; they are rebuilt lazily. 1400 for segmenter in self._segmenters.values(): 1401 segmenter.reset_predictor() 1402 self._segmenters = {} 1403 self._tile_workers = {} 1404 self._prompt_signatures = set() 1405 _free_device_memory()
1407 def get_progress_total(self, z_range=None): 1408 """Return tile-slice propagation steps for the currently active tiles.""" 1409 return sum(segmenter.get_progress_total(z_range) for segmenter in self._segmenters.values())
Return tile-slice propagation steps for the currently active tiles.
1483 def map_tiles( 1484 self, tile_ids: List[int], function: Callable, update_progress: Optional[Callable[[int], None]] = None, 1485 ) -> List[Tuple]: 1486 """Run one job per tile, one worker per device, each pulling the next tile once it is free. 1487 1488 A tile that already holds a state keeps the device that state lives on. An unassigned tile is 1489 bound to whichever worker picks it up, so tiles with very different costs (as in automatic 1490 prompt generation, where a tile costs what its candidates cost) balance over the devices 1491 instead of being dealt out round-robin before their cost is known. 1492 """ 1493 tile_ids = list(tile_ids) 1494 if not tile_ids: 1495 return [] 1496 1497 preassigned = {} 1498 unassigned = queue.Queue() 1499 for tile_id in tile_ids: 1500 if tile_id in self._tile_workers: 1501 preassigned.setdefault(self._tile_workers[tile_id], []).append(tile_id) 1502 else: 1503 unassigned.put(tile_id) 1504 1505 def run_worker(worker_id, worker_update=None): 1506 def call(tile_id): 1507 return function(tile_id) if worker_update is None else function(tile_id, worker_update) 1508 1509 results = [] 1510 with self._as_worker(worker_id): 1511 for tile_id in preassigned.get(worker_id, []): 1512 results.append((tile_id, call(tile_id))) 1513 while True: 1514 try: 1515 tile_id = unassigned.get_nowait() 1516 except queue.Empty: 1517 break 1518 self._tile_workers[tile_id] = worker_id 1519 results.append((tile_id, call(tile_id))) 1520 return results 1521 1522 if len(self._predictor_devices) < 2: 1523 return sorted(run_worker(0, update_progress), key=lambda result: result[0]) 1524 1525 progress_queue = queue.Queue() 1526 1527 def forward_progress(): 1528 increment = 0 1529 while True: 1530 try: 1531 increment += int(progress_queue.get_nowait()) 1532 except queue.Empty: 1533 break 1534 if increment: 1535 update_progress(increment) 1536 1537 results = [] 1538 n_workers = len(self._predictor_devices) 1539 with futures.ThreadPoolExecutor(max_workers=n_workers) as pool: 1540 worker_update = progress_queue.put if update_progress is not None else None 1541 tasks = [pool.submit(run_worker, worker_id, worker_update) for worker_id in range(n_workers)] 1542 pending = set(tasks) 1543 while pending: 1544 done, pending = futures.wait(pending, timeout=0.05, return_when=futures.FIRST_COMPLETED) 1545 forward_progress() 1546 for task in done: 1547 results.extend(task.result()) 1548 forward_progress() 1549 return sorted(results, key=lambda result: result[0])
Run one job per tile, one worker per device, each pulling the next tile once it is free.
A tile that already holds a state keeps the device that state lives on. An unassigned tile is bound to whichever worker picks it up, so tiles with very different costs (as in automatic prompt generation, where a tile costs what its candidates cost) balance over the devices instead of being dealt out round-robin before their cost is known.
1551 @property 1552 def predictor_devices(self): 1553 """The (predictor, device) replica per inference device, for a caller that needs its own.""" 1554 return self._predictor_devices
The (predictor, device) replica per inference device, for a caller that needs its own.
1556 @property 1557 def active_tiles(self) -> List[int]: 1558 """The tiles that currently hold a state, in ascending order.""" 1559 return sorted({tile_id for tile_id, _ in self._segmenters})
The tiles that currently hold a state, in ascending order.
1561 def map_tile_jobs(self, jobs: List, function: Callable, update_progress=None) -> List: 1562 """Run jobs that each name a tile, one worker per device, each on its own state for that tile. 1563 1564 Unlike `map_tiles`, several jobs of one tile can run at once: a job prompts the state of its 1565 tile *on its worker's device*, so a single tile whose work dwarfs the others spreads over the 1566 devices instead of pinning them to one. The extra states are what it costs, and a job that 1567 moves to a new device re-reads that tile's features, so give a job enough work to pay for it. 1568 1569 `function` is called as `function(job)`, and `update_progress` from the worker rather than 1570 from the caller's thread - unlike `map_tiles`, whose callback the GUI drives. 1571 """ 1572 devices = [device for _, device in self._predictor_devices] 1573 1574 def run(worker_id, job): 1575 with self._as_worker(worker_id): 1576 return function(job) 1577 1578 return map_jobs_over_devices(devices, jobs, run, update_progress=update_progress)
Run jobs that each name a tile, one worker per device, each on its own state for that tile.
Unlike map_tiles, several jobs of one tile can run at once: a job prompts the state of its
tile on its worker's device, so a single tile whose work dwarfs the others spreads over the
devices instead of pinning them to one. The extra states are what it costs, and a job that
moves to a new device re-reads that tile's features, so give a job enough work to pay for it.
function is called as function(job), and update_progress from the worker rather than
from the caller's thread - unlike map_tiles, whose callback the GUI drives.
1580 def reset_tile_tracking(self, tile_id: int) -> None: 1581 """Reset one tile's tracked objects, keeping its cached encoding. A no-op before its first use.""" 1582 segmenter = self._segmenters.get((tile_id, self._worker_id(tile_id))) 1583 if segmenter is not None: 1584 segmenter.reset_tracking()
Reset one tile's tracked objects, keeping its cached encoding. A no-op before its first use.
1586 def propagate_tile(self, tile_id: int, update_progress=None, early_stop_patience=None, z_range=None): 1587 """Propagate one tile's prompts, returning its own segments and its outer (halo-included) block. 1588 1589 Never merges across tiles, unlike `predict`, which stitches by object identity: it is for a 1590 caller whose object ids are tile-local, e.g. automatic prompt generation, where a candidate 1591 belongs to exactly one tile and its id would otherwise collide with another tile's. 1592 """ 1593 video_segments = self._get_segmenter(tile_id).propagate_prompts( 1594 update_progress=update_progress, early_stop_patience=early_stop_patience, z_range=z_range, 1595 ) 1596 outer = self.tiling.get_block_with_halo(tile_id, list(self.halo)).outer_block 1597 bounding_box = tuple(slice(int(b), int(e)) for b, e in zip(outer.begin, outer.end)) 1598 return video_segments, bounding_box
Propagate one tile's prompts, returning its own segments and its outer (halo-included) block.
Never merges across tiles, unlike predict, which stitches by object identity: it is for a
caller whose object ids are tile-local, e.g. automatic prompt generation, where a candidate
belongs to exactly one tile and its id would otherwise collide with another tile's.
1600 def release_tile(self, tile_id: int) -> None: 1601 """Free one tile's video-predictor state, leaving the other tiles' states alive. 1602 1603 Keeps the CUDA cache rather than emptying it: the next state on this device is the same size, 1604 so the allocator reuses the blocks, and a collection from every worker after every job costs 1605 more than it frees - it holds the interpreter lock while the other devices wait for work. 1606 """ 1607 segmenter = self._segmenters.pop((tile_id, self._worker_id(tile_id)), None) 1608 self._tile_workers.pop(tile_id, None) 1609 if segmenter is not None: 1610 segmenter.release()
Free one tile's video-predictor state, leaving the other tiles' states alive.
Keeps the CUDA cache rather than emptying it: the next state on this device is the same size, so the allocator reuses the blocks, and a collection from every worker after every job costs more than it frees - it holds the interpreter lock while the other devices wait for work.
1612 def segment_slice(self, frame_idx, points=None, labels=None, boxes=None, masks=None, object_id=1): 1613 """Segment a single slice. Points are (x, y), boxes (x0, y0, x1, y1), as passed by the annotator. 1614 1615 Groups the prompts by the tile they fall in, segments every tile with a positive cue, and 1616 unions the per-tile masks - so an object spanning tiles is segmented on both sides. 1617 """ 1618 have_points = points is not None and len(points) > 0 1619 have_boxes = boxes is not None and len(boxes) > 0 1620 have_masks = masks is not None and any(m is not None for m in masks) 1621 if not have_points and not have_boxes and not have_masks: 1622 return None 1623 1624 tile_points, tile_labels, tile_boxes, tile_masks = {}, {}, {}, {} 1625 if have_points: 1626 for point, label in zip(np.asarray(points), np.asarray(labels)): 1627 tid = self._tile_index(int(round(point[1])), int(round(point[0]))) # (y, x) from (x, y) 1628 tile_points.setdefault(tid, []).append(point) 1629 tile_labels.setdefault(tid, []).append(label) 1630 if have_boxes: 1631 for bidx, box in enumerate(boxes): 1632 box = np.asarray(box) # (x0, y0, x1, y1) 1633 box_yx = np.array([box[1], box[0], box[3], box[2]]) 1634 box_mask = masks[bidx] if masks is not None else None 1635 for tid, clipped in _box_to_tiles(self.tiling, self.halo, box_yx).items(): 1636 tile_boxes.setdefault(tid, []).append(np.array([clipped[1], clipped[0], clipped[3], clipped[2]])) 1637 tile_masks.setdefault(tid, []).append( 1638 None if box_mask is None else _crop_mask_to_tile(self.tiling, self.halo, tid, box_mask) 1639 ) 1640 1641 tile_jobs = {} 1642 for tile_id in sorted(set(tile_points) | set(tile_boxes)): 1643 tpoints = np.asarray(tile_points.get(tile_id, [])).reshape(-1, 2) 1644 tlabels = np.asarray(tile_labels.get(tile_id, []), dtype=int) 1645 tboxes = tile_boxes.get(tile_id, []) 1646 if not ((tlabels == 1).any() or len(tboxes) > 0): 1647 continue 1648 y0, x0 = self._outer_offset(tile_id) 1649 local_points = (tpoints - np.array([x0, y0])) if len(tpoints) else None 1650 local_boxes = [b - np.array([x0, y0, x0, y0]) for b in tboxes] if tboxes else None 1651 local_masks = tile_masks.get(tile_id) if tboxes else None 1652 tile_jobs[tile_id] = ( 1653 local_points, 1654 tlabels if len(tlabels) else None, 1655 local_boxes, 1656 local_masks, 1657 ) 1658 1659 def segment_tile(tile_id): 1660 local_points, local_labels, local_boxes, local_masks = tile_jobs[tile_id] 1661 return self._get_segmenter(tile_id).segment_slice( 1662 frame_idx, points=local_points, labels=local_labels, 1663 boxes=local_boxes, masks=local_masks, object_id=object_id, 1664 ) 1665 1666 out = np.zeros(self.shape[1:], dtype="uint32") 1667 found = False 1668 for tile_id, tile_seg in self.map_tiles(sorted(tile_jobs), segment_tile): 1669 if tile_seg is None: 1670 continue 1671 local, glob = self._inner_slices(tile_id) 1672 region = tile_seg[local] 1673 sub = out[glob] 1674 positive = region > 0 1675 sub[positive] = region[positive] 1676 found = True 1677 1678 return out if found else None
Segment a single slice. Points are (x, y), boxes (x0, y0, x1, y1), as passed by the annotator.
Groups the prompts by the tile they fall in, segments every tile with a positive cue, and unions the per-tile masks - so an object spanning tiles is segmented on both sides.
1680 def add_point_prompts(self, frame_ids, points, point_labels, object_id=None, multiple_objects=False): 1681 """Add point prompts. Points are in (y, x) order. Each is routed to the tile it falls in, so 1682 an object with prompts in several tiles is added to each of those tiles.""" 1683 if points is None or len(points) == 0: 1684 return 1685 if object_id is None: 1686 object_id = 1 1687 1688 tile_points, tile_labels = {}, {} 1689 for point, label in zip(np.asarray(points), np.asarray(point_labels)): 1690 tid = self._tile_index(int(round(point[0])), int(round(point[1]))) 1691 tile_points.setdefault(tid, []).append(point) 1692 tile_labels.setdefault(tid, []).append(label) 1693 1694 for tile_id, tpoints in tile_points.items(): 1695 y0, x0 = self._outer_offset(tile_id) 1696 local_points = np.asarray(tpoints) - np.array([y0, x0]) 1697 self._get_segmenter(tile_id).add_point_prompts( 1698 frame_ids=frame_ids, points=local_points, point_labels=np.asarray(tile_labels[tile_id]), 1699 object_id=object_id, multiple_objects=multiple_objects, 1700 )
Add point prompts. Points are in (y, x) order. Each is routed to the tile it falls in, so an object with prompts in several tiles is added to each of those tiles.
1702 def add_box_prompts(self, frame_ids, boxes=None, object_id=None): 1703 """Add box prompts (y0, x0, y1, x1). A box spanning several tiles is added, clipped, to each.""" 1704 if boxes is None or len(boxes) == 0: 1705 return 1706 # One object id per box. Default to a single object (id 1) when not batched. 1707 if object_id is None: 1708 object_id = [1] * len(boxes) 1709 elif not isinstance(object_id, list): 1710 object_id = [object_id] * len(boxes) 1711 # Group the (clipped) boxes and their object ids by the tile each falls in. 1712 tile_boxes, tile_ids = {}, {} 1713 for box, obj_id in zip(boxes, object_id): 1714 for tid, clipped in _box_to_tiles(self.tiling, self.halo, np.asarray(box)).items(): 1715 tile_boxes.setdefault(tid, []).append(clipped) 1716 tile_ids.setdefault(tid, []).append(obj_id) 1717 for tile_id, tboxes in tile_boxes.items(): 1718 y0, x0 = self._outer_offset(tile_id) 1719 local_boxes = [b - np.array([y0, x0, y0, x0]) for b in tboxes] 1720 self._get_segmenter(tile_id).add_box_prompts( 1721 frame_ids=frame_ids, boxes=np.array(local_boxes), object_id=tile_ids[tile_id], 1722 )
Add box prompts (y0, x0, y1, x1). A box spanning several tiles is added, clipped, to each.
1724 def add_mask_prompts(self, frame_ids, masks=None, object_id=None, refine=True): 1725 """Add mask prompts. Each mask is routed to the tiles its filled region overlaps, cropped to 1726 each tile's outer block, and added there (so a mask spanning tiles is added on both sides).""" 1727 if masks is None or len(masks) == 0: 1728 return 1729 masks = [np.asarray(m) for m in masks] 1730 # One object id per mask. Default to a single object (id 1) when not batched. 1731 if object_id is None: 1732 object_id = [1] * len(masks) 1733 elif not isinstance(object_id, list): 1734 object_id = [object_id] * len(masks) 1735 1736 for mask, obj_id in zip(masks, object_id): 1737 ys, xs = np.nonzero(mask) 1738 if len(ys) == 0: 1739 continue 1740 box_yx = np.array([ys.min(), xs.min(), ys.max() + 1, xs.max() + 1]) 1741 for tid in _box_to_tiles(self.tiling, self.halo, box_yx): 1742 self._get_segmenter(tid).add_mask_prompts( 1743 frame_ids=frame_ids, masks=[_crop_mask_to_tile(self.tiling, self.halo, tid, mask)], 1744 object_id=obj_id, refine=refine, 1745 )
Add mask prompts. Each mask is routed to the tiles its filled region overlaps, cropped to each tile's outer block, and added there (so a mask spanning tiles is added on both sides).
1747 def predict(self, update_progress=None, early_stop_patience=None, z_range=None, mask_threshold=0.0): 1748 """Propagate the prompts in every active tile and stitch the results into the full volume. 1749 1750 Object ids are preserved across tiles (the inner blocks are disjoint), so an object that was 1751 prompted in several tiles keeps one id and is merged across the tile boundaries. 1752 'mask_threshold' is the logit threshold that binarizes the masks. 1753 """ 1754 segmentation = np.zeros(self.shape, dtype="uint64") 1755 1756 def predict_tile(tile_id, tile_update=None): 1757 return self._get_segmenter(tile_id).predict( 1758 update_progress=tile_update, early_stop_patience=early_stop_patience, z_range=z_range, 1759 mask_threshold=mask_threshold, 1760 ) 1761 1762 for tile_id, tile_seg in self.map_tiles( 1763 self.active_tiles, predict_tile, update_progress=update_progress, 1764 ): 1765 local, glob = self._inner_slices(tile_id) 1766 inner = tile_seg[(slice(None),) + local] 1767 region = segmentation[(slice(None),) + glob] 1768 positive = inner != 0 1769 region[positive] = inner[positive] 1770 return segmentation
Propagate the prompts in every active tile and stitch the results into the full volume.
Object ids are preserved across tiles (the inner blocks are disjoint), so an object that was prompted in several tiles keeps one id and is merged across the tile boundaries. 'mask_threshold' is the logit threshold that binarizes the masks.