micro_sam.v2.util
1import os 2import sys 3import shutil 4import hashlib 5import warnings 6import contextlib 7from pathlib import Path 8from typing import Any, Union, Literal, Optional, Sequence, Tuple 9 10import pooch 11import numpy as np 12 13import torch 14 15import sam2 16from sam2.build_sam import build_sam2 17from sam2.sam2_image_predictor import SAM2ImagePredictor 18 19from micro_sam.v2.models._video_predictor import _build_sam2_video_predictor 20from micro_sam.v2.normalization import IMAGE_PREPROCESSING, VIDEO_PREPROCESSING, to_image 21from micro_sam.util import ( 22 get_device, get_model_cache_directory, _open_embeddings, 23 _configure_mps_memory, device_type, make_temp_embedding_path, BF16_MIN_CAPABILITY, 24) 25 26 27Device = Optional[Union[str, torch.device]] 28Devices = Optional[Union[str, torch.device, Sequence[Union[str, torch.device]]]] 29 30# Precision preference on cuda: bf16, then fp16, then fp32. See `micro_sam.util.BF16_MIN_CAPABILITY`. 31FP16_MIN_CAPABILITY = (7, 0) 32 33 34def _precision_device(device: Device = None) -> torch.device: 35 """The device a precision decision is made for, unvalidated so a missing backend answers fp32.""" 36 return torch.device(get_device()) if device is None else torch.device(device) 37 38 39def autocast_dtype(device: Device = None) -> Optional[torch.dtype]: 40 """The dtype SAM2 and UniSAM2 inference runs in on a device. 41 42 Args: 43 device: The device the forward pass runs on. Defaults to the best available one. 44 45 Returns: 46 The half precision dtype the device runs natively, or None where inference stays in fp32. 47 """ 48 device = _precision_device(device) 49 if device.type != "cuda" or not torch.cuda.is_available(): 50 return None 51 capability = torch.cuda.get_device_capability(device) 52 if capability >= BF16_MIN_CAPABILITY: 53 return torch.bfloat16 54 if capability >= FP16_MIN_CAPABILITY: 55 return torch.float16 56 return None 57 58 59def autocast(device: Device = None): 60 """The autocast context inference runs in on a device. 61 62 Args: 63 device: The device the forward pass runs on. Defaults to the best available one. 64 65 Returns: 66 The autocast context, or a null context for fp32. 67 """ 68 device = _precision_device(device) 69 dtype = autocast_dtype(device) 70 if dtype is None: 71 return contextlib.nullcontext() 72 return torch.autocast(device_type=device.type, dtype=dtype) 73 74 75def precision_name(device: Device = None) -> str: 76 """The precision name of a device, for the embedding cache signature. 77 78 Args: 79 device: The device the forward pass runs on. 80 81 Returns: 82 One of 'bf16', 'fp16' or 'fp32'. 83 """ 84 return {torch.bfloat16: "bf16", torch.float16: "fp16", None: "fp32"}[autocast_dtype(device)] 85 86 87def to_float32(value: Any) -> Any: 88 """Cast the floating point tensors of a nested structure to fp32. 89 90 Autocast returns half precision, but the embedding cache is fp32 and numpy has no bfloat16. 91 92 Args: 93 value: A tensor, or a dict, list or tuple containing tensors. 94 95 Returns: 96 The same structure with its floating point tensors in fp32. 97 """ 98 if isinstance(value, torch.Tensor): 99 return value.float() if value.is_floating_point() else value 100 if isinstance(value, dict): 101 return {key: to_float32(item) for key, item in value.items()} 102 if isinstance(value, (list, tuple)): 103 return type(value)(to_float32(item) for item in value) 104 return value 105 106 107def encode_image(predictor, image: np.ndarray) -> None: 108 """Run the image encoder in the device precision, keeping the cached features in fp32. 109 110 Args: 111 predictor: The SAM2 image predictor. 112 image: The image to encode. 113 """ 114 with autocast(predictor.device): 115 predictor.set_image(image) 116 predictor._features = to_float32(predictor._features) 117 118 119class ImageEmbeddings(dict): 120 """Embedding result with explicit lifetime management for its backing store.""" 121 122 def __init__(self, embeddings, store=None, temporary_path=None, path=None): 123 super().__init__(embeddings) 124 self._store = store 125 self._temporary_path = temporary_path 126 self._path = path 127 self._closed = False 128 129 @property 130 def closed(self): 131 """Whether this embedding resource is closed.""" 132 return self._closed 133 134 @property 135 def temporary_path(self): 136 """The owned ephemeral path, or None for memory-backed or persistent embeddings.""" 137 return self._temporary_path 138 139 @property 140 def path(self): 141 """The store these embeddings are backed by, or None when they live in memory. 142 143 A path is what makes them readable from another process. 144 """ 145 return self._path 146 147 def close(self): 148 """Close the backing store and remove an owned ephemeral path.""" 149 if self._closed: 150 return 151 self._closed = True 152 try: 153 store = getattr(self._store, "file", self._store) 154 close = getattr(store, "close", None) 155 if close is not None: 156 close() 157 finally: 158 self._store = None 159 if self._temporary_path is not None: 160 shutil.rmtree(self._temporary_path, ignore_errors=True) 161 self._temporary_path = None 162 163 def __enter__(self): 164 return self 165 166 def __exit__(self, exc_type, exc_value, traceback): 167 self.close() 168 169 def __del__(self): 170 self.close() 171 172 173# NOTE: The model config is expected to be fetched from the module's relative path location. 174sys.path.append(str(Path(sam2.__file__).parents[0])) 175 176 177DEFAULT_BASE_MODEL = "hvit_t" 178 179# Only SAM2.1 is supported. 180CFG_PATHS = { 181 "hvit_t": "configs/sam2.1/sam2.1_hiera_t.yaml", 182 "hvit_s": "configs/sam2.1/sam2.1_hiera_s.yaml", 183 "hvit_b": "configs/sam2.1/sam2.1_hiera_b+.yaml", 184 "hvit_l": "configs/sam2.1/sam2.1_hiera_l.yaml", 185} 186 187SUPPORTED_MODELS = ["hvit_t", "hvit_s", "hvit_b", "hvit_l"] 188 189URLS = { 190 "hvit_t": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt", 191 "hvit_s": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_small.pt", 192 "hvit_b": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_base_plus.pt", 193 "hvit_l": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_large.pt", 194} 195 196HASHES = { 197 "hvit_t": "7402e0d864fa82708a20fbd15bc84245c2f26dff0eb43a4b5b93452deb34be69", 198 "hvit_s": "6d1aa6f30de5c92224f8172114de081d104bbd23dd9dc5c58996f0cad5dc4d38", 199 "hvit_b": "a2345aede8715ab1d5d31b4a509fb160c5a4af1970f199d9054ccfb746c004c5", 200 "hvit_l": "2647878d5dfa5098f2f8649825738a9345572bae2d4350a2468587ece47dd318", 201} 202 203 204# Default in-plane tiling for large images. The tool enables tiling when an in-plane axis exceeds 205# DEFAULT_TILING_THRESHOLD. The SAM input patch per axis is then DEFAULT_TILE_SHAPE + 2 * DEFAULT_HALO, 206# which is kept equal to the threshold (512 + 2 * 128 = 768). 207DEFAULT_TILING_THRESHOLD = 768 208DEFAULT_TILE_SHAPE = (512, 512) 209DEFAULT_HALO = (128, 128) 210 211# Default z block / halo for volumetric (3d) tiling. Each decoder pass spans the inner block plus the 212# halo on each side, i.e. DEFAULT_TILE_Z + 2 * DEFAULT_HALO_Z = 8 slices, matching the UniSAM2 8-slice 213# training crop (so the z-convolutions see the z-context they were trained on. Do not enlarge this 214# beyond the training crop). Set the z tile >= the slice count to disable z-tiling. 215DEFAULT_TILE_Z = 4 216DEFAULT_HALO_Z = 2 217 218# Encoder batch size per free-VRAM band in GiB, then per backbone, measured end to end. A device 219# uses the largest band it reaches, see BAND_TOLERANCE. 220VRAM_BATCH_SIZES = { 221 4: {"hvit_t": 2, "hvit_s": 2, "hvit_b": 2, "hvit_l": 1}, 222 6: {"hvit_t": 2, "hvit_s": 2, "hvit_b": 2, "hvit_l": 2}, 223 8: {"hvit_t": 4, "hvit_s": 4, "hvit_b": 4, "hvit_l": 4}, 224 10: {"hvit_t": 4, "hvit_s": 4, "hvit_b": 4, "hvit_l": 4}, 225 12: {"hvit_t": 4, "hvit_s": 4, "hvit_b": 4, "hvit_l": 4}, 226 16: {"hvit_t": 8, "hvit_s": 8, "hvit_b": 8, "hvit_l": 8}, 227 24: {"hvit_t": 8, "hvit_s": 8, "hvit_b": 8, "hvit_l": 8}, 228 32: {"hvit_t": 16, "hvit_s": 16, "hvit_b": 16, "hvit_l": 16}, 229 40: {"hvit_t": 16, "hvit_s": 16, "hvit_b": 16, "hvit_l": 16}, 230 48: {"hvit_t": 16, "hvit_s": 16, "hvit_b": 16, "hvit_l": 16}, 231 80: {"hvit_t": 32, "hvit_s": 32, "hvit_b": 32, "hvit_l": 32}, 232} 233 234# The backbone assumed for an unknown model name, the most memory-hungry one in the table. 235FALLBACK_BACKBONE = "hvit_l" 236 237# Bands are keyed by nominal card size, but a card never reports all of it as free (CUDA context, 238# ECC reserve): an 80 GB A100 has 79.25 GiB. Without this slack every such card falls a band short. 239BAND_TOLERANCE = 0.95 240 241 242def _band_for(free_gib): 243 """The largest tabulated VRAM band the device reaches, or None if it reaches none.""" 244 reached = [band for band in VRAM_BATCH_SIZES if free_gib >= band * BAND_TOLERANCE] 245 return max(reached) if reached else None 246 247 248def _backbone_of(model_type): 249 """Map a model name onto its backbone, e.g. 'hvit_t_cells' -> 'hvit_t'.""" 250 backbone = str(model_type)[:6] 251 return backbone if backbone in SUPPORTED_MODELS else FALLBACK_BACKBONE 252 253 254def parameter_family(model_type): 255 """The family whose default parameters a model uses, e.g. 'em_mito' for 'hvit_s_em_mito'. 256 257 A backbone or a cells model, e.g. 'hvit_t' or 'hvit_t_cells', uses the 'cells' defaults. 258 """ 259 return str(model_type)[7:] or "cells" 260 261 262def _free_vram_gib(device): 263 """The free VRAM of a CUDA device in GiB, or None for a non-CUDA device.""" 264 device = torch.device(device) 265 if device.type != "cuda" or not torch.cuda.is_available(): 266 return None 267 return torch.cuda.mem_get_info(device)[0] / 1024 ** 3 268 269 270def recommend_batch_size(model_type, device, n_jobs=None): 271 """Look up the encoder batch size for a model on a device. 272 273 Args: 274 model_type: The model name, e.g. 'hvit_t' or 'hvit_t_cells'. Unknown names are treated as the 275 most memory-hungry backbone. 276 device: The device the encoder runs on. Non-CUDA devices always get a batch size of one, as 277 does a device with less free VRAM than the smallest tabulated band. 278 n_jobs: The total number of tiles / slices, to avoid a batch larger than the work. 279 280 Returns: 281 The batch size to use, at least one. 282 """ 283 free_gib = _free_vram_gib(device) 284 if free_gib is None: 285 return 1 286 287 band = _band_for(free_gib) 288 if band is None: 289 # The smallest entry is calibrated for the smallest band, not below it, so a device that 290 # reaches no band stays at one instead of relying on the OOM backoff to recover. 291 return 1 292 293 batch_size = VRAM_BATCH_SIZES[band][_backbone_of(model_type)] 294 if n_jobs is not None: 295 batch_size = min(batch_size, max(1, int(n_jobs))) 296 return int(batch_size) 297 298 299def needs_default_tiling(shape): 300 """Whether to enable default in-plane tiling for a given image shape. 301 302 Args: 303 shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z, y, x); 304 for 3d only the in-plane (y, x) axes are considered, not the leading z axis. 305 306 Returns: 307 Whether tiling should be enabled by default. 308 """ 309 if len(shape) == 2: 310 return shape[0] > DEFAULT_TILING_THRESHOLD or shape[1] > DEFAULT_TILING_THRESHOLD 311 elif len(shape) == 3: 312 return shape[1] > DEFAULT_TILING_THRESHOLD or shape[2] > DEFAULT_TILING_THRESHOLD 313 return False 314 315 316def tiling_is_turned_off(value): 317 """Whether a tile shape or halo explicitly asks for no tiling, i.e. is all zeros. 318 319 Every micro-sam entry point tiles by default, so an all-zero tile shape (and halo) is how a 320 caller says "run this in one piece" - the CLI also spells it `--tile_shape none --overlap none`. 321 322 Args: 323 value: A tile shape or halo, which may be None. 324 325 Returns: 326 Whether it turns tiling off. False for None, which means 'not set'. 327 """ 328 return value is not None and len(value) > 0 and all(int(entry) == 0 for entry in value) 329 330 331def resolve_default_tiling(shape, tile_shape, halo, embedding_path=None): 332 """Resolve the tiling settings for an entry point from the image shape and the embedding cache. 333 334 This is the single source of truth for the tiling defaults of all entry points: the annotation 335 tools (interactive segmentation, tracking, pixel and object classification, and their batch 336 variants) and the headless inference front-ends. The annotation tools compute their embeddings 337 before the GUI is built, so they have to resolve the same settings the embedding widget would 338 show for the image (see `EmbeddingWidget._apply_default_tiling_for_shape`). 339 340 Settings the caller passes always win. Otherwise the tiling of already cached embeddings is 341 adopted, so pointing a tool at an existing embedding path reuses it instead of recomputing it 342 just because the defaults have changed or another tool used different settings. Embeddings that 343 are cached without tiling are the exception: they are recomputed with the default tiling rather 344 than kept, since running untiled is what the default guards against. 345 346 Automatic tiling kicks in above the in-plane size cutoff (`DEFAULT_TILING_THRESHOLD`), the same 347 way for every entry point. Below it, and whenever the caller turns tiling off with an all-zero 348 tile shape, the image is passed to the model in one piece. 349 350 Args: 351 shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z / t, y, x). 352 tile_shape: The requested in-plane tile shape. If None, the tile shape of the cached 353 embeddings is used, else the default tile shape for images exceeding the in-plane size 354 cutoff. All zeros turns tiling off. 355 halo: The requested in-plane tile overlap. If None, the overlap of the cached embeddings is 356 used, or the default overlap, since tiling without an overlap cuts objects at the tile 357 borders. 358 embedding_path: Optional filepath of the cached embeddings. 359 360 Returns: 361 The resolved tile shape, None if the embeddings are computed without tiling. 362 The resolved halo, None if the embeddings are computed without tiling. 363 364 Raises: 365 ValueError: If tiling is turned off with an all-zero tile shape but a real halo is given. 366 """ 367 from micro_sam.util import read_cached_tiling 368 369 if tiling_is_turned_off(tile_shape): 370 if halo is not None and not tiling_is_turned_off(halo): 371 raise ValueError( 372 f"Tiling is turned off by an all-zero 'tile_shape', so the halo {tuple(halo)} cannot " 373 "be used. Set both to zero, or give a real tile shape." 374 ) 375 return None, None 376 377 cached = read_cached_tiling(embedding_path) if tile_shape is None else None 378 if cached is not None and cached[0] is not None: 379 tile_shape = cached[0] 380 if halo is None: 381 halo = cached[1] 382 elif tile_shape is None and needs_default_tiling(shape): 383 tile_shape = DEFAULT_TILE_SHAPE 384 385 # An all-zero halo is kept as given: with a real tile shape it means 'tile without an overlap'. 386 if tile_shape is not None and halo is None: 387 halo = DEFAULT_HALO 388 return tile_shape, halo 389 390 391# Finetuned SAM2 models (the micro-sam "model download console" for SAM2). These are exported into 392# the two-file micro-sam layout - an interactive predictor checkpoint ('<name>') and a UniSAM2 393# decoder checkpoint ('<name>_decoder') - by 'scripts/model_export/export_sam2_cells_model.py'. 394# This mirrors the v1 'micro_sam.v1.util.models' registry (encoder + '_decoder' entries) so the 395# backend (download, loading, GUI, automatic segmentation) works the same way as for SAM v1. 396# The base SAM2 backbone is read off the first 6 characters of the name (e.g. 'hvit_t_cells' -> 397# 'hvit_t'), so no explicit backbone mapping is needed. The user-facing GUI name is defined in the 398# annotator widgets. 399FINETUNED_MODELS = [ 400 # Microscopy generalist: joint SAM2 + UniSAM2 models, one per SAM2 backbone. 401 "hvit_t_cells", 402 "hvit_s_cells", 403 "hvit_b_cells", 404 "hvit_l_cells", 405 # EM organelle models: joint SAM2 + UniSAM2 models for mitochondria and nuclei in electron microscopy. 406 "hvit_s_em_mito", 407 "hvit_s_em_nuclei", 408] 409 410# The default model for the annotation tools (GUI + CLI + Python API). This is the single source of 411# truth for the default. The GUI derives its synthetic 'vit_<size><suffix>' selector string from it. 412DEFAULT_MODEL = "hvit_t_cells" 413 414# The UniSAM2 decoder prediction for automatic segmentation: foreground probability, the three directed 415# distances and the object boundary, in this order. Inference supports only this layout. 416UNISAM2_OUTPUT_CHANNELS = 5 417 418# All models below in the model registry for "_cells" are v6. 419FINETUNED_URLS = { 420 "hvit_t_cells": "https://owncloud.gwdg.de/index.php/s/XZuc5IqxQ1AlWaN/download", 421 "hvit_t_cells_decoder": "https://owncloud.gwdg.de/index.php/s/KEtW0dobX2az0GO/download", 422 "hvit_s_cells": "https://owncloud.gwdg.de/index.php/s/oFWEPBQQqOwxq07/download", 423 "hvit_s_cells_decoder": "https://owncloud.gwdg.de/index.php/s/Zweh3Ew1eO9Loen/download", 424 "hvit_b_cells": "https://owncloud.gwdg.de/index.php/s/IgyXnqw3YuGXP3L/download", 425 "hvit_b_cells_decoder": "https://owncloud.gwdg.de/index.php/s/Eo3ntD2pCdv89xg/download", 426 "hvit_l_cells": "https://owncloud.gwdg.de/index.php/s/MBLqZEMuaC94toI/download", 427 "hvit_l_cells_decoder": "https://owncloud.gwdg.de/index.php/s/Y0exLXtfdIZV96Z/download", 428 "hvit_s_em_mito": "https://owncloud.gwdg.de/index.php/s/I4WsyC5AGhzkO3F/download", 429 "hvit_s_em_mito_decoder": "https://owncloud.gwdg.de/index.php/s/xv1V7oOrNpBHI69/download", 430 "hvit_s_em_nuclei": "https://owncloud.gwdg.de/index.php/s/0fxQ0upPSOWA0CB/download", 431 "hvit_s_em_nuclei_decoder": "https://owncloud.gwdg.de/index.php/s/cLV7fgboWQhrigP/download", 432} 433 434FINETUNED_HASHES = { 435 "hvit_t_cells": "xxh128:64f0142a7a1996ab3017f2f47a21926c", 436 "hvit_t_cells_decoder": "xxh128:a469c3d0a5b65804c7858fc46f3f83ec", 437 "hvit_s_cells": "xxh128:bf42e744511ed46c35e21935a5b03e49", 438 "hvit_s_cells_decoder": "xxh128:ed69d386eb2bd4141279bb4b459eb903", 439 "hvit_b_cells": "xxh128:7854c938a67af3bd46339e821b38f5b0", 440 "hvit_b_cells_decoder": "xxh128:0e2fec5d1054a6208a32826ad057d941", 441 "hvit_l_cells": "xxh128:3ca5cba0d9622b228615d6aaa1de5d08", 442 "hvit_l_cells_decoder": "xxh128:859083bcabcf885168cb6c0f0273d372", 443 "hvit_s_em_mito": "xxh128:126d208c5014e9579d989f780bee3591", 444 "hvit_s_em_mito_decoder": "xxh128:ca6258931fb13de9b798d6273113fc84", 445 "hvit_s_em_nuclei": "xxh128:c5e86906c09c3faddf1e37b2aa47042a", 446 "hvit_s_em_nuclei_decoder": "xxh128:a630123692743f1309449c1b3a177e4c", 447} 448 449 450def models(): 451 """Return the finetuned SAM2 models registry. 452 453 Mirrors `micro_sam.v1.util.models`: finetuned SAM2 checkpoints and their UniSAM2 decoders are 454 registered with their xxh128 hashes and download URLs and fetched via pooch. The base SAM2 455 backbones (hvit_t/s/b/l) are downloaded separately, see `_get_checkpoint`. 456 457 Returns: 458 The pooch registry for the finetuned SAM2 models. 459 """ 460 registry = pooch.create( 461 path=get_model_cache_directory(), 462 base_url="", 463 registry=FINETUNED_HASHES, 464 urls=FINETUNED_URLS, 465 ) 466 return registry 467 468 469def get_model_names(): 470 """Return the names of the finetuned SAM2 models available in the download console.""" 471 return list(FINETUNED_MODELS) 472 473 474def has_registered_decoder(model_type): 475 """Whether a finetuned SAM2 model has a registered UniSAM2 decoder (for automatic segmentation). 476 477 A cheap registry lookup (no download), used e.g. to decide the default automatic-segmentation mode 478 before the model / decoder has actually been loaded. 479 480 Args: 481 model_type: The SAM2 model name, e.g. 'hvit_t_cells'. 482 483 Returns: 484 Whether a '<model_type>_decoder' is registered. 485 """ 486 return f"{model_type}_decoder" in FINETUNED_HASHES 487 488 489def _download_finetuned_sam2_model(model_type, progress_bar_factory=None): 490 """Download a finetuned SAM2 model and (if available) its UniSAM2 decoder. 491 492 Mirrors `micro_sam.v1.util._download_sam_model`. 493 494 Args: 495 model_type: The finetuned model name, e.g. 'hvit_t_cells'. 496 progress_bar_factory: Optional callable creating a progress bar for the download. 497 498 Returns: 499 A tuple of (checkpoint_path, model_hash, decoder_path). 'decoder_path' is None if the model 500 does not have a registered decoder. 501 """ 502 model_registry = models() 503 504 progress_bar = True 505 if not os.path.exists(get_model_cache_directory() / model_type) and progress_bar_factory is not None: 506 progress_bar = progress_bar_factory(model_type) 507 508 checkpoint_path = model_registry.fetch(model_type, progressbar=progress_bar) 509 if not isinstance(progress_bar, bool): 510 progress_bar.close() 511 512 model_hash = model_registry.registry[model_type] 513 514 decoder_name = f"{model_type}_decoder" 515 decoder_path = model_registry.fetch( 516 decoder_name, progressbar=True 517 ) if decoder_name in model_registry.registry else None 518 519 return checkpoint_path, model_hash, decoder_path 520 521 522def _get_device(device=None): 523 if device is None or device == "auto": 524 device = get_device() 525 else: 526 _configure_mps_memory(device) 527 528 if device_type(device) == "cuda": 529 # NOTE: Adapt global variables to work with flash attentions. 530 sam2.modeling.sam.transformer.OLD_GPU = True 531 sam2.modeling.sam.transformer.USE_FLASH_ATTN = True 532 sam2.modeling.sam.transformer.MATH_KERNEL_ON = True 533 534 return device 535 536 537def _get_checkpoint(model_type=DEFAULT_BASE_MODEL): 538 return pooch.retrieve( 539 url=URLS[model_type], known_hash=HASHES[model_type], fname=model_type, path=get_model_cache_directory(), 540 progressbar=True, 541 ) 542 543 544def _get_registry_checkpoint(model_type): 545 """Download the weights of a model name: finetuned micro-sam weights or a base SAM2 backbone.""" 546 if model_type in FINETUNED_MODELS: 547 checkpoint_path, _, _ = _download_finetuned_sam2_model(model_type) 548 return checkpoint_path 549 return _get_checkpoint(model_type=model_type) 550 551 552def _build_sam2_backbone(model_cfg, checkpoint_path, device, input_type): 553 """Build the SAM2 image model or the SAM2 video predictor from a config and a checkpoint.""" 554 if input_type == "images": 555 return build_sam2( 556 config_file=model_cfg, ckpt_path=checkpoint_path, device=device, mode="eval", apply_postprocessing=False 557 ) 558 return _build_sam2_video_predictor(config_file=model_cfg, ckpt_path=checkpoint_path, device=device) 559 560 561# The (embedding dimension, number of blocks) of the Hiera trunk of each SAM2 backbone. 562BACKBONE_SIGNATURES = {(96, 12): "hvit_t", (96, 16): "hvit_s", (112, 24): "hvit_b", (144, 48): "hvit_l"} 563 564 565def strip_wrapper_prefixes(state: dict) -> dict: 566 """Remove the key prefixes that DDP ('module.') and torch.compile ('_orig_mod.') add to model weights. 567 568 Args: 569 state: The model weights. 570 571 Returns: 572 The model weights without these prefixes. 573 """ 574 prefixes = ("module.", "_orig_mod.") 575 576 def _strip(key): 577 while key.startswith(prefixes): 578 key = key[len(next(p for p in prefixes if key.startswith(p))):] 579 return key 580 581 return {_strip(key): value for key, value in state.items()} 582 583 584def _read_sam2_checkpoint(checkpoint_path): 585 """Read a SAM2 checkpoint. 586 587 Args: 588 checkpoint_path: The path to the checkpoint. It holds the weights directly, or under 'model' 589 (the SAM2 and registry format) or 'model_state' (the training format). A UniSAM2 decoder 590 checkpoint holds only the image encoder of the SAM2 model. 591 592 Returns: 593 The full checkpoint, the weights of the SAM2 model, and whether these are only the image encoder. 594 595 Raises: 596 ValueError: If the checkpoint holds no SAM2 image encoder. 597 """ 598 from ..util import load_checkpoint 599 600 state = load_checkpoint(checkpoint_path) 601 model_state = state 602 if isinstance(state, dict): 603 for key in ("model", "model_state"): 604 if isinstance(state.get(key), dict): 605 model_state = state[key] 606 break 607 model_state = strip_wrapper_prefixes(model_state) 608 609 encoder_only = "image_encoder.trunk.patch_embed.proj.weight" not in model_state 610 if encoder_only: 611 # UniSAM2 holds the SAM2 image encoder under 'encoder.inner'. 612 prefix = "encoder.inner." 613 model_state = {"image_encoder." + k[len(prefix):]: v for k, v in model_state.items() if k.startswith(prefix)} 614 if "image_encoder.trunk.patch_embed.proj.weight" not in model_state: 615 raise ValueError(f"'{checkpoint_path}' holds no SAM2 model.") 616 return state, model_state, encoder_only 617 618 619def detect_sam2_backbone(model_state: dict) -> str: 620 """Detect the SAM2 backbone of model weights from the shape of the Hiera trunk. 621 622 Args: 623 model_state: The weights of a SAM2 model, with or without PEFT. 624 625 Returns: 626 The backbone name, for example 'hvit_b'. 627 628 Raises: 629 ValueError: If the trunk matches no known backbone. 630 """ 631 embed_dim = int(model_state["image_encoder.trunk.patch_embed.proj.weight"].shape[0]) 632 prefix = "image_encoder.trunk.blocks." 633 n_blocks = 1 + max(int(k[len(prefix):].split(".")[0]) for k in model_state if k.startswith(prefix)) 634 backbone = BACKBONE_SIGNATURES.get((embed_dim, n_blocks)) 635 if backbone is None: 636 raise ValueError(f"No SAM2 backbone has {n_blocks} blocks with embedding dimension {embed_dim}.") 637 return backbone 638 639 640def _load_sam2_from_state(model_cfg, input_type, model_state, device, peft_kwargs=None): 641 """Build a SAM2 model and load all of its weights from a checkpoint, without the base weights. 642 643 The function applies the PEFT method before it loads the weights, so that the added parameters exist. 644 645 Args: 646 model_cfg: The SAM2 model config path. 647 input_type: The input type, which is images or videos. 648 model_state: The weights of the SAM2 model. 649 device: The pytorch device. 650 peft_kwargs: The arguments for `PEFT_Sam2`, or None for a model without PEFT. 651 652 Returns: 653 The SAM2 model with the weights loaded. 654 """ 655 # The checkpoint defines every weight, so the base weights are not loaded or downloaded. 656 model = _build_sam2_backbone(model_cfg, None, device, input_type) 657 if peft_kwargs: 658 from micro_sam.v2.models.peft_sam2 import PEFT_Sam2 659 model = PEFT_Sam2(model, **peft_kwargs).sam 660 661 try: 662 model.load_state_dict(model_state) 663 except RuntimeError as e: 664 hint = f"Pass the PEFT settings of the training, not peft_kwargs={peft_kwargs}." if peft_kwargs else "" 665 raise RuntimeError(f"The checkpoint does not match the SAM2 model. {hint}") from e 666 model.to(device) 667 model.eval() 668 return model 669 670 671def get_sam2_model( 672 model_type: str = DEFAULT_BASE_MODEL, 673 device: Optional[Union[torch.device, str]] = None, 674 checkpoint_path: Optional[Union[os.PathLike, str]] = None, 675 input_type: Literal["images", "videos"] = "images", 676 peft_kwargs: Optional[dict] = None, 677): 678 """Get the Segment Anything 2 (SAM2) model for interactive segmentation of images and videos. 679 680 Args: 681 model_type: The choice of size for the vision transformer, eg. `hvit_t`. The default is `hvit_t` model. 682 With `checkpoint_path`, the backbone of the checkpoint replaces the backbone of this name. 683 device: The pytorch device. 684 checkpoint_path: Filepath to the model weights. The function then does not download the weights of 685 `model_type`. 686 input_type: Whether the inputs are images or videos. 687 peft_kwargs: The arguments for `PEFT_Sam2`. The function uses the arguments in the checkpoint by default. 688 689 Returns: 690 The SAM2 model. 691 """ 692 device = _get_device(device) 693 694 if input_type not in ("images", "videos"): 695 raise ValueError(f"'{input_type}' is not a valid input type.") 696 697 model_hash = None 698 if checkpoint_path is None: 699 checkpoint_path = _get_registry_checkpoint(model_type) 700 else: 701 # The cached embeddings of other weights with the same model name must not be reused. 702 from micro_sam.util import _compute_hash 703 model_hash = _compute_hash(checkpoint_path) 704 705 state, model_state, encoder_only = _read_sam2_checkpoint(checkpoint_path) 706 backbone = detect_sam2_backbone(model_state) 707 if backbone != model_type[:6]: 708 print(f"The checkpoint holds a '{backbone}' model, so it is used instead of '{model_type[:6]}'.") 709 model_type = backbone + model_type[6:] 710 if encoder_only: 711 # The prompt encoder, mask decoder and memory come from the registry, the image encoder from the checkpoint. 712 base_type = model_type if model_type in FINETUNED_MODELS else backbone 713 _, base_state, _ = _read_sam2_checkpoint(_get_registry_checkpoint(base_type)) 714 model_state = {**{k: v for k, v in base_state.items() if not k.startswith("image_encoder.")}, **model_state} 715 716 if not peft_kwargs and isinstance(state, dict) and state.get("peft_kwargs") is not None: 717 from micro_sam.v2.models.peft_sam2 import PEFT_MODULES 718 from micro_sam.models.peft import deserialize_peft_kwargs 719 peft_kwargs = deserialize_peft_kwargs(state["peft_kwargs"], PEFT_MODULES) 720 if peft_kwargs: 721 peft_kwargs = {k: v for k, v in peft_kwargs.items() if k != "quantize"} 722 723 model = _load_sam2_from_state(CFG_PATHS[backbone], input_type, model_state, device, peft_kwargs) 724 if peft_kwargs: 725 from micro_sam.models.peft import serialize_peft_kwargs 726 # Training reads the PEFT settings from here, so that it continues with the same PEFT layers. 727 model.peft_config = serialize_peft_kwargs(peft_kwargs) 728 729 # Both predictor wrappers and direct model use need this metadata for embedding signatures. 730 model.model_type = model_type 731 model.model_name = model_type # TODO: What is this exactly? 732 model._hash = model_hash 733 734 return model 735 736 737def export_custom_qlora_sam2_model( 738 checkpoint_path: Optional[Union[str, os.PathLike]], 739 finetuned_path: Union[str, os.PathLike], 740 model_type: str, 741 save_path: Union[str, os.PathLike], 742) -> None: 743 """Export a SAM2 model from QLoRA to a full-precision LoRA checkpoint. 744 745 The export keeps the trained parameters. It gets the frozen encoder parameters from the base model. 746 747 Args: 748 checkpoint_path: The path to the base checkpoint. Use None to download the default checkpoint. 749 finetuned_path: The path to the QLoRA checkpoint. 750 model_type: The SAM2 model type, for example, 'hvit_t'. 751 save_path: The path for the exported checkpoint. 752 """ 753 sam = get_sam2_model(model_type=model_type, checkpoint_path=checkpoint_path, device="cpu") 754 755 from ..util import load_checkpoint 756 757 ft_state = load_checkpoint(finetuned_path) 758 if isinstance(ft_state, dict) and "model_state" in ft_state: 759 ft_model_state = ft_state["model_state"] 760 elif isinstance(ft_state, dict) and "model" in ft_state: 761 ft_model_state = ft_state["model"] 762 else: 763 ft_model_state = ft_state 764 ft_model_state = strip_wrapper_prefixes(ft_model_state) 765 766 updated_model_state = {k: v for k, v in ft_model_state.items() if not k.startswith("image_encoder.")} 767 modified_attn_layers = set() 768 modified_mlp_layers = set() 769 for k, v in ft_model_state.items(): 770 if not k.startswith("image_encoder."): 771 continue 772 layer_id = int(k.split("blocks.")[1].split(".")[0]) if "blocks." in k else None 773 if "qkv.w_a_linear" in k or "qkv.w_b_linear" in k: 774 modified_attn_layers.add(layer_id) 775 updated_model_state[k] = v 776 if "mlp.w_a_linear" in k or "mlp.w_b_linear" in k: 777 modified_mlp_layers.add(layer_id) 778 updated_model_state[k] = v 779 780 for k, v in sam.state_dict().items(): 781 if not k.startswith("image_encoder."): 782 continue 783 layer_id = int(k.split("blocks.")[1].split(".")[0]) if "blocks." in k else None 784 if "attn.qkv." in k: 785 if layer_id in modified_attn_layers: 786 k = k.replace("qkv", "qkv.qkv_proj") 787 elif "mlp" in k and "image_encoder" in k: 788 if layer_id in modified_mlp_layers: 789 k = k.replace("mlp.", "mlp.mlp_layer.") 790 updated_model_state[k] = v 791 792 if isinstance(ft_state, dict) and "model_state" in ft_state: 793 ft_state["model_state"] = updated_model_state 794 out_state = ft_state 795 elif isinstance(ft_state, dict) and "model" in ft_state: 796 ft_state["model"] = updated_model_state 797 out_state = ft_state 798 else: 799 out_state = {"model": updated_model_state, "model_type": model_type} 800 801 torch.save(out_state, save_path) 802 803 804class _PrecisionImagePredictor(SAM2ImagePredictor): 805 """A SAM2 image predictor whose prompt encoder and mask decoder run in the device precision.""" 806 807 def _predict(self, *args, **kwargs): 808 with autocast(self.device): 809 return to_float32(super()._predict(*args, **kwargs)) 810 811 812def configure_image_predictor(predictor): 813 """Configure a SAM2 image predictor to always use resize-longest.""" 814 from micro_sam.v2.transforms.resize import ResizeLongestSideTransforms 815 816 old = predictor._transforms 817 predictor._transforms = ResizeLongestSideTransforms( 818 resolution=predictor.model.image_size, 819 mask_threshold=predictor.mask_threshold, 820 max_hole_area=getattr(old, "max_hole_area", 0.0), 821 max_sprinkle_area=getattr(old, "max_sprinkle_area", 0.0), 822 ) 823 return predictor 824 825 826def get_sam2_image_predictor(model, **kwargs): 827 """Build a SAM2 image predictor with resize-longest preprocessing and the device precision. 828 829 The predictor takes the 'model_type', 'model_name' and '_hash' of a model from `get_sam2_model`, 830 which the embedding cache writes to its signature and checks. 831 """ 832 predictor = configure_image_predictor(_PrecisionImagePredictor(model, **kwargs)) 833 for name in ("model_type", "model_name", "_hash"): 834 if hasattr(model, name): 835 setattr(predictor, name, getattr(model, name)) 836 return predictor 837 838 839def _predictor_device(predictor) -> torch.device: 840 """The device a predictor runs on, whether it exposes it as an attribute or as a method.""" 841 device = getattr(predictor, "device", None) 842 if callable(device): 843 device = device() 844 if device is None: 845 device = next(predictor.parameters()).device 846 return torch.device(device) 847 848 849def _normalization_bounds_digest(norm_bounds): 850 """Return a stable digest of the arrays that determine volume normalization.""" 851 if norm_bounds is None: 852 return None 853 digest = hashlib.sha1() 854 for bound in norm_bounds: 855 array = np.asarray(bound) 856 digest.update(array.dtype.str.encode("utf-8")) 857 digest.update(np.asarray([array.ndim], dtype="<i8").tobytes()) 858 digest.update(np.asarray(array.shape, dtype="<i8").tobytes()) 859 digest.update(np.ascontiguousarray(array).tobytes()) 860 return digest.hexdigest() 861 862 863def _check_saved_embeddings(input_, predictor, f, save_path, tile_shape, halo, preprocessing, norm_bounds=None): 864 """Validate saved embeddings against the requested configuration. 865 866 Returns True if the saved embeddings are stale and should be recomputed (the model, tiling, 867 preprocessing or normalization bounds changed), False if they can be loaded. Raises if they 868 belong to different image data (data signature mismatch). `preprocessing` is the policy expected 869 for the current path (2d image or 3d / video, see `micro_sam.v2.normalization`). 870 """ 871 # We can have an empty zarr file that was already created to save the embeddings in. A 872 # feature-bearing file without the completion metadata is a partial cache: reject it unless it 873 # explicitly records the current preprocessing policy. Untagged caches can use the former video 874 # resize implementation and cannot be safely resumed. 875 bounds_digest = _normalization_bounds_digest(norm_bounds) if preprocessing == VIDEO_PREPROCESSING else None 876 if "input_size" not in f.attrs: 877 normalization = f.attrs.get("normalization") 878 bounds_changed = ( 879 bounds_digest is not None and f.attrs.get("normalization_bounds_digest") != bounds_digest 880 ) 881 return "features" in f and (normalization != preprocessing or bounds_changed) 882 883 # Creates all the metadata that is stored along with the embeddings. 884 # TODO: This is currently paired with `micro_sam`-level metadata. Should we get separate for `micro_sam.v2`? 885 from micro_sam.util import _get_embedding_signature 886 signature = _get_embedding_signature(input_, predictor, tile_shape, halo) 887 signature["normalization"] = preprocessing 888 signature["precision"] = precision_name(_predictor_device(predictor)) 889 if bounds_digest is not None: 890 signature["normalization_bounds_digest"] = bounds_digest 891 892 stale = False 893 for key, val in signature.items(): 894 # Missing current preprocessing metadata means stale. We still tolerate other legacy signature fields. 895 if key not in f.attrs: 896 if key in ("normalization", "normalization_bounds_digest", "precision"): 897 stale = True 898 continue 899 if f.attrs[key] == val: 900 continue 901 # Different image data: surface as an error rather than silently overwriting it. 902 if key == "data_signature": 903 raise RuntimeError( 904 f"Embeddings file {save_path} is invalid due to mismatch in {key}: " 905 f"{f.attrs.get(key)} != {val}. Please recompute embeddings in a new file." 906 ) 907 # A version bump alone does not invalidate the embeddings. 908 if key == "micro_sam_version": 909 warnings.warn( 910 f"The signature for {key} in embeddings file {save_path} has a mismatch: " 911 f"{f.attrs.get(key)} != {val}. This key was recently added, so your embeddings are likely correct. " 912 "But please recompute them if model predictions don't look as expected." 913 ) 914 continue 915 # Model, tiling or normalization changed: the saved embeddings are stale and must be recomputed. 916 stale = True 917 return stale 918 919 920def _write_embedding_signature( 921 f, input_, predictor, tile_shape, halo, input_size, original_size, preprocessing, norm_bounds=None, 922): 923 """Write the common embedding metadata plus the SAM2 preprocessing policy, bounds and precision.""" 924 from micro_sam.util import _write_embedding_signature as _write_common_signature 925 926 _write_common_signature(f, input_, predictor, tile_shape, halo, input_size, original_size) 927 f.attrs["normalization"] = preprocessing 928 bounds_digest = _normalization_bounds_digest(norm_bounds) if preprocessing == VIDEO_PREPROCESSING else None 929 if bounds_digest is not None: 930 f.attrs["normalization_bounds_digest"] = bounds_digest 931 # The encoder precision changes the stored values, so another one is stale. 932 f.attrs["precision"] = precision_name(_predictor_device(predictor)) 933 934 935def _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update): 936 # Check if the embeddings are already cached. 937 if save_path is not None and "original_size" in f.attrs: 938 # In this case we load the embeddings. 939 features = f["features"][:] 940 original_size = f.attrs["original_size"] 941 input_size = f.attrs["input_size"] 942 # The high-resolution features are stored as a list of datasets and are needed by the decoder. 943 high_res_features = _load_list_datasets(f, "high_res_feats", lazy_loading=False) 944 image_embeddings = { 945 "features": features, 946 "high_res_feats": high_res_features, 947 "input_size": input_size, 948 "original_size": original_size, 949 } 950 # Also set the embeddings. 951 set_precomputed(predictor, image_embeddings) 952 return image_embeddings 953 954 pbar_init(1, "Compute Image Embeddings 2D") 955 # Otherwise we have to compute the embeddings. 956 predictor.reset_predictor() 957 958 encode_image(predictor, to_image(input_)) 959 features = predictor.get_image_embedding().cpu().numpy() 960 high_res_features = predictor._features.get("high_res_feats") 961 original_size = predictor._orig_hw 962 # SAM2ImagePredictor exposes the model resolution via its underlying model, unlike the 963 # video predictor which subclasses SAM2Base and has 'image_size' directly. 964 input_size = predictor.model.image_size 965 pbar_update(1) 966 967 # Save the embeddings if we have a save_path. 968 if save_path is not None: 969 from micro_sam.util import _create_dataset_with_data 970 _create_dataset_with_data(f, "features", data=features) 971 # Store the high-resolution features (a list of tensors) needed by the SAM2 decoder. 972 high_res_group = f.require_group("high_res_feats") 973 for i, feat in enumerate(high_res_features): 974 _create_dataset_with_data(high_res_group, str(i), data=feat.cpu().numpy()) 975 _write_embedding_signature( 976 f, input_, predictor, tile_shape=None, halo=None, input_size=input_size, 977 original_size=original_size, preprocessing=IMAGE_PREPROCESSING, 978 ) 979 980 image_embeddings = { 981 "features": features, 982 "high_res_feats": high_res_features, 983 "input_size": input_size, 984 "original_size": original_size, 985 } 986 return image_embeddings 987 988 989def _load_list_datasets(group, prefix_name, lazy_loading): 990 if prefix_name not in group: 991 return [] 992 993 subgroup = group[prefix_name] 994 out = [] 995 i = 0 996 while str(i) in subgroup: 997 ds = subgroup[str(i)] 998 out.append(ds if lazy_loading else ds[:]) 999 i += 1 1000 return out 1001 1002 1003def precompute_image_embeddings( 1004 predictor, 1005 input_: np.ndarray, 1006 save_path: Optional[Union[str, os.PathLike]] = None, 1007 lazy_loading: bool = False, 1008 ndim: Optional[int] = None, 1009 tile_shape: Optional[Tuple[int, ...]] = None, 1010 halo: Optional[Tuple[int, ...]] = None, 1011 verbose: bool = True, 1012 batch_size: Optional[int] = None, 1013 devices: Devices = None, 1014 num_prefetch_workers: int = 4, 1015 num_write_workers: int = 2, 1016 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 1017 pbar_init: Optional[callable] = None, 1018 pbar_update: Optional[callable] = None, 1019): 1020 """Compute the image embeddings (output of the encoder) for the input. 1021 1022 If 'save_path' is given the embeddings will be loaded/saved in a zarr container. 1023 1024 Args: 1025 predictor: The SAM2 image or video predictor. 1026 input_: The input image or volume. 1027 save_path: Optional zarr path for persistent embedding storage. 1028 lazy_loading: Stream embeddings from zarr instead of materializing them in memory. Without 1029 `save_path`, the returned `ImageEmbeddings` owns an ephemeral on-disk store; use it as a 1030 context manager or call `close()` when finished. 1031 ndim: The number of spatial dimensions. By default this is inferred from the input. 1032 tile_shape: Optional tile shape. Pass (y, x) for 2d data or (z, y, x) for 3d data. The 1033 encoder uses only the in-plane entries for 3d data. 1034 halo: Optional tile halo with the same axes as `tile_shape`. 1035 verbose: Whether to show progress. 1036 batch_size: The batch size used when running inference for multiple slices and / or tiles. 1037 By default it is looked up independently on each CUDA device from its free VRAM (see 1038 `recommend_batch_size`). Pass an integer to run every device at that batch size. 1039 devices: Device or devices used for embedding inference. If None and the predictor is on 1040 CUDA, all visible CUDA devices are used. 1041 num_prefetch_workers: Number of threads used to read and preprocess input jobs. 1042 num_write_workers: Number of threads used to write the embeddings. Only has an effect for 1043 volumes and tiled images, which are written incrementally. 1044 norm_bounds: Volumes only (`ndim == 3`). Precomputed (lower, upper) percentile bounds (see 1045 `batched_inference._volume_normalization_bounds`), computed from `input_` when not 1046 given. Pass this to normalize `input_` against a larger volume's bounds instead of its 1047 own, e.g. when `input_` is only one tile/block of that volume - every tile/block must 1048 share the same bounds, never estimate its own from its own, smaller, biased crop. 1049 pbar_init: Optional callback to initialize external progress. 1050 pbar_update: Optional callback to update external progress. 1051 1052 Returns: 1053 An `ImageEmbeddings` resource. Call `close()` when finished or use it as a context manager. 1054 """ 1055 ndim = input_.ndim if ndim is None else ndim 1056 if tile_shape is not None: 1057 if halo is None: 1058 raise ValueError("The 'halo' parameter is required when 'tile_shape' is set.") 1059 if len(tile_shape) != ndim or len(halo) != ndim: 1060 raise ValueError( 1061 f"'tile_shape' and 'halo' must have {ndim} entries for {ndim}d data, got " 1062 f"{len(tile_shape)} and {len(halo)}." 1063 ) 1064 in_plane_tile_shape = tile_shape[-2:] if ndim == 3 and tile_shape is not None else tile_shape 1065 in_plane_halo = halo[-2:] if ndim == 3 and halo is not None else halo 1066 preprocessing = IMAGE_PREPROCESSING if ndim == 2 else VIDEO_PREPROCESSING 1067 if ndim == 2: 1068 configure_image_predictor(predictor) 1069 elif ndim == 3 and norm_bounds is None: 1070 from micro_sam.v2.batched_inference import _volume_normalization_bounds 1071 norm_bounds = _volume_normalization_bounds(input_) 1072 1073 is_streamed = ndim == 3 or tile_shape is not None 1074 temporary_path = None 1075 if lazy_loading and is_streamed and save_path is None: 1076 # Without a save path the zarr is held in memory, which defeats lazy loading. Back it by an 1077 # ephemeral on-disk store so the tiles / slices are streamed from disk instead. 1078 temporary_path = save_path = make_temp_embedding_path() 1079 1080 # Handle the embedding save_path. 1081 # We don't have a save path, open in memory zarr file to hold tiled embeddings. 1082 if save_path is None: 1083 f = _open_embeddings(None) 1084 1085 # We have a save path and it already exists. Embeddings will be loaded from it, 1086 # check that the saved embeddings in there match the parameters of the function call. 1087 elif os.path.exists(save_path): 1088 f = _open_embeddings(save_path, mode="a") 1089 if _check_saved_embeddings( 1090 input_, predictor, f, save_path, in_plane_tile_shape, in_plane_halo, preprocessing, norm_bounds, 1091 ): 1092 # Close the old handle before truncating the store. 1093 getattr(f, "file", f).close() 1094 f = _open_embeddings(save_path, mode="w") 1095 1096 # We have a save path and it does not exist yet. Create the zarr file to which the 1097 # embeddings will then be saved. 1098 else: 1099 f = _open_embeddings(save_path, mode="a") 1100 1101 # Persist normalization metadata before any features, so a partial cache is validated the same way. 1102 if save_path is not None: 1103 f.attrs["normalization"] = preprocessing 1104 if ndim == 3: 1105 f.attrs["normalization_bounds_digest"] = _normalization_bounds_digest(norm_bounds) 1106 1107 from micro_sam.util import handle_pbar 1108 from micro_sam.v2.batched_inference import _compute_3d, _compute_tiled_2d, _compute_tiled_3d 1109 1110 _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update) 1111 1112 resource = ImageEmbeddings({}, store=f, temporary_path=temporary_path, path=save_path) 1113 if ndim == 2 and tile_shape is None: 1114 embeddings = _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update) 1115 elif ndim == 2 and tile_shape is not None: 1116 embeddings = _compute_tiled_2d( 1117 input_, predictor, in_plane_tile_shape, in_plane_halo, f, save_path, pbar_init, pbar_update, 1118 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1119 num_write_workers=num_write_workers, 1120 ) 1121 elif ndim == 3 and tile_shape is None: 1122 embeddings = _compute_3d( 1123 input_, predictor, f, save_path, lazy_loading, pbar_init, pbar_update, 1124 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1125 num_write_workers=num_write_workers, norm_bounds=norm_bounds, 1126 ) 1127 elif ndim == 3 and tile_shape is not None: 1128 embeddings = _compute_tiled_3d( 1129 input_, predictor, in_plane_tile_shape, in_plane_halo, f, save_path, pbar_init, pbar_update, 1130 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1131 num_write_workers=num_write_workers, norm_bounds=norm_bounds, 1132 ) 1133 else: 1134 raise ValueError(f"Invalid dimensionality {input_.ndim}, expect 2 or 3 dim data.") 1135 1136 pbar_close() 1137 uses_store = tile_shape is not None or (ndim == 3 and lazy_loading) 1138 if not uses_store: 1139 resource.close() 1140 resource.update(embeddings) 1141 return resource 1142 1143 1144def _shared_pos_enc(level): 1145 """Read the positional encoding shared by every slice. Unlike 'features' and 'fpn', it is stored once. 1146 1147 Args: 1148 level: One stored positional-encoding level, shaped (1, 1, C, H, W). 1149 1150 Returns: 1151 The encoding for any slice, shaped (1, C, H, W). 1152 """ 1153 return level[0] 1154 1155 1156def _backbone_fpn(fpn_levels, features): 1157 """Rebuild the encoder's FPN levels, whose last one is stored as 'features' rather than twice. 1158 1159 Args: 1160 fpn_levels: The stored FPN levels for one slice, all but the last. 1161 features: That slice's 'features', which is the missing last level. 1162 1163 Returns: 1164 The full list of FPN levels, in the order the encoder produced them. 1165 """ 1166 return list(fpn_levels) + [features] 1167 1168 1169def _to_device_tensor(data, device): 1170 """Convert embedding data (numpy array or torch tensor on any device) to a float tensor. 1171 1172 Freshly computed embeddings may still be tensors on MPS/CUDA, which 'np.asarray' cannot 1173 convert; move those to the target device directly instead of via numpy. 1174 1175 Args: 1176 data: The embedding data, either a numpy array or a torch tensor on any device. 1177 device: The target device for the returned tensor. 1178 1179 Returns: 1180 The data as a float tensor on the given device. 1181 """ 1182 if torch.is_tensor(data): 1183 return data.detach().to(device).float() 1184 return torch.as_tensor(np.asarray(data), device=device).float() 1185 1186 1187def set_precomputed(predictor, image_embeddings, i: Optional[int] = None, tile_id: Optional[int] = None): 1188 """Set precomputed image embeddings on a SAM2 image predictor. 1189 1190 Only 2d embeddings are set this way. A volume's embeddings are not: the video predictor reads 1191 them per frame while it tracks, see `CustomVideoPredictor.init_state`. 1192 1193 Args: 1194 predictor: The SAM2 image predictor to set the embeddings on. 1195 image_embeddings: The precomputed embeddings, as returned by `precompute_image_embeddings`. 1196 i: The slice index, which 2d embeddings do not have. Passing one raises, so that a volumetric 1197 call routed here by mistake fails instead of segmenting the wrong thing. 1198 tile_id: The tile to set, for tiled embeddings. That tile's features are read from the store 1199 and set as if they were those of a whole image. 1200 1201 Returns: 1202 The predictor, with the embeddings set on it. 1203 """ 1204 if tile_id is not None: 1205 tile_features = image_embeddings["features"][str(tile_id)] 1206 # The SAM2 image predictor also needs the high-resolution features (used by the decoder), 1207 # which are stored per tile under 'high_res_feats/{tile_id}/{level}'. 1208 high_res_feats = _load_list_datasets(image_embeddings["high_res_feats"], str(tile_id), lazy_loading=False) 1209 tile_image_embeddings = { 1210 "features": tile_features, 1211 "high_res_feats": high_res_feats, 1212 "input_size": tile_features.attrs["input_size"], 1213 "original_size": tile_features.attrs["original_size"], 1214 } 1215 return set_precomputed(predictor, tile_image_embeddings, i=i) 1216 1217 try: 1218 device = predictor.device() # Works for video predictor. 1219 except TypeError: 1220 device = predictor.device # Otherwise, for image predictor. 1221 1222 features = image_embeddings["features"] 1223 if features.ndim != 4: 1224 raise ValueError( 1225 f"Expected 2d embeddings, whose features have 4 dimensions, got {features.ndim}. The " 1226 "embeddings of a volume are read by the video predictor's 'init_state' instead." 1227 ) 1228 if i is not None: 1229 raise ValueError("The data is 2D so an index is not needed.") 1230 1231 # Convert to tensors on the predictor device, as 'predictor.set_image' would for the decoder. 1232 image_embed = _to_device_tensor(features, device) 1233 high_res_feats = [_to_device_tensor(feat, device) for feat in image_embeddings["high_res_feats"]] 1234 predictor._features = {"image_embed": image_embed, "high_res_feats": high_res_feats} 1235 predictor._is_image_set = True 1236 predictor._orig_hw = image_embeddings["original_size"] 1237 return predictor
40def autocast_dtype(device: Device = None) -> Optional[torch.dtype]: 41 """The dtype SAM2 and UniSAM2 inference runs in on a device. 42 43 Args: 44 device: The device the forward pass runs on. Defaults to the best available one. 45 46 Returns: 47 The half precision dtype the device runs natively, or None where inference stays in fp32. 48 """ 49 device = _precision_device(device) 50 if device.type != "cuda" or not torch.cuda.is_available(): 51 return None 52 capability = torch.cuda.get_device_capability(device) 53 if capability >= BF16_MIN_CAPABILITY: 54 return torch.bfloat16 55 if capability >= FP16_MIN_CAPABILITY: 56 return torch.float16 57 return None
The dtype SAM2 and UniSAM2 inference runs in on a device.
Arguments:
- device: The device the forward pass runs on. Defaults to the best available one.
Returns:
The half precision dtype the device runs natively, or None where inference stays in fp32.
60def autocast(device: Device = None): 61 """The autocast context inference runs in on a device. 62 63 Args: 64 device: The device the forward pass runs on. Defaults to the best available one. 65 66 Returns: 67 The autocast context, or a null context for fp32. 68 """ 69 device = _precision_device(device) 70 dtype = autocast_dtype(device) 71 if dtype is None: 72 return contextlib.nullcontext() 73 return torch.autocast(device_type=device.type, dtype=dtype)
The autocast context inference runs in on a device.
Arguments:
- device: The device the forward pass runs on. Defaults to the best available one.
Returns:
The autocast context, or a null context for fp32.
76def precision_name(device: Device = None) -> str: 77 """The precision name of a device, for the embedding cache signature. 78 79 Args: 80 device: The device the forward pass runs on. 81 82 Returns: 83 One of 'bf16', 'fp16' or 'fp32'. 84 """ 85 return {torch.bfloat16: "bf16", torch.float16: "fp16", None: "fp32"}[autocast_dtype(device)]
The precision name of a device, for the embedding cache signature.
Arguments:
- device: The device the forward pass runs on.
Returns:
One of 'bf16', 'fp16' or 'fp32'.
88def to_float32(value: Any) -> Any: 89 """Cast the floating point tensors of a nested structure to fp32. 90 91 Autocast returns half precision, but the embedding cache is fp32 and numpy has no bfloat16. 92 93 Args: 94 value: A tensor, or a dict, list or tuple containing tensors. 95 96 Returns: 97 The same structure with its floating point tensors in fp32. 98 """ 99 if isinstance(value, torch.Tensor): 100 return value.float() if value.is_floating_point() else value 101 if isinstance(value, dict): 102 return {key: to_float32(item) for key, item in value.items()} 103 if isinstance(value, (list, tuple)): 104 return type(value)(to_float32(item) for item in value) 105 return value
Cast the floating point tensors of a nested structure to fp32.
Autocast returns half precision, but the embedding cache is fp32 and numpy has no bfloat16.
Arguments:
- value: A tensor, or a dict, list or tuple containing tensors.
Returns:
The same structure with its floating point tensors in fp32.
108def encode_image(predictor, image: np.ndarray) -> None: 109 """Run the image encoder in the device precision, keeping the cached features in fp32. 110 111 Args: 112 predictor: The SAM2 image predictor. 113 image: The image to encode. 114 """ 115 with autocast(predictor.device): 116 predictor.set_image(image) 117 predictor._features = to_float32(predictor._features)
Run the image encoder in the device precision, keeping the cached features in fp32.
Arguments:
- predictor: The SAM2 image predictor.
- image: The image to encode.
120class ImageEmbeddings(dict): 121 """Embedding result with explicit lifetime management for its backing store.""" 122 123 def __init__(self, embeddings, store=None, temporary_path=None, path=None): 124 super().__init__(embeddings) 125 self._store = store 126 self._temporary_path = temporary_path 127 self._path = path 128 self._closed = False 129 130 @property 131 def closed(self): 132 """Whether this embedding resource is closed.""" 133 return self._closed 134 135 @property 136 def temporary_path(self): 137 """The owned ephemeral path, or None for memory-backed or persistent embeddings.""" 138 return self._temporary_path 139 140 @property 141 def path(self): 142 """The store these embeddings are backed by, or None when they live in memory. 143 144 A path is what makes them readable from another process. 145 """ 146 return self._path 147 148 def close(self): 149 """Close the backing store and remove an owned ephemeral path.""" 150 if self._closed: 151 return 152 self._closed = True 153 try: 154 store = getattr(self._store, "file", self._store) 155 close = getattr(store, "close", None) 156 if close is not None: 157 close() 158 finally: 159 self._store = None 160 if self._temporary_path is not None: 161 shutil.rmtree(self._temporary_path, ignore_errors=True) 162 self._temporary_path = None 163 164 def __enter__(self): 165 return self 166 167 def __exit__(self, exc_type, exc_value, traceback): 168 self.close() 169 170 def __del__(self): 171 self.close()
Embedding result with explicit lifetime management for its backing store.
130 @property 131 def closed(self): 132 """Whether this embedding resource is closed.""" 133 return self._closed
Whether this embedding resource is closed.
135 @property 136 def temporary_path(self): 137 """The owned ephemeral path, or None for memory-backed or persistent embeddings.""" 138 return self._temporary_path
The owned ephemeral path, or None for memory-backed or persistent embeddings.
140 @property 141 def path(self): 142 """The store these embeddings are backed by, or None when they live in memory. 143 144 A path is what makes them readable from another process. 145 """ 146 return self._path
The store these embeddings are backed by, or None when they live in memory.
A path is what makes them readable from another process.
148 def close(self): 149 """Close the backing store and remove an owned ephemeral path.""" 150 if self._closed: 151 return 152 self._closed = True 153 try: 154 store = getattr(self._store, "file", self._store) 155 close = getattr(store, "close", None) 156 if close is not None: 157 close() 158 finally: 159 self._store = None 160 if self._temporary_path is not None: 161 shutil.rmtree(self._temporary_path, ignore_errors=True) 162 self._temporary_path = None
Close the backing store and remove an owned ephemeral path.
255def parameter_family(model_type): 256 """The family whose default parameters a model uses, e.g. 'em_mito' for 'hvit_s_em_mito'. 257 258 A backbone or a cells model, e.g. 'hvit_t' or 'hvit_t_cells', uses the 'cells' defaults. 259 """ 260 return str(model_type)[7:] or "cells"
The family whose default parameters a model uses, e.g. 'em_mito' for 'hvit_s_em_mito'.
A backbone or a cells model, e.g. 'hvit_t' or 'hvit_t_cells', uses the 'cells' defaults.
271def recommend_batch_size(model_type, device, n_jobs=None): 272 """Look up the encoder batch size for a model on a device. 273 274 Args: 275 model_type: The model name, e.g. 'hvit_t' or 'hvit_t_cells'. Unknown names are treated as the 276 most memory-hungry backbone. 277 device: The device the encoder runs on. Non-CUDA devices always get a batch size of one, as 278 does a device with less free VRAM than the smallest tabulated band. 279 n_jobs: The total number of tiles / slices, to avoid a batch larger than the work. 280 281 Returns: 282 The batch size to use, at least one. 283 """ 284 free_gib = _free_vram_gib(device) 285 if free_gib is None: 286 return 1 287 288 band = _band_for(free_gib) 289 if band is None: 290 # The smallest entry is calibrated for the smallest band, not below it, so a device that 291 # reaches no band stays at one instead of relying on the OOM backoff to recover. 292 return 1 293 294 batch_size = VRAM_BATCH_SIZES[band][_backbone_of(model_type)] 295 if n_jobs is not None: 296 batch_size = min(batch_size, max(1, int(n_jobs))) 297 return int(batch_size)
Look up the encoder batch size for a model on a device.
Arguments:
- model_type: The model name, e.g. 'hvit_t' or 'hvit_t_cells'. Unknown names are treated as the most memory-hungry backbone.
- device: The device the encoder runs on. Non-CUDA devices always get a batch size of one, as does a device with less free VRAM than the smallest tabulated band.
- n_jobs: The total number of tiles / slices, to avoid a batch larger than the work.
Returns:
The batch size to use, at least one.
300def needs_default_tiling(shape): 301 """Whether to enable default in-plane tiling for a given image shape. 302 303 Args: 304 shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z, y, x); 305 for 3d only the in-plane (y, x) axes are considered, not the leading z axis. 306 307 Returns: 308 Whether tiling should be enabled by default. 309 """ 310 if len(shape) == 2: 311 return shape[0] > DEFAULT_TILING_THRESHOLD or shape[1] > DEFAULT_TILING_THRESHOLD 312 elif len(shape) == 3: 313 return shape[1] > DEFAULT_TILING_THRESHOLD or shape[2] > DEFAULT_TILING_THRESHOLD 314 return False
Whether to enable default in-plane tiling for a given image shape.
Arguments:
- shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z, y, x); for 3d only the in-plane (y, x) axes are considered, not the leading z axis.
Returns:
Whether tiling should be enabled by default.
317def tiling_is_turned_off(value): 318 """Whether a tile shape or halo explicitly asks for no tiling, i.e. is all zeros. 319 320 Every micro-sam entry point tiles by default, so an all-zero tile shape (and halo) is how a 321 caller says "run this in one piece" - the CLI also spells it `--tile_shape none --overlap none`. 322 323 Args: 324 value: A tile shape or halo, which may be None. 325 326 Returns: 327 Whether it turns tiling off. False for None, which means 'not set'. 328 """ 329 return value is not None and len(value) > 0 and all(int(entry) == 0 for entry in value)
Whether a tile shape or halo explicitly asks for no tiling, i.e. is all zeros.
Every micro-sam entry point tiles by default, so an all-zero tile shape (and halo) is how a
caller says "run this in one piece" - the CLI also spells it --tile_shape none --overlap none.
Arguments:
- value: A tile shape or halo, which may be None.
Returns:
Whether it turns tiling off. False for None, which means 'not set'.
332def resolve_default_tiling(shape, tile_shape, halo, embedding_path=None): 333 """Resolve the tiling settings for an entry point from the image shape and the embedding cache. 334 335 This is the single source of truth for the tiling defaults of all entry points: the annotation 336 tools (interactive segmentation, tracking, pixel and object classification, and their batch 337 variants) and the headless inference front-ends. The annotation tools compute their embeddings 338 before the GUI is built, so they have to resolve the same settings the embedding widget would 339 show for the image (see `EmbeddingWidget._apply_default_tiling_for_shape`). 340 341 Settings the caller passes always win. Otherwise the tiling of already cached embeddings is 342 adopted, so pointing a tool at an existing embedding path reuses it instead of recomputing it 343 just because the defaults have changed or another tool used different settings. Embeddings that 344 are cached without tiling are the exception: they are recomputed with the default tiling rather 345 than kept, since running untiled is what the default guards against. 346 347 Automatic tiling kicks in above the in-plane size cutoff (`DEFAULT_TILING_THRESHOLD`), the same 348 way for every entry point. Below it, and whenever the caller turns tiling off with an all-zero 349 tile shape, the image is passed to the model in one piece. 350 351 Args: 352 shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z / t, y, x). 353 tile_shape: The requested in-plane tile shape. If None, the tile shape of the cached 354 embeddings is used, else the default tile shape for images exceeding the in-plane size 355 cutoff. All zeros turns tiling off. 356 halo: The requested in-plane tile overlap. If None, the overlap of the cached embeddings is 357 used, or the default overlap, since tiling without an overlap cuts objects at the tile 358 borders. 359 embedding_path: Optional filepath of the cached embeddings. 360 361 Returns: 362 The resolved tile shape, None if the embeddings are computed without tiling. 363 The resolved halo, None if the embeddings are computed without tiling. 364 365 Raises: 366 ValueError: If tiling is turned off with an all-zero tile shape but a real halo is given. 367 """ 368 from micro_sam.util import read_cached_tiling 369 370 if tiling_is_turned_off(tile_shape): 371 if halo is not None and not tiling_is_turned_off(halo): 372 raise ValueError( 373 f"Tiling is turned off by an all-zero 'tile_shape', so the halo {tuple(halo)} cannot " 374 "be used. Set both to zero, or give a real tile shape." 375 ) 376 return None, None 377 378 cached = read_cached_tiling(embedding_path) if tile_shape is None else None 379 if cached is not None and cached[0] is not None: 380 tile_shape = cached[0] 381 if halo is None: 382 halo = cached[1] 383 elif tile_shape is None and needs_default_tiling(shape): 384 tile_shape = DEFAULT_TILE_SHAPE 385 386 # An all-zero halo is kept as given: with a real tile shape it means 'tile without an overlap'. 387 if tile_shape is not None and halo is None: 388 halo = DEFAULT_HALO 389 return tile_shape, halo
Resolve the tiling settings for an entry point from the image shape and the embedding cache.
This is the single source of truth for the tiling defaults of all entry points: the annotation
tools (interactive segmentation, tracking, pixel and object classification, and their batch
variants) and the headless inference front-ends. The annotation tools compute their embeddings
before the GUI is built, so they have to resolve the same settings the embedding widget would
show for the image (see EmbeddingWidget._apply_default_tiling_for_shape).
Settings the caller passes always win. Otherwise the tiling of already cached embeddings is adopted, so pointing a tool at an existing embedding path reuses it instead of recomputing it just because the defaults have changed or another tool used different settings. Embeddings that are cached without tiling are the exception: they are recomputed with the default tiling rather than kept, since running untiled is what the default guards against.
Automatic tiling kicks in above the in-plane size cutoff (DEFAULT_TILING_THRESHOLD), the same
way for every entry point. Below it, and whenever the caller turns tiling off with an all-zero
tile shape, the image is passed to the model in one piece.
Arguments:
- shape: The image shape without any channel axis. Either 2d (y, x) or 3d (z / t, y, x).
- tile_shape: The requested in-plane tile shape. If None, the tile shape of the cached embeddings is used, else the default tile shape for images exceeding the in-plane size cutoff. All zeros turns tiling off.
- halo: The requested in-plane tile overlap. If None, the overlap of the cached embeddings is used, or the default overlap, since tiling without an overlap cuts objects at the tile borders.
- embedding_path: Optional filepath of the cached embeddings.
Returns:
The resolved tile shape, None if the embeddings are computed without tiling. The resolved halo, None if the embeddings are computed without tiling.
Raises:
- ValueError: If tiling is turned off with an all-zero tile shape but a real halo is given.
451def models(): 452 """Return the finetuned SAM2 models registry. 453 454 Mirrors `micro_sam.v1.util.models`: finetuned SAM2 checkpoints and their UniSAM2 decoders are 455 registered with their xxh128 hashes and download URLs and fetched via pooch. The base SAM2 456 backbones (hvit_t/s/b/l) are downloaded separately, see `_get_checkpoint`. 457 458 Returns: 459 The pooch registry for the finetuned SAM2 models. 460 """ 461 registry = pooch.create( 462 path=get_model_cache_directory(), 463 base_url="", 464 registry=FINETUNED_HASHES, 465 urls=FINETUNED_URLS, 466 ) 467 return registry
Return the finetuned SAM2 models registry.
Mirrors micro_sam.v1.util.models: finetuned SAM2 checkpoints and their UniSAM2 decoders are
registered with their xxh128 hashes and download URLs and fetched via pooch. The base SAM2
backbones (hvit_t/s/b/l) are downloaded separately, see _get_checkpoint.
Returns:
The pooch registry for the finetuned SAM2 models.
470def get_model_names(): 471 """Return the names of the finetuned SAM2 models available in the download console.""" 472 return list(FINETUNED_MODELS)
Return the names of the finetuned SAM2 models available in the download console.
475def has_registered_decoder(model_type): 476 """Whether a finetuned SAM2 model has a registered UniSAM2 decoder (for automatic segmentation). 477 478 A cheap registry lookup (no download), used e.g. to decide the default automatic-segmentation mode 479 before the model / decoder has actually been loaded. 480 481 Args: 482 model_type: The SAM2 model name, e.g. 'hvit_t_cells'. 483 484 Returns: 485 Whether a '<model_type>_decoder' is registered. 486 """ 487 return f"{model_type}_decoder" in FINETUNED_HASHES
Whether a finetuned SAM2 model has a registered UniSAM2 decoder (for automatic segmentation).
A cheap registry lookup (no download), used e.g. to decide the default automatic-segmentation mode before the model / decoder has actually been loaded.
Arguments:
- model_type: The SAM2 model name, e.g. 'hvit_t_cells'.
Returns:
Whether a '
_decoder' is registered.
566def strip_wrapper_prefixes(state: dict) -> dict: 567 """Remove the key prefixes that DDP ('module.') and torch.compile ('_orig_mod.') add to model weights. 568 569 Args: 570 state: The model weights. 571 572 Returns: 573 The model weights without these prefixes. 574 """ 575 prefixes = ("module.", "_orig_mod.") 576 577 def _strip(key): 578 while key.startswith(prefixes): 579 key = key[len(next(p for p in prefixes if key.startswith(p))):] 580 return key 581 582 return {_strip(key): value for key, value in state.items()}
Remove the key prefixes that DDP ('module.') and torch.compile ('_orig_mod.') add to model weights.
Arguments:
- state: The model weights.
Returns:
The model weights without these prefixes.
620def detect_sam2_backbone(model_state: dict) -> str: 621 """Detect the SAM2 backbone of model weights from the shape of the Hiera trunk. 622 623 Args: 624 model_state: The weights of a SAM2 model, with or without PEFT. 625 626 Returns: 627 The backbone name, for example 'hvit_b'. 628 629 Raises: 630 ValueError: If the trunk matches no known backbone. 631 """ 632 embed_dim = int(model_state["image_encoder.trunk.patch_embed.proj.weight"].shape[0]) 633 prefix = "image_encoder.trunk.blocks." 634 n_blocks = 1 + max(int(k[len(prefix):].split(".")[0]) for k in model_state if k.startswith(prefix)) 635 backbone = BACKBONE_SIGNATURES.get((embed_dim, n_blocks)) 636 if backbone is None: 637 raise ValueError(f"No SAM2 backbone has {n_blocks} blocks with embedding dimension {embed_dim}.") 638 return backbone
Detect the SAM2 backbone of model weights from the shape of the Hiera trunk.
Arguments:
- model_state: The weights of a SAM2 model, with or without PEFT.
Returns:
The backbone name, for example 'hvit_b'.
Raises:
- ValueError: If the trunk matches no known backbone.
672def get_sam2_model( 673 model_type: str = DEFAULT_BASE_MODEL, 674 device: Optional[Union[torch.device, str]] = None, 675 checkpoint_path: Optional[Union[os.PathLike, str]] = None, 676 input_type: Literal["images", "videos"] = "images", 677 peft_kwargs: Optional[dict] = None, 678): 679 """Get the Segment Anything 2 (SAM2) model for interactive segmentation of images and videos. 680 681 Args: 682 model_type: The choice of size for the vision transformer, eg. `hvit_t`. The default is `hvit_t` model. 683 With `checkpoint_path`, the backbone of the checkpoint replaces the backbone of this name. 684 device: The pytorch device. 685 checkpoint_path: Filepath to the model weights. The function then does not download the weights of 686 `model_type`. 687 input_type: Whether the inputs are images or videos. 688 peft_kwargs: The arguments for `PEFT_Sam2`. The function uses the arguments in the checkpoint by default. 689 690 Returns: 691 The SAM2 model. 692 """ 693 device = _get_device(device) 694 695 if input_type not in ("images", "videos"): 696 raise ValueError(f"'{input_type}' is not a valid input type.") 697 698 model_hash = None 699 if checkpoint_path is None: 700 checkpoint_path = _get_registry_checkpoint(model_type) 701 else: 702 # The cached embeddings of other weights with the same model name must not be reused. 703 from micro_sam.util import _compute_hash 704 model_hash = _compute_hash(checkpoint_path) 705 706 state, model_state, encoder_only = _read_sam2_checkpoint(checkpoint_path) 707 backbone = detect_sam2_backbone(model_state) 708 if backbone != model_type[:6]: 709 print(f"The checkpoint holds a '{backbone}' model, so it is used instead of '{model_type[:6]}'.") 710 model_type = backbone + model_type[6:] 711 if encoder_only: 712 # The prompt encoder, mask decoder and memory come from the registry, the image encoder from the checkpoint. 713 base_type = model_type if model_type in FINETUNED_MODELS else backbone 714 _, base_state, _ = _read_sam2_checkpoint(_get_registry_checkpoint(base_type)) 715 model_state = {**{k: v for k, v in base_state.items() if not k.startswith("image_encoder.")}, **model_state} 716 717 if not peft_kwargs and isinstance(state, dict) and state.get("peft_kwargs") is not None: 718 from micro_sam.v2.models.peft_sam2 import PEFT_MODULES 719 from micro_sam.models.peft import deserialize_peft_kwargs 720 peft_kwargs = deserialize_peft_kwargs(state["peft_kwargs"], PEFT_MODULES) 721 if peft_kwargs: 722 peft_kwargs = {k: v for k, v in peft_kwargs.items() if k != "quantize"} 723 724 model = _load_sam2_from_state(CFG_PATHS[backbone], input_type, model_state, device, peft_kwargs) 725 if peft_kwargs: 726 from micro_sam.models.peft import serialize_peft_kwargs 727 # Training reads the PEFT settings from here, so that it continues with the same PEFT layers. 728 model.peft_config = serialize_peft_kwargs(peft_kwargs) 729 730 # Both predictor wrappers and direct model use need this metadata for embedding signatures. 731 model.model_type = model_type 732 model.model_name = model_type # TODO: What is this exactly? 733 model._hash = model_hash 734 735 return model
Get the Segment Anything 2 (SAM2) model for interactive segmentation of images and videos.
Arguments:
- model_type: The choice of size for the vision transformer, eg.
hvit_t. The default ishvit_tmodel. Withcheckpoint_path, the backbone of the checkpoint replaces the backbone of this name. - device: The pytorch device.
- checkpoint_path: Filepath to the model weights. The function then does not download the weights of
model_type. - input_type: Whether the inputs are images or videos.
- peft_kwargs: The arguments for
PEFT_Sam2. The function uses the arguments in the checkpoint by default.
Returns:
The SAM2 model.
738def export_custom_qlora_sam2_model( 739 checkpoint_path: Optional[Union[str, os.PathLike]], 740 finetuned_path: Union[str, os.PathLike], 741 model_type: str, 742 save_path: Union[str, os.PathLike], 743) -> None: 744 """Export a SAM2 model from QLoRA to a full-precision LoRA checkpoint. 745 746 The export keeps the trained parameters. It gets the frozen encoder parameters from the base model. 747 748 Args: 749 checkpoint_path: The path to the base checkpoint. Use None to download the default checkpoint. 750 finetuned_path: The path to the QLoRA checkpoint. 751 model_type: The SAM2 model type, for example, 'hvit_t'. 752 save_path: The path for the exported checkpoint. 753 """ 754 sam = get_sam2_model(model_type=model_type, checkpoint_path=checkpoint_path, device="cpu") 755 756 from ..util import load_checkpoint 757 758 ft_state = load_checkpoint(finetuned_path) 759 if isinstance(ft_state, dict) and "model_state" in ft_state: 760 ft_model_state = ft_state["model_state"] 761 elif isinstance(ft_state, dict) and "model" in ft_state: 762 ft_model_state = ft_state["model"] 763 else: 764 ft_model_state = ft_state 765 ft_model_state = strip_wrapper_prefixes(ft_model_state) 766 767 updated_model_state = {k: v for k, v in ft_model_state.items() if not k.startswith("image_encoder.")} 768 modified_attn_layers = set() 769 modified_mlp_layers = set() 770 for k, v in ft_model_state.items(): 771 if not k.startswith("image_encoder."): 772 continue 773 layer_id = int(k.split("blocks.")[1].split(".")[0]) if "blocks." in k else None 774 if "qkv.w_a_linear" in k or "qkv.w_b_linear" in k: 775 modified_attn_layers.add(layer_id) 776 updated_model_state[k] = v 777 if "mlp.w_a_linear" in k or "mlp.w_b_linear" in k: 778 modified_mlp_layers.add(layer_id) 779 updated_model_state[k] = v 780 781 for k, v in sam.state_dict().items(): 782 if not k.startswith("image_encoder."): 783 continue 784 layer_id = int(k.split("blocks.")[1].split(".")[0]) if "blocks." in k else None 785 if "attn.qkv." in k: 786 if layer_id in modified_attn_layers: 787 k = k.replace("qkv", "qkv.qkv_proj") 788 elif "mlp" in k and "image_encoder" in k: 789 if layer_id in modified_mlp_layers: 790 k = k.replace("mlp.", "mlp.mlp_layer.") 791 updated_model_state[k] = v 792 793 if isinstance(ft_state, dict) and "model_state" in ft_state: 794 ft_state["model_state"] = updated_model_state 795 out_state = ft_state 796 elif isinstance(ft_state, dict) and "model" in ft_state: 797 ft_state["model"] = updated_model_state 798 out_state = ft_state 799 else: 800 out_state = {"model": updated_model_state, "model_type": model_type} 801 802 torch.save(out_state, save_path)
Export a SAM2 model from QLoRA to a full-precision LoRA checkpoint.
The export keeps the trained parameters. It gets the frozen encoder parameters from the base model.
Arguments:
- checkpoint_path: The path to the base checkpoint. Use None to download the default checkpoint.
- finetuned_path: The path to the QLoRA checkpoint.
- model_type: The SAM2 model type, for example, 'hvit_t'.
- save_path: The path for the exported checkpoint.
813def configure_image_predictor(predictor): 814 """Configure a SAM2 image predictor to always use resize-longest.""" 815 from micro_sam.v2.transforms.resize import ResizeLongestSideTransforms 816 817 old = predictor._transforms 818 predictor._transforms = ResizeLongestSideTransforms( 819 resolution=predictor.model.image_size, 820 mask_threshold=predictor.mask_threshold, 821 max_hole_area=getattr(old, "max_hole_area", 0.0), 822 max_sprinkle_area=getattr(old, "max_sprinkle_area", 0.0), 823 ) 824 return predictor
Configure a SAM2 image predictor to always use resize-longest.
827def get_sam2_image_predictor(model, **kwargs): 828 """Build a SAM2 image predictor with resize-longest preprocessing and the device precision. 829 830 The predictor takes the 'model_type', 'model_name' and '_hash' of a model from `get_sam2_model`, 831 which the embedding cache writes to its signature and checks. 832 """ 833 predictor = configure_image_predictor(_PrecisionImagePredictor(model, **kwargs)) 834 for name in ("model_type", "model_name", "_hash"): 835 if hasattr(model, name): 836 setattr(predictor, name, getattr(model, name)) 837 return predictor
Build a SAM2 image predictor with resize-longest preprocessing and the device precision.
The predictor takes the 'model_type', 'model_name' and '_hash' of a model from get_sam2_model,
which the embedding cache writes to its signature and checks.
1004def precompute_image_embeddings( 1005 predictor, 1006 input_: np.ndarray, 1007 save_path: Optional[Union[str, os.PathLike]] = None, 1008 lazy_loading: bool = False, 1009 ndim: Optional[int] = None, 1010 tile_shape: Optional[Tuple[int, ...]] = None, 1011 halo: Optional[Tuple[int, ...]] = None, 1012 verbose: bool = True, 1013 batch_size: Optional[int] = None, 1014 devices: Devices = None, 1015 num_prefetch_workers: int = 4, 1016 num_write_workers: int = 2, 1017 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 1018 pbar_init: Optional[callable] = None, 1019 pbar_update: Optional[callable] = None, 1020): 1021 """Compute the image embeddings (output of the encoder) for the input. 1022 1023 If 'save_path' is given the embeddings will be loaded/saved in a zarr container. 1024 1025 Args: 1026 predictor: The SAM2 image or video predictor. 1027 input_: The input image or volume. 1028 save_path: Optional zarr path for persistent embedding storage. 1029 lazy_loading: Stream embeddings from zarr instead of materializing them in memory. Without 1030 `save_path`, the returned `ImageEmbeddings` owns an ephemeral on-disk store; use it as a 1031 context manager or call `close()` when finished. 1032 ndim: The number of spatial dimensions. By default this is inferred from the input. 1033 tile_shape: Optional tile shape. Pass (y, x) for 2d data or (z, y, x) for 3d data. The 1034 encoder uses only the in-plane entries for 3d data. 1035 halo: Optional tile halo with the same axes as `tile_shape`. 1036 verbose: Whether to show progress. 1037 batch_size: The batch size used when running inference for multiple slices and / or tiles. 1038 By default it is looked up independently on each CUDA device from its free VRAM (see 1039 `recommend_batch_size`). Pass an integer to run every device at that batch size. 1040 devices: Device or devices used for embedding inference. If None and the predictor is on 1041 CUDA, all visible CUDA devices are used. 1042 num_prefetch_workers: Number of threads used to read and preprocess input jobs. 1043 num_write_workers: Number of threads used to write the embeddings. Only has an effect for 1044 volumes and tiled images, which are written incrementally. 1045 norm_bounds: Volumes only (`ndim == 3`). Precomputed (lower, upper) percentile bounds (see 1046 `batched_inference._volume_normalization_bounds`), computed from `input_` when not 1047 given. Pass this to normalize `input_` against a larger volume's bounds instead of its 1048 own, e.g. when `input_` is only one tile/block of that volume - every tile/block must 1049 share the same bounds, never estimate its own from its own, smaller, biased crop. 1050 pbar_init: Optional callback to initialize external progress. 1051 pbar_update: Optional callback to update external progress. 1052 1053 Returns: 1054 An `ImageEmbeddings` resource. Call `close()` when finished or use it as a context manager. 1055 """ 1056 ndim = input_.ndim if ndim is None else ndim 1057 if tile_shape is not None: 1058 if halo is None: 1059 raise ValueError("The 'halo' parameter is required when 'tile_shape' is set.") 1060 if len(tile_shape) != ndim or len(halo) != ndim: 1061 raise ValueError( 1062 f"'tile_shape' and 'halo' must have {ndim} entries for {ndim}d data, got " 1063 f"{len(tile_shape)} and {len(halo)}." 1064 ) 1065 in_plane_tile_shape = tile_shape[-2:] if ndim == 3 and tile_shape is not None else tile_shape 1066 in_plane_halo = halo[-2:] if ndim == 3 and halo is not None else halo 1067 preprocessing = IMAGE_PREPROCESSING if ndim == 2 else VIDEO_PREPROCESSING 1068 if ndim == 2: 1069 configure_image_predictor(predictor) 1070 elif ndim == 3 and norm_bounds is None: 1071 from micro_sam.v2.batched_inference import _volume_normalization_bounds 1072 norm_bounds = _volume_normalization_bounds(input_) 1073 1074 is_streamed = ndim == 3 or tile_shape is not None 1075 temporary_path = None 1076 if lazy_loading and is_streamed and save_path is None: 1077 # Without a save path the zarr is held in memory, which defeats lazy loading. Back it by an 1078 # ephemeral on-disk store so the tiles / slices are streamed from disk instead. 1079 temporary_path = save_path = make_temp_embedding_path() 1080 1081 # Handle the embedding save_path. 1082 # We don't have a save path, open in memory zarr file to hold tiled embeddings. 1083 if save_path is None: 1084 f = _open_embeddings(None) 1085 1086 # We have a save path and it already exists. Embeddings will be loaded from it, 1087 # check that the saved embeddings in there match the parameters of the function call. 1088 elif os.path.exists(save_path): 1089 f = _open_embeddings(save_path, mode="a") 1090 if _check_saved_embeddings( 1091 input_, predictor, f, save_path, in_plane_tile_shape, in_plane_halo, preprocessing, norm_bounds, 1092 ): 1093 # Close the old handle before truncating the store. 1094 getattr(f, "file", f).close() 1095 f = _open_embeddings(save_path, mode="w") 1096 1097 # We have a save path and it does not exist yet. Create the zarr file to which the 1098 # embeddings will then be saved. 1099 else: 1100 f = _open_embeddings(save_path, mode="a") 1101 1102 # Persist normalization metadata before any features, so a partial cache is validated the same way. 1103 if save_path is not None: 1104 f.attrs["normalization"] = preprocessing 1105 if ndim == 3: 1106 f.attrs["normalization_bounds_digest"] = _normalization_bounds_digest(norm_bounds) 1107 1108 from micro_sam.util import handle_pbar 1109 from micro_sam.v2.batched_inference import _compute_3d, _compute_tiled_2d, _compute_tiled_3d 1110 1111 _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update) 1112 1113 resource = ImageEmbeddings({}, store=f, temporary_path=temporary_path, path=save_path) 1114 if ndim == 2 and tile_shape is None: 1115 embeddings = _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update) 1116 elif ndim == 2 and tile_shape is not None: 1117 embeddings = _compute_tiled_2d( 1118 input_, predictor, in_plane_tile_shape, in_plane_halo, f, save_path, pbar_init, pbar_update, 1119 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1120 num_write_workers=num_write_workers, 1121 ) 1122 elif ndim == 3 and tile_shape is None: 1123 embeddings = _compute_3d( 1124 input_, predictor, f, save_path, lazy_loading, pbar_init, pbar_update, 1125 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1126 num_write_workers=num_write_workers, norm_bounds=norm_bounds, 1127 ) 1128 elif ndim == 3 and tile_shape is not None: 1129 embeddings = _compute_tiled_3d( 1130 input_, predictor, in_plane_tile_shape, in_plane_halo, f, save_path, pbar_init, pbar_update, 1131 batch_size=batch_size, devices=devices, num_prefetch_workers=num_prefetch_workers, 1132 num_write_workers=num_write_workers, norm_bounds=norm_bounds, 1133 ) 1134 else: 1135 raise ValueError(f"Invalid dimensionality {input_.ndim}, expect 2 or 3 dim data.") 1136 1137 pbar_close() 1138 uses_store = tile_shape is not None or (ndim == 3 and lazy_loading) 1139 if not uses_store: 1140 resource.close() 1141 resource.update(embeddings) 1142 return resource
Compute the image embeddings (output of the encoder) for the input.
If 'save_path' is given the embeddings will be loaded/saved in a zarr container.
Arguments:
- predictor: The SAM2 image or video predictor.
- input_: The input image or volume.
- save_path: Optional zarr path for persistent embedding storage.
- lazy_loading: Stream embeddings from zarr instead of materializing them in memory. Without
save_path, the returnedImageEmbeddingsowns an ephemeral on-disk store; use it as a context manager or callclose()when finished. - ndim: The number of spatial dimensions. By default this is inferred from the input.
- tile_shape: Optional tile shape. Pass (y, x) for 2d data or (z, y, x) for 3d data. The encoder uses only the in-plane entries for 3d data.
- halo: Optional tile halo with the same axes as
tile_shape. - verbose: Whether to show progress.
- batch_size: The batch size used when running inference for multiple slices and / or tiles.
By default it is looked up independently on each CUDA device from its free VRAM (see
recommend_batch_size). Pass an integer to run every device at that batch size. - devices: Device or devices used for embedding inference. If None and the predictor is on CUDA, all visible CUDA devices are used.
- num_prefetch_workers: Number of threads used to read and preprocess input jobs.
- num_write_workers: Number of threads used to write the embeddings. Only has an effect for volumes and tiled images, which are written incrementally.
- norm_bounds: Volumes only (
ndim == 3). Precomputed (lower, upper) percentile bounds (seebatched_inference._volume_normalization_bounds), computed frominput_when not given. Pass this to normalizeinput_against a larger volume's bounds instead of its own, e.g. wheninput_is only one tile/block of that volume - every tile/block must share the same bounds, never estimate its own from its own, smaller, biased crop. - pbar_init: Optional callback to initialize external progress.
- pbar_update: Optional callback to update external progress.
Returns:
An
ImageEmbeddingsresource. Callclose()when finished or use it as a context manager.
1188def set_precomputed(predictor, image_embeddings, i: Optional[int] = None, tile_id: Optional[int] = None): 1189 """Set precomputed image embeddings on a SAM2 image predictor. 1190 1191 Only 2d embeddings are set this way. A volume's embeddings are not: the video predictor reads 1192 them per frame while it tracks, see `CustomVideoPredictor.init_state`. 1193 1194 Args: 1195 predictor: The SAM2 image predictor to set the embeddings on. 1196 image_embeddings: The precomputed embeddings, as returned by `precompute_image_embeddings`. 1197 i: The slice index, which 2d embeddings do not have. Passing one raises, so that a volumetric 1198 call routed here by mistake fails instead of segmenting the wrong thing. 1199 tile_id: The tile to set, for tiled embeddings. That tile's features are read from the store 1200 and set as if they were those of a whole image. 1201 1202 Returns: 1203 The predictor, with the embeddings set on it. 1204 """ 1205 if tile_id is not None: 1206 tile_features = image_embeddings["features"][str(tile_id)] 1207 # The SAM2 image predictor also needs the high-resolution features (used by the decoder), 1208 # which are stored per tile under 'high_res_feats/{tile_id}/{level}'. 1209 high_res_feats = _load_list_datasets(image_embeddings["high_res_feats"], str(tile_id), lazy_loading=False) 1210 tile_image_embeddings = { 1211 "features": tile_features, 1212 "high_res_feats": high_res_feats, 1213 "input_size": tile_features.attrs["input_size"], 1214 "original_size": tile_features.attrs["original_size"], 1215 } 1216 return set_precomputed(predictor, tile_image_embeddings, i=i) 1217 1218 try: 1219 device = predictor.device() # Works for video predictor. 1220 except TypeError: 1221 device = predictor.device # Otherwise, for image predictor. 1222 1223 features = image_embeddings["features"] 1224 if features.ndim != 4: 1225 raise ValueError( 1226 f"Expected 2d embeddings, whose features have 4 dimensions, got {features.ndim}. The " 1227 "embeddings of a volume are read by the video predictor's 'init_state' instead." 1228 ) 1229 if i is not None: 1230 raise ValueError("The data is 2D so an index is not needed.") 1231 1232 # Convert to tensors on the predictor device, as 'predictor.set_image' would for the decoder. 1233 image_embed = _to_device_tensor(features, device) 1234 high_res_feats = [_to_device_tensor(feat, device) for feat in image_embeddings["high_res_feats"]] 1235 predictor._features = {"image_embed": image_embed, "high_res_feats": high_res_feats} 1236 predictor._is_image_set = True 1237 predictor._orig_hw = image_embeddings["original_size"] 1238 return predictor
Set precomputed image embeddings on a SAM2 image predictor.
Only 2d embeddings are set this way. A volume's embeddings are not: the video predictor reads
them per frame while it tracks, see CustomVideoPredictor.init_state.
Arguments:
- predictor: The SAM2 image predictor to set the embeddings on.
- image_embeddings: The precomputed embeddings, as returned by
precompute_image_embeddings. - i: The slice index, which 2d embeddings do not have. Passing one raises, so that a volumetric call routed here by mistake fails instead of segmenting the wrong thing.
- tile_id: The tile to set, for tiled embeddings. That tile's features are read from the store and set as if they were those of a whole image.
Returns:
The predictor, with the embeddings set on it.