micro_sam.precompute_state
Precompute and cache image embeddings for image data (SAM1, SAM2 or VFM encoders).
1"""Precompute and cache image embeddings for image data (SAM1, SAM2 or VFM encoders). 2""" 3 4import os 5import pickle 6import inspect 7from glob import glob 8from pathlib import Path 9from typing import Optional, Sequence, Tuple, Union 10 11import h5py 12import numpy as np 13from segment_anything.predictor import SamPredictor 14 15import torch 16 17from . import util 18from .util import AutoSegBase 19 20 21def cache_amg_state( 22 predictor: SamPredictor, 23 raw: np.ndarray, 24 image_embeddings: util.ImageEmbeddings, 25 save_path: Union[str, os.PathLike], 26 verbose: bool = True, 27 i: Optional[int] = None, 28 **kwargs, 29) -> AutoSegBase: 30 """Compute and cache or load the state for the automatic mask generator. 31 32 Args: 33 predictor: The Segment Anything predictor. 34 raw: The image data. 35 image_embeddings: The image embeddings. 36 save_path: The embedding save path. The AMG state will be stored in 'save_path/amg_state.pickle'. 37 verbose: Whether to run the computation verbose. By default, set to 'True'. 38 i: The index for which to cache the state. 39 kwargs: The keyword arguments for the amg class. 40 41 Returns: 42 The automatic mask generator class with the cached state. 43 """ 44 # Imported here rather than at module scope: SAM1 instance segmentation pulls in the torch_em 45 # training stack, which a SAM2 precompute run does not need and which dominates its start-up. 46 from .v1 import instance_segmentation 47 48 is_tiled = image_embeddings["input_size"] is None 49 amg = instance_segmentation.get_instance_segmentation_generator(predictor, is_tiled=is_tiled, **kwargs) 50 51 # If i is given we compute the state for a given slice/frame. 52 # And we have to save the state for slices/frames separately. 53 if i is None: 54 save_path_amg = os.path.join(save_path, "amg_state.pickle") 55 else: 56 os.makedirs(os.path.join(save_path, "amg_state"), exist_ok=True) 57 save_path_amg = os.path.join(save_path, "amg_state", f"state-{i}.pkl") 58 59 if os.path.exists(save_path_amg): 60 if verbose: 61 print("Load the AMG state from", save_path_amg) 62 with open(save_path_amg, "rb") as f: 63 amg_state = pickle.load(f) 64 amg.set_state(amg_state) 65 return amg 66 67 if verbose: 68 print("Precomputing the state for instance segmentation.") 69 70 amg.initialize(raw if i is None else raw[i], image_embeddings=image_embeddings, verbose=verbose, i=i) 71 amg_state = amg.get_state() 72 73 # put all state onto the cpu so that the state can be deserialized without a gpu 74 new_crop_list = [] 75 for mask_data in amg_state["crop_list"]: 76 for k, v in mask_data.items(): 77 if torch.is_tensor(v): 78 mask_data[k] = v.cpu() 79 new_crop_list.append(mask_data) 80 amg_state["crop_list"] = new_crop_list 81 82 with open(save_path_amg, "wb") as f: 83 pickle.dump(amg_state, f) 84 85 return amg 86 87 88def cache_is_state( 89 predictor: SamPredictor, 90 decoder: torch.nn.Module, 91 raw: np.ndarray, 92 image_embeddings: util.ImageEmbeddings, 93 save_path: Union[str, os.PathLike], 94 verbose: bool = True, 95 i: Optional[int] = None, 96 skip_load: bool = False, 97 **kwargs, 98) -> Optional[AutoSegBase]: 99 """Compute and cache or load the state for the decoder-based instance segmentation. 100 101 Args: 102 predictor: The Segment Anything predictor. 103 decoder: The instance segmentation decoder. 104 raw: The image data. 105 image_embeddings: The image embeddings. 106 save_path: The embedding save path. The state will be stored in 'save_path/is_state.h5'. 107 verbose: Whether to run the computation verbose. By default, set to 'True'. 108 i: The index for which to cache the state. 109 skip_load: Skip loading the state if it is precomputed. By default, set to 'False'. 110 kwargs: The keyword arguments for the instance segmentation class. 111 112 Returns: 113 The instance segmentation class with the cached state. 114 """ 115 from .v1 import instance_segmentation 116 117 is_tiled = image_embeddings["input_size"] is None 118 amg = instance_segmentation.get_instance_segmentation_generator( 119 predictor, is_tiled=is_tiled, decoder=decoder, **kwargs 120 ) 121 122 # If i is given we compute the state for a given slice/frame. 123 # And we have to save the state for slices/frames separately. 124 save_path = os.path.join(save_path, "is_state.h5") 125 save_key = "state" if i is None else f"state-{i}" 126 127 with h5py.File(save_path, "a") as f: 128 if save_key in f: 129 if skip_load: # Skip loading to speed this up for cases where we don't need the return val. 130 return 131 132 if verbose: 133 print("Load instance segmentation state from", save_path, ":", save_key) 134 g = f[save_key] 135 state = { 136 "foreground": g["foreground"][:], 137 "boundary_distances": g["boundary_distances"][:], 138 "center_distances": g["center_distances"][:], 139 } 140 amg.set_state(state) 141 return amg 142 143 if verbose: 144 print("Precomputing the state for instance segmentation.") 145 146 amg.initialize(raw, image_embeddings=image_embeddings, verbose=verbose, i=i) 147 state = amg.get_state() 148 149 with h5py.File(save_path, "a") as f: 150 g = f.create_group(save_key) 151 g.create_dataset("foreground", data=state["foreground"], compression="gzip") 152 g.create_dataset("boundary_distances", data=state["boundary_distances"], compression="gzip") 153 g.create_dataset("center_distances", data=state["center_distances"], compression="gzip") 154 155 return amg 156 157 158AUTOSEG_STATE_GROUP = "autoseg_state" 159AUTOSEG_STATE_ATTRIBUTE = "autoseg_state" 160AUTOSEG_STATE_VERSION = 1 161 162 163def _autoseg_state_key(i): 164 """Return the Zarr key for a whole-image/volume state or a per-slice state.""" 165 return "state" if i is None else f"state-{i}" 166 167 168def _get_autoseg_state_group(embeddings, mode, create=False): 169 """Return the mode-specific state group from an open embedding Zarr.""" 170 if mode not in ("amg", "ais"): 171 raise ValueError(f"Invalid automatic segmentation mode: {mode}") 172 173 if create: 174 root = embeddings.require_group(AUTOSEG_STATE_GROUP) 175 group = root.require_group(mode) 176 group.attrs["version"] = AUTOSEG_STATE_VERSION 177 return group 178 179 if AUTOSEG_STATE_GROUP not in embeddings: 180 return None 181 root = embeddings[AUTOSEG_STATE_GROUP] 182 return root.get(mode, None) 183 184 185def _record_autoseg_state(embeddings, mode, group): 186 """Record which automatic-segmentation states are present in the embedding metadata.""" 187 modes = embeddings.attrs.get(AUTOSEG_STATE_ATTRIBUTE, []) 188 if isinstance(modes, str): 189 modes = [modes] 190 modes = sorted(set(modes) | {mode}) 191 embeddings.attrs[AUTOSEG_STATE_ATTRIBUTE] = modes 192 group.attrs["state_count"] = len(group) 193 194 195# Embedding metadata that defines the identity of the embeddings the state was computed from. If any 196# of these change (image, tiling, model, normalization) the cached state is stale and must not be 197# reused. 'micro_sam_version' is deliberately excluded (a version bump alone does not invalidate it). 198EMBEDDING_SIGNATURE_KEYS = ("data_signature", "tile_shape", "halo", "normalization", "model_name", "model_hash") 199 200 201def _embedding_signature(save_path): 202 """A stable signature of the embeddings at `save_path`, or None if it cannot be read. 203 204 Stamped into the cached automatic-segmentation state so it is not reused against embeddings that 205 were recomputed with different settings (e.g. tiling toggled) but the same image data. 206 """ 207 if save_path is None: 208 return None 209 try: 210 attrs = dict(util._open_embeddings(save_path, mode="r").attrs) 211 except Exception: 212 return None 213 return "|".join(f"{key}={attrs.get(key)}" for key in EMBEDDING_SIGNATURE_KEYS) 214 215 216def _signature_matches(cached, requested): 217 """Whether a cached signature is compatible: equal, or unknown on either side (lenient).""" 218 return cached is None or requested is None or cached == requested 219 220 221def _save_amg_state_v2(segmenter, save_path, key, embedding_signature=None): 222 """Serialize an AMG state as a byte array inside the embedding Zarr.""" 223 state = segmenter.get_state() 224 payload = np.frombuffer(pickle.dumps(state, protocol=pickle.HIGHEST_PROTOCOL), dtype="uint8") 225 226 embeddings = util._open_embeddings(save_path, mode="a") 227 group = _get_autoseg_state_group(embeddings, "amg", create=True) 228 if key in group: 229 del group[key] 230 chunks = (min(len(payload), 1024 ** 2),) 231 dataset = util._create_dataset_with_data(group, key, data=payload, chunks=chunks) 232 if embedding_signature is not None: 233 dataset.attrs["embedding_signature"] = embedding_signature 234 _record_autoseg_state(embeddings, "amg", group) 235 236 237def _load_amg_state_v2(save_path, key): 238 """Load one AMG state from the embedding Zarr, without touching other slice states.""" 239 embeddings = util._open_embeddings(save_path, mode="r") 240 group = _get_autoseg_state_group(embeddings, "amg") 241 if group is None or key not in group: 242 return None 243 dataset = group[key] 244 state = pickle.loads(np.asarray(dataset[:], dtype="uint8").tobytes()) 245 state["embedding_signature"] = dataset.attrs.get("embedding_signature", None) 246 return state 247 248 249def write_ais_state_v2(state, save_path, key, model_type, embedding_signature=None): 250 """Store a decoder state as an array inside the embedding Zarr.""" 251 prediction = state["prediction"] 252 embeddings = util._open_embeddings(save_path, mode="a") 253 group = _get_autoseg_state_group(embeddings, "ais", create=True) 254 if key in group: 255 del group[key] 256 state_group = group.create_group(key) 257 258 # Keep channel and z chunks independent so writing and later reading volumetric predictions 259 # does not require materializing one very large compressed chunk. 260 chunks = list(prediction.shape) 261 chunks[0] = 1 262 if prediction.ndim == 4: 263 chunks[1] = 1 264 chunks[-2] = min(chunks[-2], 512) 265 chunks[-1] = min(chunks[-1], 512) 266 util._create_dataset_with_data(state_group, "prediction", data=prediction, chunks=tuple(chunks)) 267 268 # Record which model produced the prediction so it is not reused with a different decoder. 269 if model_type is not None: 270 state_group.attrs["model_type"] = model_type 271 if embedding_signature is not None: 272 state_group.attrs["embedding_signature"] = embedding_signature 273 _record_autoseg_state(embeddings, "ais", group) 274 275 276def _save_ais_state_v2(segmenter, save_path, key, model_type, embedding_signature=None): 277 """Store a segmenter's decoder prediction inside the embedding Zarr.""" 278 write_ais_state_v2(segmenter.get_state(), save_path, key, model_type, embedding_signature) 279 280 281def save_ais_state(state, save_path, state_index=None, model_type=None): 282 """Persist an existing decoder state without running the decoder again.""" 283 key = _autoseg_state_key(state_index) 284 signature = _embedding_signature(save_path) 285 write_ais_state_v2(state, save_path, key, model_type, embedding_signature=signature) 286 287 288def _load_ais_state_v2(save_path, key): 289 """Load one AIS prediction from the embedding Zarr on demand.""" 290 embeddings = util._open_embeddings(save_path, mode="r") 291 group = _get_autoseg_state_group(embeddings, "ais") 292 if group is None or key not in group: 293 return None 294 state_group = group[key] 295 return { 296 "prediction": state_group["prediction"][:], 297 "model_type": state_group.attrs.get("model_type", None), 298 "embedding_signature": state_group.attrs.get("embedding_signature", None), 299 } 300 301 302def _has_autoseg_state(save_path, mode, state_count=1): 303 """Check cache completeness from Zarr metadata without loading state arrays or bitstreams.""" 304 if save_path is None or not os.path.exists(save_path): 305 return False 306 # Any failure to read the metadata (unreadable / partial zarr, backend error) means we cannot 307 # confirm a usable cache, so we treat it as absent rather than propagate into the GUI gating. 308 try: 309 embeddings = util._open_embeddings(save_path, mode="r") 310 group = _get_autoseg_state_group(embeddings, mode) 311 if group is None: 312 return False 313 return int(group.attrs.get("state_count", len(group))) >= state_count 314 except Exception: 315 return False 316 317 318def _ais_state_matches(state, model_type): 319 """Whether the tool can reuse a cached AIS state for `model_type`. 320 321 The AIS prediction depends only on the decoder and the embeddings, so the only staleness risk is 322 reusing it with a different decoder. We reuse the cached state unless both the stored and the 323 requested `model_type` are known and differ (a state written without a signature is reused). 324 """ 325 cached = state.get("model_type") 326 return cached is None or model_type is None or cached == model_type 327 328 329def cache_autoseg_state(mode, model_or_decoder, raw, image_embeddings, save_path, **kwargs): 330 """Compute, cache or load the SAM2 automatic-segmentation state for one image / slice / volume. 331 332 A single entry point over the two modes; both reuse a matching cached state instead of recomputing. 333 - 'amg': grid-based mask generation. `model_or_decoder` is the SAM2 model; extra kwargs are the 334 AMG parameters (see `_cache_amg_state_v2`). 335 - 'ais': UniSAM2 decoder prediction. `model_or_decoder` is the decoder; `ndim` is required 336 (see `_cache_ais_state_v2`). 337 338 Args: 339 mode: The automatic-segmentation mode, 'amg' or 'ais'. 340 model_or_decoder: The SAM2 model (AMG) or the UniSAM2 decoder (AIS). 341 raw: The image data. 342 image_embeddings: The (optionally precomputed) image embeddings. 343 save_path: The embedding save path used to store the state, or None to skip caching. 344 kwargs: Mode-specific keyword arguments forwarded to the underlying cache function. 345 346 Returns: 347 The segmenter with the (cached or freshly computed) state set. 348 """ 349 if mode == "amg": 350 return _cache_amg_state_v2(model_or_decoder, raw, image_embeddings, save_path, **kwargs) 351 if mode == "ais": 352 return _cache_ais_state_v2(model_or_decoder, raw, image_embeddings, save_path, **kwargs) 353 raise ValueError(f"Invalid automatic-segmentation state mode: {mode!r} (expected 'amg' or 'ais').") 354 355 356def _save_autoseg_state(mode, segmenter, save_path, key, **kwargs): 357 """Save an autoseg state into the embedding Zarr: 'amg' as pickled masks, 'ais' as a decoder array.""" 358 if mode == "amg": 359 return _save_amg_state_v2(segmenter, save_path, key, **kwargs) 360 if mode == "ais": 361 return _save_ais_state_v2(segmenter, save_path, key, **kwargs) 362 raise ValueError(f"Invalid automatic-segmentation state mode: {mode!r} (expected 'amg' or 'ais').") 363 364 365def _load_autoseg_state(mode, save_path, key): 366 """Load one autoseg state (AMG masks or AIS prediction) from the embedding Zarr, or None if absent.""" 367 if mode == "amg": 368 return _load_amg_state_v2(save_path, key) 369 if mode == "ais": 370 return _load_ais_state_v2(save_path, key) 371 raise ValueError(f"Invalid automatic-segmentation state mode: {mode!r} (expected 'amg' or 'ais').") 372 373 374def _cache_amg_state_v2( 375 model: torch.nn.Module, 376 raw: np.ndarray, 377 image_embeddings: Optional[dict], 378 save_path: Optional[Union[str, os.PathLike]], 379 model_type: Optional[str] = None, 380 i: Optional[int] = None, 381 state_index: Optional[int] = None, 382 is_tiled: Optional[bool] = None, 383 tile_shape: Optional[Tuple[int, int]] = None, 384 halo: Optional[Tuple[int, int]] = None, 385 points_per_side: int = 32, 386 pred_iou_thresh: float = 0.8, 387 stability_score_thresh: float = 0.9, 388 verbose: bool = True, 389 pbar_init: Optional[callable] = None, 390 pbar_update: Optional[callable] = None, 391 **kwargs, 392): 393 """Compute and cache, or load, the SAM2 grid-based (AMG) automatic-segmentation state. 394 395 The SAM2 counterpart of `cache_amg_state`. The state (the predicted masks) is stored in the 396 embedding Zarr under 'autoseg_state/amg'. A cached state is reused only if it was 397 computed with the same AMG parameters; otherwise it is recomputed and overwritten. Pass 398 'save_path=None' to compute in memory without caching. 399 400 Args: 401 model: The SAM2 model, loaded via `micro_sam.v2.util.get_sam2_model`. 402 raw: The image data. 403 image_embeddings: The (optionally precomputed) image embeddings. When None the segmenter 404 computes them from `raw`. 405 save_path: The embedding save path used to store the state, or None to skip caching. 406 model_type: The SAM2 model type, e.g. 'hvit_t'. Recorded in the cached state. 407 i: The slice index passed to the segmenter's `initialize` (for reusing volume embeddings). 408 state_index: The index used for the on-disk state (defaults to `i`). Set this to identify a 409 slice on disk when `i`/`image_embeddings` do not (e.g. a prebuilt single-slice embedding). 410 is_tiled: Whether to use the tiled segmenter. By default inferred from the embeddings. 411 tile_shape: The tile shape for the tiled segmenter. 412 halo: The tile overlap for the tiled segmenter. 413 points_per_side: The number of grid points sampled per image side. 414 pred_iou_thresh: The predicted-IoU filter threshold. 415 stability_score_thresh: The stability-score filter threshold. 416 verbose: Whether to run verbose. 417 pbar_init: Callback to initialize an external progress bar. 418 pbar_update: Callback to update an external progress bar. 419 kwargs: Additional keyword arguments for the AMG segmenter. 420 421 Returns: 422 The AMG segmenter with the (cached or freshly computed) state set. 423 """ 424 from .v2.instance_segmentation import get_amg_segmenter 425 426 if is_tiled is None: 427 is_tiled = image_embeddings is not None and image_embeddings.get("input_size") is None 428 429 segmenter = get_amg_segmenter( 430 model, is_tiled=is_tiled, model_type=model_type, points_per_side=points_per_side, 431 pred_iou_thresh=pred_iou_thresh, stability_score_thresh=stability_score_thresh, **kwargs, 432 ) 433 434 key_index = i if state_index is None else state_index 435 key, signature = None, None 436 if save_path is not None: 437 key = _autoseg_state_key(key_index) 438 signature = _embedding_signature(save_path) 439 state = _load_amg_state_v2(save_path, key) 440 if state is not None: 441 matches = state.get("params") == segmenter._amg_params 442 matches = matches and _signature_matches(state.get("embedding_signature"), signature) 443 if matches: 444 if verbose: 445 print("Load the AMG state from", save_path, ":", key) 446 segmenter.set_state(state) 447 return segmenter 448 449 if verbose: 450 print("Precomputing the state for automatic mask generation.") 451 452 init_kwargs = {"tile_shape": tile_shape, "halo": halo} if is_tiled else {} 453 segmenter.initialize( 454 raw, image_embeddings=image_embeddings, i=i, verbose=verbose, 455 pbar_init=pbar_init, pbar_update=pbar_update, **init_kwargs, 456 ) 457 if key is not None: 458 _save_amg_state_v2(segmenter, save_path, key, embedding_signature=signature) 459 return segmenter 460 461 462def _cache_amg_slice(segmenter, save_path, i, init_fn, embedding_signature=None): 463 """Load slice `i`'s AMG state from `save_path` if present and matching, else init and save. 464 465 Used by `micro_sam.v2.instance_segmentation.amg_3d_segmentation` to cache the per-slice 466 grid-prediction state of a volume. `init_fn(i)` runs the (expensive) `initialize` for the slice. 467 """ 468 key = _autoseg_state_key(i) 469 state = _load_amg_state_v2(save_path, key) 470 if state is not None: 471 matches = state.get("params") == segmenter._amg_params 472 matches = matches and _signature_matches(state.get("embedding_signature"), embedding_signature) 473 if matches: 474 segmenter.set_state(state) 475 return 476 init_fn(i) 477 _save_amg_state_v2(segmenter, save_path, key, embedding_signature=embedding_signature) 478 479 480def _cache_amg_volume_state( 481 model: torch.nn.Module, 482 get_slice: callable, 483 n_slices: int, 484 image_embeddings: Optional[dict], 485 save_path: Union[str, os.PathLike], 486 model_type: Optional[str] = None, 487 is_tiled: Optional[bool] = None, 488 tile_shape: Optional[Tuple[int, int]] = None, 489 halo: Optional[Tuple[int, int]] = None, 490 verbose: bool = True, 491 pbar_init: Optional[callable] = None, 492 pbar_update: Optional[callable] = None, 493 **amg_kwargs, 494): 495 """Cache the per-slice AMG grid-prediction state for a whole volume with one shared segmenter. 496 497 Builds the AMG segmenter and reads the embedding signature once, then caches each slice via 498 `_cache_amg_slice`, reusing the shared 3d embeddings. This avoids rebuilding the segmenter and 499 re-reading the signature on every slice, which a per-slice `cache_autoseg_state` loop would do. 500 501 Args: 502 model: The SAM2 model. 503 get_slice: Callable mapping a slice index to the 2d image for that slice. The image is only 504 used if `image_embeddings` is None; with embeddings the slice is taken from them. 505 n_slices: The number of slices in the volume. 506 image_embeddings: The precomputed 3d (video-style) embeddings for the volume. 507 save_path: The embedding save path used to store the per-slice state. 508 model_type: The SAM2 model type, recorded in the cached state. 509 is_tiled: Whether to use the tiled segmenter. By default inferred from the embeddings. 510 tile_shape: The tile shape for the tiled segmenter. 511 halo: The tile overlap for the tiled segmenter. 512 verbose: Whether to report progress. By default, set to 'True'. 513 pbar_init: Callback to initialize an external progress bar. 514 pbar_update: Callback to update an external progress bar. 515 amg_kwargs: Additional keyword arguments for the AMG segmenter. 516 517 Returns: 518 The AMG segmenter, with the last slice's state set. 519 """ 520 from .v2.instance_segmentation import get_amg_segmenter 521 522 if is_tiled is None: 523 is_tiled = image_embeddings is not None and image_embeddings.get("input_size") is None 524 525 segmenter = get_amg_segmenter(model, is_tiled=is_tiled, model_type=model_type, **amg_kwargs) 526 signature = _embedding_signature(save_path) 527 init_kwargs = {"tile_shape": tile_shape, "halo": halo} if is_tiled else {} 528 529 def init_slice(i): 530 segmenter.initialize(get_slice(i), image_embeddings=image_embeddings, i=i, verbose=False, **init_kwargs) 531 532 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 533 pbar_init(n_slices, "Precompute automatic segmentation state") 534 for i in range(n_slices): 535 _cache_amg_slice(segmenter, save_path, i, init_slice, embedding_signature=signature) 536 pbar_update(1) 537 pbar_close() 538 return segmenter 539 540 541def _cache_ais_state_v2( 542 decoder: torch.nn.Module, 543 raw: np.ndarray, 544 image_embeddings: Optional[dict], 545 save_path: Optional[Union[str, os.PathLike]], 546 ndim: int, 547 model_type: Optional[str] = None, 548 i: Optional[int] = None, 549 state_index: Optional[int] = None, 550 is_tiled: Optional[bool] = None, 551 tile_shape: Optional[Tuple[int, ...]] = None, 552 halo: Optional[Tuple[int, ...]] = None, 553 device: Optional[str] = None, 554 devices: Optional[Union[str, torch.device, Sequence[Union[str, torch.device]]]] = None, 555 verbose: bool = True, 556 pbar_init: Optional[callable] = None, 557 pbar_update: Optional[callable] = None, 558): 559 """Compute and cache, or load, the SAM2 decoder-based (AIS) automatic-segmentation state. 560 561 The SAM2 counterpart of `cache_is_state`, using the UniSAM2 decoder. The state (the foreground 562 and directed-distance predictions) is stored in the embedding Zarr under 563 'autoseg_state/ais', using the key 'state' (whole image / volume) or 'state-{i}' 564 (a slice). It is independent of the post-processing parameters, so it is always reusable. Pass 565 'save_path=None' to skip caching. 566 567 Args: 568 decoder: The UniSAM2 model, loaded via `micro_sam.v2.instance_segmentation.get_unisam2_model`. 569 raw: The image data. 570 image_embeddings: The (optionally precomputed) image embeddings. When given only the decoder 571 is run on them (no encoder pass). 572 save_path: The embedding save path used to store the state, or None to skip caching. 573 ndim: The number of spatial dimensions (2 or 3). 574 model_type: The SAM2 model type. Recorded in the cached state so it is not reused with a 575 different decoder. 576 i: The slice index passed to the segmenter's `initialize`. 577 state_index: The index used for the on-disk state (defaults to `i`). 578 is_tiled: Whether to use the tiled segmenter. By default inferred from the embeddings. 579 tile_shape: The tile shape for the tiled segmenter, (y, x) for an image. For a volume, 580 always the full (z, y, x) - its z entry also sets the z chunk a volume is decoded in 581 (None for the library default), tiled or not. 582 halo: The tile overlap, matching `tile_shape`'s axes. 583 device: The device the decoder lives on. 584 devices: The device or devices to run the decoder inference on. By default all visible CUDA 585 devices are used; pass a single device to pin inference to it. 586 verbose: Whether to run verbose. 587 pbar_init: Callback to initialize an external progress bar. 588 pbar_update: Callback to update an external progress bar. 589 590 Returns: 591 The AIS segmenter with the (cached or freshly computed) state set. 592 """ 593 from .v2.instance_segmentation import get_unisam2_segmentation_generator 594 595 if is_tiled is None: 596 is_tiled = image_embeddings is not None and image_embeddings.get("input_size") is None 597 598 segmenter = get_unisam2_segmentation_generator( 599 decoder, is_tiled=is_tiled, device=device, inference_device=devices 600 ) 601 602 key_index = i if state_index is None else state_index 603 key, signature = None, None 604 if save_path is not None: 605 key = _autoseg_state_key(key_index) 606 signature = _embedding_signature(save_path) 607 state = _load_ais_state_v2(save_path, key) 608 matches = state is not None and _ais_state_matches(state, model_type) 609 matches = matches and _signature_matches(state.get("embedding_signature"), signature) 610 if matches: 611 if verbose: 612 print("Load instance segmentation state from", save_path, ":", key) 613 segmenter.set_state(state) 614 return segmenter 615 616 if verbose: 617 print("Precomputing the state for automatic instance segmentation.") 618 619 segmenter.initialize( 620 raw, ndim, image_embeddings=image_embeddings, i=i, tile_shape=tile_shape, halo=halo, 621 pbar_init=pbar_init, pbar_update=pbar_update, 622 ) 623 if key is not None: 624 _save_ais_state_v2(segmenter, save_path, key, model_type, embedding_signature=signature) 625 return segmenter 626 627 628def _resolve_unisam2_decoder(model_type, checkpoint_path, device): 629 """Return a UniSAM2 decoder for the SAM2 model if one is available, else None (fall back to AMG). 630 631 Uses `micro_sam.v2.instance_segmentation.get_decoder`: a decoder from a custom `checkpoint_path` 632 (a joint checkpoint, or a model file with its '<name>_decoder' file next to it), or the registered 633 decoder of a finetuned model (e.g. 'hvit_t_cells'). Any failure (e.g. an interactive-only 634 checkpoint without a decoder) returns None. 635 """ 636 from .v2.util import FINETUNED_MODELS, has_registered_decoder 637 from .v2.instance_segmentation import get_decoder 638 639 if checkpoint_path is None and not (model_type in FINETUNED_MODELS and has_registered_decoder(model_type)): 640 return None 641 try: 642 return get_decoder(model_type, checkpoint=checkpoint_path, device=util.get_device(device)) 643 except Exception as e: 644 print(f"Could not load a UniSAM2 decoder for '{model_type}': {e}") 645 return None 646 647 648def _cache_autoseg_state_for_file( 649 predictor, decoder, model_type, image_data, embeddings, save_path, ndim, verbose, devices=None, 650): 651 """Cache the SAM2 automatic-segmentation state for one file: AIS if a decoder is given, else AMG.""" 652 if decoder is not None: # AIS segments the whole image / volume in one pass. 653 device = next(decoder.parameters()).device 654 cache_autoseg_state( 655 "ais", decoder, image_data, embeddings, save_path, ndim=ndim, model_type=model_type, 656 device=device, devices=devices, verbose=verbose, 657 ) 658 elif ndim == 2: # AMG on a single 2d image. 659 model = getattr(predictor, "model", predictor) 660 cache_autoseg_state("amg", model, image_data, embeddings, save_path, model_type=model_type, verbose=verbose) 661 else: # AMG on a volume: cache the per-slice grid state, reusing the 3d embeddings and one segmenter. 662 model = getattr(predictor, "model", predictor) 663 _cache_amg_volume_state( 664 model, lambda i: image_data[i], image_data.shape[0], embeddings, save_path, 665 model_type=model_type, verbose=verbose, 666 ) 667 668 669def precompute_state( 670 input_path: Union[os.PathLike, str], 671 output_path: Union[os.PathLike, str], 672 pattern: Optional[str] = None, 673 model_type: str = "hvit_t", 674 checkpoint_path: Optional[Union[os.PathLike, str]] = None, 675 key: Optional[str] = None, 676 ndim: Optional[int] = None, 677 precompute_autoseg_state: bool = False, 678 prefer_decoder: bool = True, 679 batch_size: Optional[int] = None, 680 devices: Optional[Union[str, Sequence[str]]] = None, 681 tile_shape: Optional[Tuple[int, int]] = None, 682 halo: Optional[Tuple[int, int]] = None, 683) -> None: 684 """Precompute and cache the image embeddings (and, optionally, the automatic-segmentation state). 685 686 The embeddings are saved in the same zarr format the annotators use, so the output can be loaded 687 directly by the `micro_sam.annotator` CLI and the napari GUI by passing the same path as the 688 embedding path (with a matching model and image). 689 690 Args: 691 input_path: The input image file(s). Can either be a single image file (e.g. tif or png), 692 a container file (e.g. hdf5 or zarr) or a folder with image files. 693 In case of a container file the argument `key` must be given. In case of a folder 694 the `pattern` argument must be given to subselect files. 695 output_path: The output path where the embeddings will be saved. For a single input this is the path 696 to the embeddings zarr; for a folder of inputs this is the directory the embeddings are saved in. 697 pattern: Glob pattern to select files in a folder. The embeddings will be computed 698 for each of these files. To select all files in a folder pass "*". 699 model_type: The model to use. Supports SAM1 ('vit_*'), SAM2 ('hvit_*') and VFM (DINO / UNI) 700 encoders. By default the `hvit_t` model is used. 701 checkpoint_path: Path to a checkpoint for a custom model. 702 key: The key to the input file. This is needed for container files (e.g. hdf5 or zarr) 703 or to load several images as 3d volume. Provide a glob pattern, e.g. "*.tif", for this case. 704 ndim: The dimensionality of the data. By default, computed from the input data. 705 precompute_autoseg_state: Whether to also precompute the automatic-segmentation state in the 706 embeddings (a longer start-up in exchange for a faster first automatic segmentation). 707 Supported for SAM2 ('hvit_*') models. 708 prefer_decoder: Whether to use the decoder-based state (AIS) when the SAM2 model has a decoder, 709 instead of grid-based mask generation (AMG). 710 batch_size: The number of tiles / slices per model call. By default it is selected per device 711 from the free VRAM (SAM2; SAM1 uses a single tile / slice). Ignored by the families 712 without batching (VFM encoders). 713 devices: The device or devices to compute the embeddings and the decoder-based (AIS) 714 automatic-segmentation state on. By default all visible CUDA devices are used. Only 715 supported for SAM2 ('hvit_*') models. 716 tile_shape: The in-plane tile shape. By default, the function uses the tiling of cached 717 embeddings. Without them, it tiles an image that is larger than the in-plane size cutoff 718 with the default tile shape. The annotation tools and the automatic segmentation use the 719 same tiling, so they can reuse these embeddings. Pass all zeros to compute the embeddings 720 without tiles. 721 halo: The in-plane tile overlap. By default, the overlap of cached embeddings, or the default 722 overlap for tiled embeddings. 723 """ 724 from .v2.util import resolve_default_tiling 725 726 is_sam2 = model_type.startswith("hvit") 727 if precompute_autoseg_state and not is_sam2: 728 raise ValueError( 729 "Precomputing the automatic-segmentation state via 'precompute_state' is only supported for " 730 "SAM2 ('hvit_*') models. For SAM1 use the annotator command with " 731 "'--precompute_autoseg_state'." 732 ) 733 734 # Dispatch to the embedding function for the model family (SAM1 / SAM2 / VFM). All share the same 735 # interface, so the per-family predictor from '_get_sam_model' feeds directly into it. 736 compute_embeddings = util.get_embedding_function(model_type) 737 738 # Only SAM2 supports multi-device inference and only SAM1 / SAM2 support batching, so forward 739 # these settings just to the families whose embedding function accepts them. 740 supported = inspect.signature(compute_embeddings).parameters 741 compute_kwargs = { 742 name: value for name, value in (("batch_size", batch_size), ("devices", devices)) 743 if name in supported 744 } 745 746 # Resolve the UniSAM2 decoder once (AIS); when none is available the state is cached with AMG. 747 decoder = None 748 if precompute_autoseg_state and prefer_decoder: 749 decoder = _resolve_unisam2_decoder(model_type, checkpoint_path, device=None) 750 751 # Determine the input files and matching output embedding paths. 752 single = pattern is None 753 if single: 754 input_files, output_paths = [input_path], [output_path] 755 else: 756 input_files = sorted(glob(os.path.join(input_path, pattern))) 757 if len(input_files) == 0: 758 raise ValueError(f"Could not find any files matching the pattern '{pattern}' in '{input_path}'.") 759 os.makedirs(output_path, exist_ok=True) 760 output_paths = [os.path.join(output_path, os.path.basename(f)) for f in input_files] 761 762 predictor, current_ndim = None, None 763 for input_file, out_path in util._progress_bar( 764 zip(input_files, output_paths), total=len(input_files), desc="Precompute embeddings", disable=single 765 ): 766 image_data = input_file if isinstance(input_file, np.ndarray) else util.load_image_data(input_file, key) 767 file_ndim = image_data.ndim if ndim is None else ndim 768 769 # Build the predictor for the data dimensionality (for SAM2 a 2d image vs. 3d video predictor). 770 # We reuse the annotator's model loader so the embeddings match what the GUI / CLI expect. 771 if predictor is None or file_ndim != current_ndim: 772 predictor, _ = util._get_sam_model( 773 model_type=model_type, ndim=file_ndim, device=None, 774 checkpoint_path=checkpoint_path, decoder_path=None, use_cli=True, 775 ) 776 current_ndim = file_ndim 777 778 save_path = str(Path(out_path).with_suffix(".zarr")) 779 # Use the tiling of the annotation tools, so that they can reuse these embeddings. 780 spatial_shape = image_data.shape[:file_ndim] 781 file_tile_shape, file_halo = resolve_default_tiling(spatial_shape, tile_shape, halo, save_path) 782 if is_sam2 and file_ndim == 3 and file_tile_shape is not None: 783 # The SAM2 embedding API takes all spatial axes; the encoder only tiles in-plane. 784 file_tile_shape, file_halo = (spatial_shape[0], *file_tile_shape), (0, *file_halo) 785 embeddings = compute_embeddings( 786 predictor=predictor, input_=image_data, save_path=save_path, ndim=file_ndim, verbose=single, 787 tile_shape=file_tile_shape, halo=file_halo, **compute_kwargs, 788 ) 789 790 if precompute_autoseg_state: 791 _cache_autoseg_state_for_file( 792 predictor, decoder, model_type, image_data, embeddings, save_path, file_ndim, verbose=single, 793 devices=devices, 794 )
22def cache_amg_state( 23 predictor: SamPredictor, 24 raw: np.ndarray, 25 image_embeddings: util.ImageEmbeddings, 26 save_path: Union[str, os.PathLike], 27 verbose: bool = True, 28 i: Optional[int] = None, 29 **kwargs, 30) -> AutoSegBase: 31 """Compute and cache or load the state for the automatic mask generator. 32 33 Args: 34 predictor: The Segment Anything predictor. 35 raw: The image data. 36 image_embeddings: The image embeddings. 37 save_path: The embedding save path. The AMG state will be stored in 'save_path/amg_state.pickle'. 38 verbose: Whether to run the computation verbose. By default, set to 'True'. 39 i: The index for which to cache the state. 40 kwargs: The keyword arguments for the amg class. 41 42 Returns: 43 The automatic mask generator class with the cached state. 44 """ 45 # Imported here rather than at module scope: SAM1 instance segmentation pulls in the torch_em 46 # training stack, which a SAM2 precompute run does not need and which dominates its start-up. 47 from .v1 import instance_segmentation 48 49 is_tiled = image_embeddings["input_size"] is None 50 amg = instance_segmentation.get_instance_segmentation_generator(predictor, is_tiled=is_tiled, **kwargs) 51 52 # If i is given we compute the state for a given slice/frame. 53 # And we have to save the state for slices/frames separately. 54 if i is None: 55 save_path_amg = os.path.join(save_path, "amg_state.pickle") 56 else: 57 os.makedirs(os.path.join(save_path, "amg_state"), exist_ok=True) 58 save_path_amg = os.path.join(save_path, "amg_state", f"state-{i}.pkl") 59 60 if os.path.exists(save_path_amg): 61 if verbose: 62 print("Load the AMG state from", save_path_amg) 63 with open(save_path_amg, "rb") as f: 64 amg_state = pickle.load(f) 65 amg.set_state(amg_state) 66 return amg 67 68 if verbose: 69 print("Precomputing the state for instance segmentation.") 70 71 amg.initialize(raw if i is None else raw[i], image_embeddings=image_embeddings, verbose=verbose, i=i) 72 amg_state = amg.get_state() 73 74 # put all state onto the cpu so that the state can be deserialized without a gpu 75 new_crop_list = [] 76 for mask_data in amg_state["crop_list"]: 77 for k, v in mask_data.items(): 78 if torch.is_tensor(v): 79 mask_data[k] = v.cpu() 80 new_crop_list.append(mask_data) 81 amg_state["crop_list"] = new_crop_list 82 83 with open(save_path_amg, "wb") as f: 84 pickle.dump(amg_state, f) 85 86 return amg
Compute and cache or load the state for the automatic mask generator.
Arguments:
- predictor: The Segment Anything predictor.
- raw: The image data.
- image_embeddings: The image embeddings.
- save_path: The embedding save path. The AMG state will be stored in 'save_path/amg_state.pickle'.
- verbose: Whether to run the computation verbose. By default, set to 'True'.
- i: The index for which to cache the state.
- kwargs: The keyword arguments for the amg class.
Returns:
The automatic mask generator class with the cached state.
89def cache_is_state( 90 predictor: SamPredictor, 91 decoder: torch.nn.Module, 92 raw: np.ndarray, 93 image_embeddings: util.ImageEmbeddings, 94 save_path: Union[str, os.PathLike], 95 verbose: bool = True, 96 i: Optional[int] = None, 97 skip_load: bool = False, 98 **kwargs, 99) -> Optional[AutoSegBase]: 100 """Compute and cache or load the state for the decoder-based instance segmentation. 101 102 Args: 103 predictor: The Segment Anything predictor. 104 decoder: The instance segmentation decoder. 105 raw: The image data. 106 image_embeddings: The image embeddings. 107 save_path: The embedding save path. The state will be stored in 'save_path/is_state.h5'. 108 verbose: Whether to run the computation verbose. By default, set to 'True'. 109 i: The index for which to cache the state. 110 skip_load: Skip loading the state if it is precomputed. By default, set to 'False'. 111 kwargs: The keyword arguments for the instance segmentation class. 112 113 Returns: 114 The instance segmentation class with the cached state. 115 """ 116 from .v1 import instance_segmentation 117 118 is_tiled = image_embeddings["input_size"] is None 119 amg = instance_segmentation.get_instance_segmentation_generator( 120 predictor, is_tiled=is_tiled, decoder=decoder, **kwargs 121 ) 122 123 # If i is given we compute the state for a given slice/frame. 124 # And we have to save the state for slices/frames separately. 125 save_path = os.path.join(save_path, "is_state.h5") 126 save_key = "state" if i is None else f"state-{i}" 127 128 with h5py.File(save_path, "a") as f: 129 if save_key in f: 130 if skip_load: # Skip loading to speed this up for cases where we don't need the return val. 131 return 132 133 if verbose: 134 print("Load instance segmentation state from", save_path, ":", save_key) 135 g = f[save_key] 136 state = { 137 "foreground": g["foreground"][:], 138 "boundary_distances": g["boundary_distances"][:], 139 "center_distances": g["center_distances"][:], 140 } 141 amg.set_state(state) 142 return amg 143 144 if verbose: 145 print("Precomputing the state for instance segmentation.") 146 147 amg.initialize(raw, image_embeddings=image_embeddings, verbose=verbose, i=i) 148 state = amg.get_state() 149 150 with h5py.File(save_path, "a") as f: 151 g = f.create_group(save_key) 152 g.create_dataset("foreground", data=state["foreground"], compression="gzip") 153 g.create_dataset("boundary_distances", data=state["boundary_distances"], compression="gzip") 154 g.create_dataset("center_distances", data=state["center_distances"], compression="gzip") 155 156 return amg
Compute and cache or load the state for the decoder-based instance segmentation.
Arguments:
- predictor: The Segment Anything predictor.
- decoder: The instance segmentation decoder.
- raw: The image data.
- image_embeddings: The image embeddings.
- save_path: The embedding save path. The state will be stored in 'save_path/is_state.h5'.
- verbose: Whether to run the computation verbose. By default, set to 'True'.
- i: The index for which to cache the state.
- skip_load: Skip loading the state if it is precomputed. By default, set to 'False'.
- kwargs: The keyword arguments for the instance segmentation class.
Returns:
The instance segmentation class with the cached state.
250def write_ais_state_v2(state, save_path, key, model_type, embedding_signature=None): 251 """Store a decoder state as an array inside the embedding Zarr.""" 252 prediction = state["prediction"] 253 embeddings = util._open_embeddings(save_path, mode="a") 254 group = _get_autoseg_state_group(embeddings, "ais", create=True) 255 if key in group: 256 del group[key] 257 state_group = group.create_group(key) 258 259 # Keep channel and z chunks independent so writing and later reading volumetric predictions 260 # does not require materializing one very large compressed chunk. 261 chunks = list(prediction.shape) 262 chunks[0] = 1 263 if prediction.ndim == 4: 264 chunks[1] = 1 265 chunks[-2] = min(chunks[-2], 512) 266 chunks[-1] = min(chunks[-1], 512) 267 util._create_dataset_with_data(state_group, "prediction", data=prediction, chunks=tuple(chunks)) 268 269 # Record which model produced the prediction so it is not reused with a different decoder. 270 if model_type is not None: 271 state_group.attrs["model_type"] = model_type 272 if embedding_signature is not None: 273 state_group.attrs["embedding_signature"] = embedding_signature 274 _record_autoseg_state(embeddings, "ais", group)
Store a decoder state as an array inside the embedding Zarr.
282def save_ais_state(state, save_path, state_index=None, model_type=None): 283 """Persist an existing decoder state without running the decoder again.""" 284 key = _autoseg_state_key(state_index) 285 signature = _embedding_signature(save_path) 286 write_ais_state_v2(state, save_path, key, model_type, embedding_signature=signature)
Persist an existing decoder state without running the decoder again.
330def cache_autoseg_state(mode, model_or_decoder, raw, image_embeddings, save_path, **kwargs): 331 """Compute, cache or load the SAM2 automatic-segmentation state for one image / slice / volume. 332 333 A single entry point over the two modes; both reuse a matching cached state instead of recomputing. 334 - 'amg': grid-based mask generation. `model_or_decoder` is the SAM2 model; extra kwargs are the 335 AMG parameters (see `_cache_amg_state_v2`). 336 - 'ais': UniSAM2 decoder prediction. `model_or_decoder` is the decoder; `ndim` is required 337 (see `_cache_ais_state_v2`). 338 339 Args: 340 mode: The automatic-segmentation mode, 'amg' or 'ais'. 341 model_or_decoder: The SAM2 model (AMG) or the UniSAM2 decoder (AIS). 342 raw: The image data. 343 image_embeddings: The (optionally precomputed) image embeddings. 344 save_path: The embedding save path used to store the state, or None to skip caching. 345 kwargs: Mode-specific keyword arguments forwarded to the underlying cache function. 346 347 Returns: 348 The segmenter with the (cached or freshly computed) state set. 349 """ 350 if mode == "amg": 351 return _cache_amg_state_v2(model_or_decoder, raw, image_embeddings, save_path, **kwargs) 352 if mode == "ais": 353 return _cache_ais_state_v2(model_or_decoder, raw, image_embeddings, save_path, **kwargs) 354 raise ValueError(f"Invalid automatic-segmentation state mode: {mode!r} (expected 'amg' or 'ais').")
Compute, cache or load the SAM2 automatic-segmentation state for one image / slice / volume.
A single entry point over the two modes; both reuse a matching cached state instead of recomputing.
- 'amg': grid-based mask generation. model_or_decoder is the SAM2 model; extra kwargs are the
AMG parameters (see _cache_amg_state_v2).
- 'ais': UniSAM2 decoder prediction. model_or_decoder is the decoder; ndim is required
(see _cache_ais_state_v2).
Arguments:
- mode: The automatic-segmentation mode, 'amg' or 'ais'.
- model_or_decoder: The SAM2 model (AMG) or the UniSAM2 decoder (AIS).
- raw: The image data.
- image_embeddings: The (optionally precomputed) image embeddings.
- save_path: The embedding save path used to store the state, or None to skip caching.
- kwargs: Mode-specific keyword arguments forwarded to the underlying cache function.
Returns:
The segmenter with the (cached or freshly computed) state set.
670def precompute_state( 671 input_path: Union[os.PathLike, str], 672 output_path: Union[os.PathLike, str], 673 pattern: Optional[str] = None, 674 model_type: str = "hvit_t", 675 checkpoint_path: Optional[Union[os.PathLike, str]] = None, 676 key: Optional[str] = None, 677 ndim: Optional[int] = None, 678 precompute_autoseg_state: bool = False, 679 prefer_decoder: bool = True, 680 batch_size: Optional[int] = None, 681 devices: Optional[Union[str, Sequence[str]]] = None, 682 tile_shape: Optional[Tuple[int, int]] = None, 683 halo: Optional[Tuple[int, int]] = None, 684) -> None: 685 """Precompute and cache the image embeddings (and, optionally, the automatic-segmentation state). 686 687 The embeddings are saved in the same zarr format the annotators use, so the output can be loaded 688 directly by the `micro_sam.annotator` CLI and the napari GUI by passing the same path as the 689 embedding path (with a matching model and image). 690 691 Args: 692 input_path: The input image file(s). Can either be a single image file (e.g. tif or png), 693 a container file (e.g. hdf5 or zarr) or a folder with image files. 694 In case of a container file the argument `key` must be given. In case of a folder 695 the `pattern` argument must be given to subselect files. 696 output_path: The output path where the embeddings will be saved. For a single input this is the path 697 to the embeddings zarr; for a folder of inputs this is the directory the embeddings are saved in. 698 pattern: Glob pattern to select files in a folder. The embeddings will be computed 699 for each of these files. To select all files in a folder pass "*". 700 model_type: The model to use. Supports SAM1 ('vit_*'), SAM2 ('hvit_*') and VFM (DINO / UNI) 701 encoders. By default the `hvit_t` model is used. 702 checkpoint_path: Path to a checkpoint for a custom model. 703 key: The key to the input file. This is needed for container files (e.g. hdf5 or zarr) 704 or to load several images as 3d volume. Provide a glob pattern, e.g. "*.tif", for this case. 705 ndim: The dimensionality of the data. By default, computed from the input data. 706 precompute_autoseg_state: Whether to also precompute the automatic-segmentation state in the 707 embeddings (a longer start-up in exchange for a faster first automatic segmentation). 708 Supported for SAM2 ('hvit_*') models. 709 prefer_decoder: Whether to use the decoder-based state (AIS) when the SAM2 model has a decoder, 710 instead of grid-based mask generation (AMG). 711 batch_size: The number of tiles / slices per model call. By default it is selected per device 712 from the free VRAM (SAM2; SAM1 uses a single tile / slice). Ignored by the families 713 without batching (VFM encoders). 714 devices: The device or devices to compute the embeddings and the decoder-based (AIS) 715 automatic-segmentation state on. By default all visible CUDA devices are used. Only 716 supported for SAM2 ('hvit_*') models. 717 tile_shape: The in-plane tile shape. By default, the function uses the tiling of cached 718 embeddings. Without them, it tiles an image that is larger than the in-plane size cutoff 719 with the default tile shape. The annotation tools and the automatic segmentation use the 720 same tiling, so they can reuse these embeddings. Pass all zeros to compute the embeddings 721 without tiles. 722 halo: The in-plane tile overlap. By default, the overlap of cached embeddings, or the default 723 overlap for tiled embeddings. 724 """ 725 from .v2.util import resolve_default_tiling 726 727 is_sam2 = model_type.startswith("hvit") 728 if precompute_autoseg_state and not is_sam2: 729 raise ValueError( 730 "Precomputing the automatic-segmentation state via 'precompute_state' is only supported for " 731 "SAM2 ('hvit_*') models. For SAM1 use the annotator command with " 732 "'--precompute_autoseg_state'." 733 ) 734 735 # Dispatch to the embedding function for the model family (SAM1 / SAM2 / VFM). All share the same 736 # interface, so the per-family predictor from '_get_sam_model' feeds directly into it. 737 compute_embeddings = util.get_embedding_function(model_type) 738 739 # Only SAM2 supports multi-device inference and only SAM1 / SAM2 support batching, so forward 740 # these settings just to the families whose embedding function accepts them. 741 supported = inspect.signature(compute_embeddings).parameters 742 compute_kwargs = { 743 name: value for name, value in (("batch_size", batch_size), ("devices", devices)) 744 if name in supported 745 } 746 747 # Resolve the UniSAM2 decoder once (AIS); when none is available the state is cached with AMG. 748 decoder = None 749 if precompute_autoseg_state and prefer_decoder: 750 decoder = _resolve_unisam2_decoder(model_type, checkpoint_path, device=None) 751 752 # Determine the input files and matching output embedding paths. 753 single = pattern is None 754 if single: 755 input_files, output_paths = [input_path], [output_path] 756 else: 757 input_files = sorted(glob(os.path.join(input_path, pattern))) 758 if len(input_files) == 0: 759 raise ValueError(f"Could not find any files matching the pattern '{pattern}' in '{input_path}'.") 760 os.makedirs(output_path, exist_ok=True) 761 output_paths = [os.path.join(output_path, os.path.basename(f)) for f in input_files] 762 763 predictor, current_ndim = None, None 764 for input_file, out_path in util._progress_bar( 765 zip(input_files, output_paths), total=len(input_files), desc="Precompute embeddings", disable=single 766 ): 767 image_data = input_file if isinstance(input_file, np.ndarray) else util.load_image_data(input_file, key) 768 file_ndim = image_data.ndim if ndim is None else ndim 769 770 # Build the predictor for the data dimensionality (for SAM2 a 2d image vs. 3d video predictor). 771 # We reuse the annotator's model loader so the embeddings match what the GUI / CLI expect. 772 if predictor is None or file_ndim != current_ndim: 773 predictor, _ = util._get_sam_model( 774 model_type=model_type, ndim=file_ndim, device=None, 775 checkpoint_path=checkpoint_path, decoder_path=None, use_cli=True, 776 ) 777 current_ndim = file_ndim 778 779 save_path = str(Path(out_path).with_suffix(".zarr")) 780 # Use the tiling of the annotation tools, so that they can reuse these embeddings. 781 spatial_shape = image_data.shape[:file_ndim] 782 file_tile_shape, file_halo = resolve_default_tiling(spatial_shape, tile_shape, halo, save_path) 783 if is_sam2 and file_ndim == 3 and file_tile_shape is not None: 784 # The SAM2 embedding API takes all spatial axes; the encoder only tiles in-plane. 785 file_tile_shape, file_halo = (spatial_shape[0], *file_tile_shape), (0, *file_halo) 786 embeddings = compute_embeddings( 787 predictor=predictor, input_=image_data, save_path=save_path, ndim=file_ndim, verbose=single, 788 tile_shape=file_tile_shape, halo=file_halo, **compute_kwargs, 789 ) 790 791 if precompute_autoseg_state: 792 _cache_autoseg_state_for_file( 793 predictor, decoder, model_type, image_data, embeddings, save_path, file_ndim, verbose=single, 794 devices=devices, 795 )
Precompute and cache the image embeddings (and, optionally, the automatic-segmentation state).
The embeddings are saved in the same zarr format the annotators use, so the output can be loaded
directly by the micro_sam.annotator CLI and the napari GUI by passing the same path as the
embedding path (with a matching model and image).
Arguments:
- input_path: The input image file(s). Can either be a single image file (e.g. tif or png),
a container file (e.g. hdf5 or zarr) or a folder with image files.
In case of a container file the argument
keymust be given. In case of a folder thepatternargument must be given to subselect files. - output_path: The output path where the embeddings will be saved. For a single input this is the path to the embeddings zarr; for a folder of inputs this is the directory the embeddings are saved in.
- pattern: Glob pattern to select files in a folder. The embeddings will be computed for each of these files. To select all files in a folder pass "*".
- model_type: The model to use. Supports SAM1 ('vit_*'), SAM2 ('hvit_*') and VFM (DINO / UNI)
encoders. By default the
hvit_tmodel is used. - checkpoint_path: Path to a checkpoint for a custom model.
- key: The key to the input file. This is needed for container files (e.g. hdf5 or zarr) or to load several images as 3d volume. Provide a glob pattern, e.g. "*.tif", for this case.
- ndim: The dimensionality of the data. By default, computed from the input data.
- precompute_autoseg_state: Whether to also precompute the automatic-segmentation state in the embeddings (a longer start-up in exchange for a faster first automatic segmentation). Supported for SAM2 ('hvit_*') models.
- prefer_decoder: Whether to use the decoder-based state (AIS) when the SAM2 model has a decoder, instead of grid-based mask generation (AMG).
- batch_size: The number of tiles / slices per model call. By default it is selected per device from the free VRAM (SAM2; SAM1 uses a single tile / slice). Ignored by the families without batching (VFM encoders).
- devices: The device or devices to compute the embeddings and the decoder-based (AIS) automatic-segmentation state on. By default all visible CUDA devices are used. Only supported for SAM2 ('hvit_*') models.
- tile_shape: The in-plane tile shape. By default, the function uses the tiling of cached embeddings. Without them, it tiles an image that is larger than the in-plane size cutoff with the default tile shape. The annotation tools and the automatic segmentation use the same tiling, so they can reuse these embeddings. Pass all zeros to compute the embeddings without tiles.
- halo: The in-plane tile overlap. By default, the overlap of cached embeddings, or the default overlap for tiled embeddings.