micro_sam.v1.util
SAM1 (Segment Anything v1) model loading and embedding-computation utilities.
1"""SAM1 (Segment Anything v1) model loading and embedding-computation utilities. 2""" 3 4import os 5import pooch 6import warnings 7import multiprocessing as mp 8from concurrent import futures 9from collections import OrderedDict 10from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, Callable # noqa 11 12import numpy as np 13 14import torch 15 16from bioimage_cpp.utils import Blocking 17 18from . import models as custom_models # noqa 19from ..util import ( # noqa 20 ImageEmbeddings, SamPredictor, sam_model_registry, VIT_T_SUPPORT, 21 DEFAULT_SAM1_MODEL, SAM1_MODEL_TYPES, 22 get_device, _available_devices, _to_image, _load_checkpoint, _compute_hash, 23 _CustomUnpickler, get_cache_directory, get_model_cache_directory, 24 _create_dataset_with_data, _create_dataset_without_data, _open_embeddings, 25 _compute_data_signature, _get_embedding_signature, _write_embedding_signature, 26 handle_pbar, 27) 28 29 30def models(): 31 """Return the segmentation models registry. 32 33 We recreate the model registry every time this function is called, 34 so any user changes to the default micro-sam cache directory location 35 are respected. 36 """ 37 38 # We use xxhash to compute the hash of the models, see 39 # https://github.com/computational-cell-analytics/micro-sam/issues/283 40 # (It is now a dependency, so we don't provide the sha256 fallback anymore.) 41 # To generate the xxh128 hash: 42 # xxh128sum filename 43 encoder_registry = { 44 # The default segment anything models: 45 "vit_l": "xxh128:a82beb3c660661e3dd38d999cc860e9a", 46 "vit_h": "xxh128:97698fac30bd929c2e6d8d8cc15933c2", 47 "vit_b": "xxh128:6923c33df3637b6a922d7682bfc9a86b", 48 # The model with vit tiny backend fom https://github.com/ChaoningZhang/MobileSAM. 49 "vit_t": "xxh128:8eadbc88aeb9d8c7e0b4b60c3db48bd0", 50 # The current version of our models in the modelzoo. 51 # LM generalist models: 52 "vit_l_lm": "xxh128:017f20677997d628426dec80a8018f9d", 53 "vit_b_lm": "xxh128:fe9252a29f3f4ea53c15a06de471e186", 54 "vit_t_lm": "xxh128:72ec5074774761a6e5c05a08942f981e", 55 # EM models: 56 "vit_l_em_organelles": "xxh128:810b084b6e51acdbf760a993d8619f2d", 57 "vit_b_em_organelles": "xxh128:f3bf2ed83d691456bae2c3f9a05fb438", 58 "vit_t_em_organelles": "xxh128:253474720c497cce605e57c9b1d18fd9", 59 # Histopathology models: 60 "vit_b_histopathology": "xxh128:ffd1a2cd84570458b257bd95fdd8f974", 61 "vit_l_histopathology": "xxh128:b591833c89754271023e901281dee3f2", 62 "vit_h_histopathology": "xxh128:bd1856dafc156a43fb3aa705f1a6e92e", 63 # Medical Imaging models: 64 "vit_b_medical_imaging": "xxh128:40169f1e3c03a4b67bff58249c176d92", 65 } 66 # Additional decoders for instance segmentation. 67 decoder_registry = { 68 # LM generalist models: 69 "vit_l_lm_decoder": "xxh128:2faeafa03819dfe03e7c46a44aaac64a", 70 "vit_b_lm_decoder": "xxh128:708b15ac620e235f90bb38612c4929ba", 71 "vit_t_lm_decoder": "xxh128:3e914a5f397b0312cdd36813031f8823", 72 # EM models: 73 "vit_l_em_organelles_decoder": "xxh128:334877640bfdaaabce533e3252a17294", 74 "vit_b_em_organelles_decoder": "xxh128:bb6398956a6b0132c26b631c14f95ce2", 75 "vit_t_em_organelles_decoder": "xxh128:8f897c7bb93174a4d1638827c4dd6f44", 76 # Histopathology models: 77 "vit_b_histopathology_decoder": "xxh128:6a66194dcb6e36199cbee2214ecf7213", 78 "vit_l_histopathology_decoder": "xxh128:46aab7765d4400e039772d5a50b55c04", 79 "vit_h_histopathology_decoder": "xxh128:3ed9f87e46ad5e16935bd8d722c8dc47", 80 # Medical Imaging models: 81 "vit_b_medical_imaging_decoder": "xxh128:9e498b12f526f119b96c88be76e3b2ed", 82 } 83 registry = {**encoder_registry, **decoder_registry} 84 85 encoder_urls = { 86 "vit_l": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth", 87 "vit_h": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", 88 "vit_b": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", 89 "vit_t": "https://owncloud.gwdg.de/index.php/s/TuDzuwVDHd1ZDnQ/download", 90 "vit_l_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/idealistic-rat/1.2/files/vit_l.pt", 91 "vit_b_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/diplomatic-bug/1.2/files/vit_b.pt", 92 "vit_t_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/faithful-chicken/1.1/files/vit_t.pt", 93 "vit_l_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/humorous-crab/1.2/files/vit_l.pt", # noqa 94 "vit_b_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/noisy-ox/1.2/files/vit_b.pt", # noqa 95 "vit_t_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/greedy-whale/1/files/vit_t.pt", # noqa 96 "vit_b_histopathology": "https://owncloud.gwdg.de/index.php/s/sBB4H8CTmIoBZsQ/download", 97 "vit_l_histopathology": "https://owncloud.gwdg.de/index.php/s/IZgnn1cpBq2PHod/download", 98 "vit_h_histopathology": "https://owncloud.gwdg.de/index.php/s/L7AcvVz7DoWJ2RZ/download", 99 "vit_b_medical_imaging": "https://owncloud.gwdg.de/index.php/s/f5Ol4FrjPQWfjUF/download", 100 } 101 102 decoder_urls = { 103 "vit_l_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/idealistic-rat/1.2/files/vit_l_decoder.pt", # noqa 104 "vit_b_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/diplomatic-bug/1.2/files/vit_b_decoder.pt", # noqa 105 "vit_t_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/faithful-chicken/1.1/files/vit_t_decoder.pt", # noqa 106 "vit_l_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/humorous-crab/1.2/files/vit_l_decoder.pt", # noqa 107 "vit_b_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/noisy-ox/1.2/files/vit_b_decoder.pt", # noqa 108 "vit_t_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/greedy-whale/1/files/vit_t_decoder.pt", # noqa 109 "vit_b_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/KO9AWqynI7SFOBj/download", 110 "vit_l_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/oIs6VSmkOp7XrKF/download", 111 "vit_h_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/1qAKxy5H0jgwZvM/download", 112 "vit_b_medical_imaging_decoder": "https://owncloud.gwdg.de/index.php/s/ahd3ZhZl2e0RIwz/download", 113 } 114 urls = {**encoder_urls, **decoder_urls} 115 116 models = pooch.create( 117 path=get_model_cache_directory(), 118 base_url="", 119 registry=registry, 120 urls=urls, 121 ) 122 return models 123 124 125def _download_sam_model(model_type, progress_bar_factory=None): 126 model_registry = models() 127 128 progress_bar = True 129 # Check if we have to download the model. 130 # If we do and have a progress bar factory, then we over-write the progress bar. 131 if not os.path.exists(get_model_cache_directory() / model_type) and progress_bar_factory is not None: 132 progress_bar = progress_bar_factory(model_type) 133 134 checkpoint_path = model_registry.fetch(model_type, progressbar=progress_bar) 135 if not isinstance(progress_bar, bool): # Close the progress bar when the task finishes. 136 progress_bar.close() 137 138 model_hash = model_registry.registry[model_type] 139 140 # If we have a custom model then we can also have a decoder checkpoint. 141 # Download it here, so that we can add it to the state. 142 decoder_name = f"{model_type}_decoder" 143 decoder_path = model_registry.fetch( 144 decoder_name, progressbar=True 145 ) if decoder_name in model_registry.registry else None 146 147 return checkpoint_path, model_hash, decoder_path 148 149 150def get_sam_model( 151 model_type: str = DEFAULT_SAM1_MODEL, 152 device: Optional[Union[str, torch.device]] = None, 153 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 154 return_sam: bool = False, 155 return_state: bool = False, 156 peft_kwargs: Optional[Dict] = None, 157 flexible_load_checkpoint: bool = False, 158 progress_bar_factory: Optional[Callable] = None, 159 decoder_path: Optional[Union[str, os.PathLike]] = None, 160 **model_kwargs, 161) -> SamPredictor: 162 r"""Get the Segment Anything Predictor. 163 164 This function will download the required model or load it from the cached weight file. 165 This location of the cache can be changed by setting the environment variable: MICROSAM_CACHEDIR. 166 The name of the requested model can be set via `model_type`. 167 See https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models 168 for an overview of the available models 169 170 Alternatively this function can also load a model from weights stored in a local filepath. 171 The corresponding file path is given via `checkpoint_path`. In this case `model_type` 172 must be given as the matching encoder architecture, e.g. "vit_b" if the weights are for 173 a SAM model with vit_b encoder. 174 175 By default the models are downloaded to a folder named 'micro_sam/models' 176 inside your default cache directory, eg: 177 * Mac: ~/Library/Caches/<AppName> 178 * Unix: ~/.cache/<AppName> or the value of the XDG_CACHE_HOME environment variable, if defined. 179 * Windows: C:\Users\<user>\AppData\Local\<AppAuthor>\<AppName>\Cache 180 See the pooch.os_cache() documentation for more details: 181 https://www.fatiando.org/pooch/latest/api/generated/pooch.os_cache.html 182 183 Args: 184 model_type: The Segment Anything model to use. Will use the 'vit_b_lm' model by default. 185 To get a list of all available model names you can call `micro_sam.v1.util.get_model_names`. 186 device: The device for the model. If 'None' is provided, will use GPU if available. 187 checkpoint_path: The path to a file with weights that should be used instead of using the 188 weights corresponding to `model_type`. If given, `model_type` must match the architecture 189 corresponding to the weight file. e.g. if you use weights for SAM with `vit_b` encoder 190 then `model_type` must be given as 'vit_b'. 191 return_sam: Return the sam model object as well as the predictor. By default, set to 'False'. 192 return_state: Return the unpickled checkpoint state. By default, set to 'False'. 193 peft_kwargs: Keyword arguments for th PEFT wrapper class. 194 If passed 'None', it does not initialize any parameter efficient finetuning. 195 flexible_load_checkpoint: Whether to adjust mismatching params while loading pretrained checkpoints. 196 By default, set to 'False'. 197 progress_bar_factory: A function to create a progress bar for the model download. 198 decoder_path: Optional path to weights for a segmentation decoder. If given and 199 `return_state=True`, the decoder state is added to the returned state as 200 'decoder_state'. This can be used to provide decoder-only weights that are 201 separate from the encoder checkpoint. 202 model_kwargs: Additional parameters necessary to initialize the Segment Anything model. 203 204 Returns: 205 The Segment Anything predictor. 206 """ 207 device = get_device(device) 208 209 # We support passing a local filepath to a checkpoint. 210 # In this case we do not download any weights but just use the local weight file, 211 # as it is, without copying it over anywhere or checking it's hashes. 212 213 # checkpoint_path has not been passed, we download a known model and derive the correct 214 # URL from the model_type. If the model_type is invalid pooch will raise an error. 215 _provided_checkpoint_path = checkpoint_path is not None 216 if checkpoint_path is None: 217 checkpoint_path, model_hash, downloaded_decoder_path = _download_sam_model(model_type, progress_bar_factory) 218 if decoder_path is None: 219 decoder_path = downloaded_decoder_path 220 221 # If checkpoint_path was passed, we use it instead of downloading a model. 222 else: 223 # Check if the file exists and raise an error otherwise. 224 # We can't check any hashes here, and we don't check if the file is actually a valid weight file. 225 # (If it isn't the model creation will fail below.) 226 if not os.path.exists(checkpoint_path): 227 raise ValueError(f"Checkpoint at '{checkpoint_path}' could not be found.") 228 model_hash = _compute_hash(checkpoint_path) 229 230 if decoder_path is not None and not os.path.exists(decoder_path): 231 raise ValueError(f"Decoder checkpoint at '{decoder_path}' could not be found.") 232 233 # Our fine-tuned model types have a suffix "_...". This suffix needs to be stripped 234 # before calling sam_model_registry. 235 abbreviated_model_type = model_type[:5] 236 if abbreviated_model_type not in SAM1_MODEL_TYPES: 237 raise ValueError(f"Invalid model_type: {abbreviated_model_type}. Expect one of {SAM1_MODEL_TYPES}") 238 if abbreviated_model_type == "vit_t" and not VIT_T_SUPPORT: 239 raise RuntimeError( 240 "'mobile_sam' is required for the vit-tiny. " 241 "You can install it via 'pip install git+https://github.com/ChaoningZhang/MobileSAM.git'" 242 ) 243 244 state, model_state = _load_checkpoint(checkpoint_path) 245 246 if _provided_checkpoint_path: 247 # To get the model weights, we prioritize having the correct 'checkpoint_path' over 'model_type' 248 # It is done to avoid strange parameter mismatch issues while incompatible model type and weights combination. 249 from micro_sam.v1.models.build_sam import _validate_model_type 250 _provided_model_type = _validate_model_type(model_state) 251 252 # Verify whether the 'abbreviated_model_type' matches the '_provided_model_type' 253 # Otherwise replace 'abbreviated_model_type' with the later. 254 if abbreviated_model_type != _provided_model_type: 255 # Printing the message below to avoid any filtering of warnings on user's end. 256 print( 257 f"CRITICAL WARNING: The chosen 'model_type' is '{abbreviated_model_type}', " 258 f"however the model checkpoint provided correspond to '{_provided_model_type}', which does not match. " 259 f"We internally switch the model type to the expected value, i.e. '{_provided_model_type}'. " 260 "However, please avoid mismatching combination of 'model_type' and 'checkpoint_path' in future." 261 ) 262 263 # Replace the extracted 'abbreviated_model_type' subjected to the model weights. 264 abbreviated_model_type = _provided_model_type 265 266 # Whether to update parameters necessary to initialize the model 267 if model_kwargs: # Checks whether model_kwargs have been provided or not 268 if abbreviated_model_type == "vit_t": 269 raise ValueError("'micro-sam' does not support changing the model parameters for 'mobile-sam'.") 270 sam = custom_models.sam_model_registry[abbreviated_model_type](**model_kwargs) 271 272 else: 273 sam = sam_model_registry[abbreviated_model_type]() 274 275 # Whether to use Parameter Efficient Finetuning methods to wrap around Segment Anything. 276 # Overwrites the SAM model by freezing the backbone and allow PEFT. 277 if peft_kwargs and isinstance(peft_kwargs, dict): 278 # NOTE: We bump out 'quantize' parameter, if found, as we do not quantize in inference. 279 peft_kwargs.pop("quantize", None) 280 281 if abbreviated_model_type == "vit_t": 282 raise ValueError("'micro-sam' does not support parameter efficient finetuning for 'mobile-sam'.") 283 284 sam = custom_models.peft_sam.PEFT_Sam(sam, **peft_kwargs).sam 285 # In case the model checkpoints have some issues when it is initialized with different parameters than default. 286 if flexible_load_checkpoint: 287 sam = _handle_checkpoint_loading(sam, model_state) 288 else: 289 sam.load_state_dict(model_state) 290 sam.to(device=device) 291 292 predictor = SamPredictor(sam) 293 predictor.model_type = abbreviated_model_type 294 predictor._hash = model_hash 295 predictor.model_name = model_type 296 predictor.checkpoint_path = checkpoint_path 297 298 # Add the decoder to the state if we have one and if the state is returned. 299 if decoder_path is not None and return_state: 300 state["decoder_state"] = torch.load(decoder_path, map_location=device, weights_only=False) 301 302 if return_sam and return_state: 303 return predictor, sam, state 304 if return_sam: 305 return predictor, sam 306 if return_state: 307 return predictor, state 308 return predictor 309 310 311def _handle_checkpoint_loading(sam, model_state): 312 # Whether to handle the mismatch issues in a bit more elegant way. 313 # eg. while training for multi-class semantic segmentation in the mask encoder, 314 # parameters are updated - leading to "size mismatch" errors 315 316 new_state_dict = {} # for loading matching parameters 317 mismatched_layers = [] # for tracking mismatching parameters 318 319 reference_state = sam.state_dict() 320 321 for k, v in model_state.items(): 322 if k in reference_state: # This is done to get rid of unwanted layers from pretrained SAM. 323 if reference_state[k].size() == v.size(): 324 new_state_dict[k] = v 325 else: 326 mismatched_layers.append(k) 327 328 reference_state.update(new_state_dict) 329 330 if len(mismatched_layers) > 0: 331 warnings.warn(f"The layers with size mismatch: {mismatched_layers}") 332 333 for mlayer in mismatched_layers: 334 if 'weight' in mlayer: 335 torch.nn.init.kaiming_uniform_(reference_state[mlayer]) 336 elif 'bias' in mlayer: 337 reference_state[mlayer].zero_() 338 339 sam.load_state_dict(reference_state) 340 341 return sam 342 343 344def export_custom_sam_model( 345 checkpoint_path: Union[str, os.PathLike], 346 model_type: str, 347 save_path: Union[str, os.PathLike], 348 with_segmentation_decoder: bool = False, 349 prefix: str = "sam.", 350) -> None: 351 """Export a finetuned Segment Anything Model to the standard model format. 352 353 The exported model can be used by the interactive annotation tools in `micro_sam.annotator`. 354 355 Args: 356 checkpoint_path: The path to the corresponding checkpoint if not in the default model folder. 357 model_type: The Segment Anything Model type corresponding to the checkpoint (vit_h, vit_b, vit_l or vit_t). 358 save_path: Where to save the exported model. 359 with_segmentation_decoder: Whether to store the decoder state in the model checkpoint as well. 360 If set to 'True', the model checkpoint will not be compatible with other tools besides 'micro-sam'. 361 prefix: The prefix to remove from the model parameter keys. 362 """ 363 state, model_state = _load_checkpoint(checkpoint_path=checkpoint_path) 364 model_state = OrderedDict([(k[len(prefix):] if k.startswith(prefix) else k, v) for k, v in model_state.items()]) 365 366 # Store the 'decoder_state' as well, if desired. 367 if with_segmentation_decoder: 368 if "decoder_state" not in state: 369 raise RuntimeError(f"'decoder_state' is not found in the model at '{checkpoint_path}'.") 370 decoder_state = state["decoder_state"] 371 save_state = {"model_state": model_state, "decoder_state": decoder_state} 372 else: 373 save_state = model_state 374 375 torch.save(save_state, save_path) 376 377 378def export_custom_qlora_model( 379 checkpoint_path: Optional[Union[str, os.PathLike]], 380 finetuned_path: Union[str, os.PathLike], 381 model_type: str, 382 save_path: Union[str, os.PathLike], 383) -> None: 384 """Export a finetuned Segment Anything Model, in QLoRA style, to LoRA-style checkpoint format. 385 386 The exported model can be used with the LoRA backbone by passing the relevant `peft_kwargs` to `get_sam_model`. 387 388 Args: 389 checkpoint_path: The path to the base foundation model from which the new model has been finetuned. 390 finetuned_path: The path to the new finetuned model, using QLoRA. 391 model_type: The Segment Anything Model type corresponding to the checkpoint. 392 save_path: Where to save the exported model. 393 """ 394 # Step 1: Get the base SAM model: used to start finetuning from. 395 _, sam = get_sam_model( 396 model_type=model_type, checkpoint_path=checkpoint_path, return_sam=True, 397 ) 398 399 # Step 2: Load the QLoRA-style finetuned model. 400 ft_state, ft_model_state = _load_checkpoint(finetuned_path) 401 402 # Step 3: Identify LoRA layers from QLoRA model. 403 # - differentiate between LoRA applied to the attention matrices and LoRA applied to the MLP layers. 404 # - then copy the LoRA layers from the QLoRA model to the new state dict 405 updated_model_state = {} 406 407 modified_attn_layers = set() 408 modified_mlp_layers = set() 409 410 for k, v in ft_model_state.items(): 411 if "blocks." in k: 412 layer_id = int(k.split("blocks.")[1].split(".")[0]) 413 if k.find("qkv.w_a_linear") != -1 or k.find("qkv.w_b_linear") != -1: 414 modified_attn_layers.add(layer_id) 415 updated_model_state[k] = v 416 if k.find("mlp.w_a_linear") != -1 or k.find("mlp.w_b_linear") != -1: 417 modified_mlp_layers.add(layer_id) 418 updated_model_state[k] = v 419 420 # Step 4: Next, we get all the remaining parameters from the base SAM model. 421 for k, v in sam.state_dict().items(): 422 if "blocks." in k: 423 layer_id = int(k.split("blocks.")[1].split(".")[0]) 424 if k.find("attn.qkv.") != -1: 425 if layer_id in modified_attn_layers: # We have LoRA in QKV layers, so we need to modify the key 426 k = k.replace("qkv", "qkv.qkv_proj") 427 elif k.find("mlp") != -1 and k.find("image_encoder") != -1: 428 if layer_id in modified_mlp_layers: # We have LoRA in MLP layers, so we need to modify the key 429 k = k.replace("mlp.", "mlp.mlp_layer.") 430 updated_model_state[k] = v 431 432 # Step 5: Finally, we replace the old model state with the new one (to retain other relevant stuff) 433 ft_state['model_state'] = updated_model_state 434 435 # Step 6: Store the new "state" to "save_path" 436 torch.save(ft_state, save_path) 437 438 439def get_model_names() -> Iterable: 440 model_registry = models() 441 model_names = model_registry.registry.keys() 442 return model_names 443 444 445@torch.no_grad 446def _compute_embeddings_batched(predictor, batched_images): 447 predictor.reset_image() 448 batched_tensors, original_sizes, input_sizes = [], [], [] 449 450 # Apply proeprocessing to all images in the batch, and then stack them. 451 # Note: after the transformation the images are all of the same size, 452 # so they can be stacked and processed as a batch, even if the input images were of different size. 453 for image in batched_images: 454 tensor = predictor.transform.apply_image(image) 455 tensor = torch.as_tensor(tensor, device=predictor.device) 456 tensor = tensor.permute(2, 0, 1).contiguous()[None, :, :, :] 457 458 original_sizes.append(image.shape[:2]) 459 input_sizes.append(tensor.shape[-2:]) 460 461 tensor = predictor.model.preprocess(tensor) 462 batched_tensors.append(tensor) 463 464 batched_tensors = torch.cat(batched_tensors) 465 features = predictor.model.image_encoder(batched_tensors) 466 467 predictor.original_size = original_sizes[-1] 468 predictor.input_size = input_sizes[-1] 469 predictor.features = features[-1] 470 predictor.is_image_set = True 471 472 return features, original_sizes, input_sizes 473 474 475def _write_batch(features, tile_ids, batched_embeddings, original_sizes, input_sizes, slices=None, n_slices=None): 476 477 # Pre-create / pre-fetch the datasets if we have slices. 478 # (Dataset creation is not thread-safe) 479 if slices is not None: 480 datasets = {} 481 for tile_id, tile_embeddings, original_size, input_size in zip( 482 tile_ids, batched_embeddings, original_sizes, input_sizes 483 ): 484 ds_name = str(tile_id) 485 if ds_name in datasets: 486 continue 487 if ds_name in features: 488 datasets[ds_name] = features[ds_name] 489 continue 490 shape = (n_slices, 1) + tile_embeddings.shape 491 chunks = (1, 1) + tile_embeddings.shape 492 ds = _create_dataset_without_data(features, ds_name, shape=shape, dtype="float32", chunks=chunks) 493 ds.attrs["original_size"] = original_size 494 ds.attrs["input_size"] = input_size 495 datasets[ds_name] = ds 496 497 def _write_embed(i): 498 ds_name = str(tile_ids[i]) 499 tile_embeddings = batched_embeddings[i].unsqueeze(0) 500 if slices is None: 501 ds = _create_dataset_with_data(features, ds_name, data=tile_embeddings.cpu().numpy()) 502 ds.attrs["original_size"] = original_sizes[i] 503 ds.attrs["input_size"] = input_sizes[i] 504 elif ds_name in features: 505 ds = datasets[ds_name] 506 z = slices[i] 507 ds[z] = tile_embeddings.cpu().numpy() 508 509 n_tiles = len(tile_ids) 510 n_workers = min(mp.cpu_count(), n_tiles) 511 with futures.ThreadPoolExecutor(n_workers) as tp: 512 list(tp.map(_write_embed, range(n_tiles))) 513 514 515def _get_tiles_in_mask(mask, tiling, halo, z=None): 516 def _check_mask(tile_id): 517 tile = tiling.get_block_with_halo(tile_id, list(halo)) 518 outer_tile = tuple(slice(beg, end) for beg, end in zip(tile.outer_block.begin, tile.outer_block.end)) 519 if z is not None: 520 outer_tile = (z,) + outer_tile 521 tile_mask = mask[outer_tile].astype("bool") 522 return None if tile_mask.sum() == 0 else tile_id 523 524 n_threads = mp.cpu_count() 525 with futures.ThreadPoolExecutor(n_threads) as tp: 526 tiles_in_mask = tp.map(_check_mask, range(tiling.number_of_blocks)) 527 return sorted([tile_id for tile_id in tiles_in_mask if tile_id is not None]) 528 529 530def _compute_tiled_features_2d(predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask): 531 tiling = Blocking([0, 0], input_.shape[:2], tile_shape) 532 n_tiles = tiling.number_of_blocks 533 534 features = f.require_group("features") 535 features.attrs["shape"] = input_.shape[:2] 536 features.attrs["tile_shape"] = tile_shape 537 features.attrs["halo"] = halo 538 539 n_batches = int(np.ceil(n_tiles / batch_size)) 540 if mask is None: 541 tile_ids_for_batches = [ 542 range(batch_id * batch_size, min((batch_id + 1) * batch_size, n_tiles)) 543 for batch_id in range(n_batches) 544 ] 545 pbar_init(n_tiles, "Compute Image Embeddings 2D tiled") 546 else: 547 tiles_in_mask = _get_tiles_in_mask(mask, tiling, halo) 548 pbar_init(len(tiles_in_mask), "Compute Image Embeddings 2D tiled with mask") 549 tile_ids_for_batches = np.array_split(tiles_in_mask, n_batches) 550 assert len(tile_ids_for_batches) == n_batches 551 552 for tile_ids in tile_ids_for_batches: 553 batched_images = [] 554 for tile_id in tile_ids: 555 tile = tiling.get_block_with_halo(tile_id, list(halo)) 556 outer_tile = tuple(slice(beg, end) for beg, end in zip(tile.outer_block.begin, tile.outer_block.end)) 557 tile_input = _to_image(input_[outer_tile]) 558 batched_images.append(tile_input) 559 560 batched_embeddings, original_sizes, input_sizes = _compute_embeddings_batched(predictor, batched_images) 561 _write_batch(features, tile_ids, batched_embeddings, original_sizes, input_sizes) 562 pbar_update(len(tile_ids)) 563 564 _write_embedding_signature(f, input_, predictor, tile_shape, halo, input_size=None, original_size=None) 565 if mask is not None: 566 features.attrs["tiles_in_mask"] = tiles_in_mask 567 568 return features 569 570 571class _BatchProvider: 572 def __init__(self, n_slices, n_tiles_per_plane, tiles_in_mask_per_slice, batch_size): 573 if tiles_in_mask_per_slice is None: 574 self.n_tiles_total = n_slices * n_tiles_per_plane 575 else: 576 self.n_tiles_total = sum(len(val) for val in tiles_in_mask_per_slice.values()) 577 578 self.n_batches = int(np.ceil(self.n_tiles_total / batch_size)) 579 self.n_slices = n_slices 580 self.n_tiles_per_plane = n_tiles_per_plane 581 self.tiles_in_mask_per_slice = tiles_in_mask_per_slice 582 self.batch_size = batch_size 583 584 # Iter variables. 585 self.batch_id = 0 586 self.z = 0 587 self.tile_id = 0 588 589 def __iter__(self): 590 return self 591 592 def __next__(self): 593 if self.batch_id >= self.n_batches: 594 raise StopIteration 595 596 z_list = list(range(self.n_tiles_per_plane)) 597 z_tiles = z_list if self.tiles_in_mask_per_slice is None else self.tiles_in_mask_per_slice[self.z] 598 599 slices, tile_ids = [], [] 600 this_batch_size = 0 601 while this_batch_size < self.batch_size: 602 if self.tile_id == len(z_tiles): 603 self.z += 1 604 self.tile_id = 0 605 if self.z >= self.n_slices: 606 break 607 z_tiles = z_list if self.tiles_in_mask_per_slice is None else self.tiles_in_mask_per_slice[self.z] 608 continue 609 610 slices.append(self.z), tile_ids.append(z_tiles[self.tile_id]) 611 self.tile_id += 1 612 this_batch_size += 1 613 614 self.batch_id += 1 615 return slices, tile_ids 616 617 618def _compute_tiled_features_3d(predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask): 619 assert input_.ndim == 3 620 621 shape = input_.shape[1:] 622 tiling = Blocking([0, 0], shape, tile_shape) 623 features = f.require_group("features") 624 features.attrs["shape"] = shape 625 features.attrs["tile_shape"] = tile_shape 626 features.attrs["halo"] = halo 627 628 n_tiles_per_plane = tiling.number_of_blocks 629 n_slices = input_.shape[0] 630 631 msg = "Compute Image Embeddings 3D tiled" 632 if mask is None: 633 n_tiles_total = n_slices * n_tiles_per_plane 634 tiles_in_mask_per_slice = None 635 else: 636 tiles_in_mask_per_slice = {} 637 for z in range(n_slices): 638 tiles_in_mask_per_slice[z] = _get_tiles_in_mask(mask, tiling, halo, z=z) 639 n_tiles_total = sum(len(val) for val in tiles_in_mask_per_slice.values()) 640 msg += " masked" 641 pbar_init(n_tiles_total, msg) 642 643 batch_provider = _BatchProvider(n_slices, n_tiles_per_plane, tiles_in_mask_per_slice, batch_size) 644 for slices, tile_ids in batch_provider: 645 batched_images = [] 646 for z, tile_id in zip(slices, tile_ids): 647 tile = tiling.get_block_with_halo(tile_id, list(halo)) 648 outer_tile = (z,) + tuple( 649 slice(beg, end) for beg, end in zip(tile.outer_block.begin, tile.outer_block.end) 650 ) 651 tile_input = _to_image(input_[outer_tile]) 652 batched_images.append(tile_input) 653 654 batched_embeddings, original_sizes, input_sizes = _compute_embeddings_batched(predictor, batched_images) 655 _write_batch( 656 features, tile_ids, batched_embeddings, original_sizes, input_sizes, slices=slices, n_slices=n_slices 657 ) 658 pbar_update(len(tile_ids)) 659 660 if mask is not None: 661 features.attrs["tiles_in_mask"] = {str(z): per_slice for z, per_slice in tiles_in_mask_per_slice.items()} 662 663 _write_embedding_signature(f, input_, predictor, tile_shape, halo, input_size=None, original_size=None) 664 return features 665 666 667def _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update): 668 # Check if the embeddings are already cached. 669 if save_path is not None and "input_size" in f.attrs: 670 # In this case we load the embeddings. 671 features = f["features"][:] 672 original_size, input_size = f.attrs["original_size"], f.attrs["input_size"] 673 image_embeddings = {"features": features, "input_size": input_size, "original_size": original_size} 674 # Also set the embeddings. 675 set_precomputed(predictor, image_embeddings) 676 return image_embeddings 677 678 pbar_init(1, "Compute Image Embeddings 2D") 679 # Otherwise we have to compute the embeddings. 680 predictor.reset_image() 681 predictor.set_image(_to_image(input_)) 682 features = predictor.get_image_embedding().cpu().numpy() 683 original_size = predictor.original_size 684 input_size = predictor.input_size 685 pbar_update(1) 686 687 # Save the embeddings if we have a save_path. 688 if save_path is not None: 689 _create_dataset_with_data(f, "features", data=features) 690 _write_embedding_signature( 691 f, input_, predictor, tile_shape=None, halo=None, input_size=input_size, original_size=original_size, 692 ) 693 694 image_embeddings = {"features": features, "input_size": input_size, "original_size": original_size} 695 return image_embeddings 696 697 698def _compute_tiled_2d(input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask): 699 # Check if the features are already computed. 700 if "input_size" in f.attrs: 701 features = f["features"] 702 original_size, input_size = f.attrs["original_size"], f.attrs["input_size"] 703 image_embeddings = {"features": features, "input_size": input_size, "original_size": original_size} 704 return image_embeddings 705 706 # Otherwise compute them. Note: saving happens automatically because we 707 # always write the features to zarr. If no save path is given we use an in-memory zarr. 708 features = _compute_tiled_features_2d( 709 predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask=mask 710 ) 711 image_embeddings = {"features": features, "input_size": None, "original_size": None} 712 return image_embeddings 713 714 715def _compute_3d(input_, predictor, f, save_path, lazy_loading, pbar_init, pbar_update, batch_size): 716 # Check if the embeddings are already fully cached. 717 if save_path is not None and "input_size" in f.attrs: 718 # In this case we load the embeddings. 719 features = f["features"] if lazy_loading else f["features"][:] 720 original_size, input_size = f.attrs["original_size"], f.attrs["input_size"] 721 image_embeddings = {"features": features, "input_size": input_size, "original_size": original_size} 722 return image_embeddings 723 724 # Otherwise we have to compute the embeddings. 725 726 # First check if we have a save path or not and set things up accordingly. 727 if save_path is None: 728 features = [] 729 save_features = False 730 partial_features = False 731 else: 732 save_features = True 733 embed_shape = (1, 256, 64, 64) 734 shape = (input_.shape[0],) + embed_shape 735 chunks = (1,) + embed_shape 736 if "features" in f: 737 partial_features = True 738 features = f["features"] 739 if features.shape != shape or features.chunks != chunks: 740 raise RuntimeError("Invalid partial features") 741 else: 742 partial_features = False 743 features = _create_dataset_without_data(f, "features", shape=shape, chunks=chunks, dtype="float32") 744 745 # Initialize the pbar and batches. 746 n_slices = input_.shape[0] 747 pbar_init(n_slices, "Compute Image Embeddings 3D") 748 n_batches = int(np.ceil(n_slices / batch_size)) 749 750 for batch_id in range(n_batches): 751 z_start = batch_id * batch_size 752 z_stop = min(z_start + batch_size, n_slices) 753 754 batched_images, batched_z = [], [] 755 for z in range(z_start, z_stop): 756 # Skip feature computation in case of partial features in non-zero slice. 757 if partial_features and np.count_nonzero(features[z]) != 0: 758 continue 759 tile_input = _to_image(input_[z]) 760 batched_images.append(tile_input) 761 batched_z.append(z) 762 763 batched_embeddings, original_sizes, input_sizes = _compute_embeddings_batched(predictor, batched_images) 764 765 for z, embedding in zip(batched_z, batched_embeddings): 766 embedding = embedding.unsqueeze(0) 767 if save_features: 768 features[z] = embedding.cpu().numpy() 769 else: 770 features.append(embedding.unsqueeze(0)) 771 pbar_update(1) 772 773 if save_features: 774 _write_embedding_signature( 775 f, input_, predictor, tile_shape=None, halo=None, 776 input_size=input_sizes[-1], original_size=original_sizes[-1], 777 ) 778 else: 779 # Concatenate across the z axis. 780 features = torch.cat(features).cpu().numpy() 781 782 image_embeddings = {"features": features, "input_size": input_sizes[-1], "original_size": original_sizes[-1]} 783 return image_embeddings 784 785 786def _compute_tiled_3d(input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask): 787 # Check if the features are already computed. 788 if "input_size" in f.attrs: 789 features = f["features"] 790 original_size, input_size = f.attrs["original_size"], f.attrs["input_size"] 791 image_embeddings = {"features": features, "input_size": input_size, "original_size": original_size} 792 return image_embeddings 793 794 # Otherwise compute them. Note: saving happens automatically because we 795 # always write the features to zarr. If no save path is given we use an in-memory zarr. 796 features = _compute_tiled_features_3d( 797 predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask 798 ) 799 image_embeddings = {"features": features, "input_size": None, "original_size": None} 800 return image_embeddings 801 802 803def _check_saved_embeddings(input_, predictor, f, save_path, tile_shape, halo): 804 """Validate saved embeddings against the requested configuration. 805 806 Returns True if the saved embeddings are stale and should be recomputed (the model or tiling 807 configuration changed), False if they can be loaded. Raises if they belong to different image 808 data (data signature mismatch). 809 """ 810 # We can have an empty zarr file that was already created to save the embeddings in. 811 # In this case the embeddings will be computed and we don't need to perform any checks. 812 if "input_size" not in f.attrs: 813 return False 814 815 signature = _get_embedding_signature(input_, predictor, tile_shape, halo) 816 stale = False 817 for key, val in signature.items(): 818 # A key absent from an older file must not invalidate it (it predates that key). 819 if key not in f.attrs or f.attrs[key] == val: 820 continue 821 # Different image data: surface as an error rather than silently overwriting it. 822 if key == "data_signature": 823 raise RuntimeError( 824 f"Embeddings file {save_path} is invalid due to mismatch in {key}: " 825 f"{f.attrs.get(key)} != {val}. Please recompute embeddings in a new file." 826 ) 827 # A version bump alone does not invalidate the embeddings. 828 if key == "micro_sam_version": 829 warnings.warn( 830 f"The signature for {key} in embeddings file {save_path} has a mismatch: " 831 f"{f.attrs.get(key)} != {val}. This key was recently added, so your embeddings are likely correct. " 832 "But please recompute them if model predictions don't look as expected." 833 ) 834 continue 835 # Model or tiling changed: the saved embeddings are stale and must be recomputed. 836 stale = True 837 return stale 838 839 840def precompute_image_embeddings( 841 predictor: SamPredictor, 842 input_: np.ndarray, 843 save_path: Optional[Union[str, os.PathLike]] = None, 844 lazy_loading: bool = False, 845 ndim: Optional[int] = None, 846 tile_shape: Optional[Tuple[int, int]] = None, 847 halo: Optional[Tuple[int, int]] = None, 848 verbose: bool = True, 849 batch_size: Optional[int] = 1, 850 mask: Optional[np.typing.ArrayLike] = None, 851 pbar_init: Optional[callable] = None, 852 pbar_update: Optional[callable] = None, 853) -> ImageEmbeddings: 854 """Compute the image embeddings (output of the encoder) for the input. 855 856 If 'save_path' is given the embeddings will be loaded/saved in a zarr container. 857 858 Args: 859 predictor: The Segment Anything predictor. 860 input_: The input data. Can be 2 or 3 dimensional, corresponding to an image, volume or timeseries. 861 save_path: Path to save the embeddings in a zarr container. 862 By default, set to 'None', i.e. the computed embeddings will not be stored locally. 863 lazy_loading: Whether to load all embeddings into memory or return an 864 object to load them on demand when required. This only has an effect if 'save_path' is given 865 and if the input is 3 dimensional. By default, set to 'False'. 866 ndim: The dimensionality of the data. If not given will be deduced from the input data. 867 By default, set to 'None', i.e. will be computed from the provided `input_`. 868 tile_shape: Shape of tiles for tiled prediction. By default prediction is run without tiling. 869 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 870 verbose: Whether to be verbose in the computation. By default, set to 'True'. 871 batch_size: The batch size for precomputing image embeddings over tiles (or planes). By default, set to '1'. 872 Pass None to leave the choice to the backend, which is a single tile / plane for SAM1. 873 mask: An optional mask to define areas that are ignored in the computation. 874 The mask will be used within tiled embedding computation and tiles that don't contain any foreground 875 in the mask will be excluded from the computation. It does not have any effect for non-tiled embeddings. 876 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 877 Can be used together with pbar_update to handle napari progress bar in other thread. 878 To enable using this function within a threadworker. 879 pbar_update: Callback to update an external progress bar. 880 881 Returns: 882 The image embeddings. 883 """ 884 ndim = input_.ndim if ndim is None else ndim 885 # SAM1 has no per-device batch-size lookup, so the automatic choice is the single tile / slice. 886 batch_size = 1 if batch_size is None else batch_size 887 888 # Handle the embedding save_path. 889 # We don't have a save path, open in memory zarr file to hold tiled embeddings. 890 if save_path is None: 891 f = _open_embeddings(None) 892 893 # We have a save path and it already exists. Embeddings will be loaded from it, 894 # check that the saved embeddings in there match the parameters of the function call. 895 elif os.path.exists(save_path): 896 f = _open_embeddings(save_path, mode="a") 897 if _check_saved_embeddings(input_, predictor, f, save_path, tile_shape, halo): 898 # Stale embeddings (model or tiling changed): truncate and recompute, overwriting them. 899 f = _open_embeddings(save_path, mode="w") 900 901 # We have a save path and it does not exist yet. Create the zarr file to which the 902 # embeddings will then be saved. 903 else: 904 f = _open_embeddings(save_path, mode="a") 905 906 _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update) 907 908 if ndim == 2 and tile_shape is None: 909 embeddings = _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update) 910 elif ndim == 2 and tile_shape is not None: 911 embeddings = _compute_tiled_2d( 912 input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask=mask 913 ) 914 elif ndim == 3 and tile_shape is None: 915 embeddings = _compute_3d(input_, predictor, f, save_path, lazy_loading, pbar_init, pbar_update, batch_size) 916 elif ndim == 3 and tile_shape is not None: 917 embeddings = _compute_tiled_3d( 918 input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask=mask 919 ) 920 else: 921 raise ValueError(f"Invalid dimesionality {input_.ndim}, expect 2 or 3 dim data.") 922 923 pbar_close() 924 return embeddings 925 926 927def set_precomputed( 928 predictor: SamPredictor, image_embeddings: ImageEmbeddings, i: Optional[int] = None, tile_id: Optional[int] = None, 929) -> SamPredictor: 930 """Set the precomputed image embeddings for a predictor. 931 932 Args: 933 predictor: The Segment Anything predictor. 934 image_embeddings: The precomputed image embeddings computed by `precompute_image_embeddings`. 935 i: Index for the image data. Required if `image` has three spatial dimensions 936 or a time dimension and two spatial dimensions. 937 tile_id: Index for the tile. This is required if the embeddings are tiled. 938 939 Returns: 940 The predictor with set features. 941 """ 942 if tile_id is not None: 943 tile_features = image_embeddings["features"][str(tile_id)] 944 tile_image_embeddings = { 945 "features": tile_features, 946 "input_size": tile_features.attrs["input_size"], 947 "original_size": tile_features.attrs["original_size"] 948 } 949 return set_precomputed(predictor, tile_image_embeddings, i=i) 950 951 device = predictor.device 952 features = image_embeddings["features"] 953 assert features.ndim in (4, 5), f"{features.ndim}" 954 if features.ndim == 5 and i is None: 955 raise ValueError("The data is 3D so an index i is needed.") 956 elif features.ndim == 4 and i is not None: 957 raise ValueError("The data is 2D so an index is not needed.") 958 959 if i is None: 960 predictor.features = features.to(device) if torch.is_tensor(features) else \ 961 torch.from_numpy(features[:]).to(device) 962 else: 963 predictor.features = features[i].to(device) if torch.is_tensor(features) else \ 964 torch.from_numpy(features[i]).to(device) 965 966 predictor.original_size = image_embeddings["original_size"] 967 predictor.input_size = image_embeddings["input_size"] 968 predictor.is_image_set = True 969 970 return predictor
31def models(): 32 """Return the segmentation models registry. 33 34 We recreate the model registry every time this function is called, 35 so any user changes to the default micro-sam cache directory location 36 are respected. 37 """ 38 39 # We use xxhash to compute the hash of the models, see 40 # https://github.com/computational-cell-analytics/micro-sam/issues/283 41 # (It is now a dependency, so we don't provide the sha256 fallback anymore.) 42 # To generate the xxh128 hash: 43 # xxh128sum filename 44 encoder_registry = { 45 # The default segment anything models: 46 "vit_l": "xxh128:a82beb3c660661e3dd38d999cc860e9a", 47 "vit_h": "xxh128:97698fac30bd929c2e6d8d8cc15933c2", 48 "vit_b": "xxh128:6923c33df3637b6a922d7682bfc9a86b", 49 # The model with vit tiny backend fom https://github.com/ChaoningZhang/MobileSAM. 50 "vit_t": "xxh128:8eadbc88aeb9d8c7e0b4b60c3db48bd0", 51 # The current version of our models in the modelzoo. 52 # LM generalist models: 53 "vit_l_lm": "xxh128:017f20677997d628426dec80a8018f9d", 54 "vit_b_lm": "xxh128:fe9252a29f3f4ea53c15a06de471e186", 55 "vit_t_lm": "xxh128:72ec5074774761a6e5c05a08942f981e", 56 # EM models: 57 "vit_l_em_organelles": "xxh128:810b084b6e51acdbf760a993d8619f2d", 58 "vit_b_em_organelles": "xxh128:f3bf2ed83d691456bae2c3f9a05fb438", 59 "vit_t_em_organelles": "xxh128:253474720c497cce605e57c9b1d18fd9", 60 # Histopathology models: 61 "vit_b_histopathology": "xxh128:ffd1a2cd84570458b257bd95fdd8f974", 62 "vit_l_histopathology": "xxh128:b591833c89754271023e901281dee3f2", 63 "vit_h_histopathology": "xxh128:bd1856dafc156a43fb3aa705f1a6e92e", 64 # Medical Imaging models: 65 "vit_b_medical_imaging": "xxh128:40169f1e3c03a4b67bff58249c176d92", 66 } 67 # Additional decoders for instance segmentation. 68 decoder_registry = { 69 # LM generalist models: 70 "vit_l_lm_decoder": "xxh128:2faeafa03819dfe03e7c46a44aaac64a", 71 "vit_b_lm_decoder": "xxh128:708b15ac620e235f90bb38612c4929ba", 72 "vit_t_lm_decoder": "xxh128:3e914a5f397b0312cdd36813031f8823", 73 # EM models: 74 "vit_l_em_organelles_decoder": "xxh128:334877640bfdaaabce533e3252a17294", 75 "vit_b_em_organelles_decoder": "xxh128:bb6398956a6b0132c26b631c14f95ce2", 76 "vit_t_em_organelles_decoder": "xxh128:8f897c7bb93174a4d1638827c4dd6f44", 77 # Histopathology models: 78 "vit_b_histopathology_decoder": "xxh128:6a66194dcb6e36199cbee2214ecf7213", 79 "vit_l_histopathology_decoder": "xxh128:46aab7765d4400e039772d5a50b55c04", 80 "vit_h_histopathology_decoder": "xxh128:3ed9f87e46ad5e16935bd8d722c8dc47", 81 # Medical Imaging models: 82 "vit_b_medical_imaging_decoder": "xxh128:9e498b12f526f119b96c88be76e3b2ed", 83 } 84 registry = {**encoder_registry, **decoder_registry} 85 86 encoder_urls = { 87 "vit_l": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth", 88 "vit_h": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", 89 "vit_b": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", 90 "vit_t": "https://owncloud.gwdg.de/index.php/s/TuDzuwVDHd1ZDnQ/download", 91 "vit_l_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/idealistic-rat/1.2/files/vit_l.pt", 92 "vit_b_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/diplomatic-bug/1.2/files/vit_b.pt", 93 "vit_t_lm": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/faithful-chicken/1.1/files/vit_t.pt", 94 "vit_l_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/humorous-crab/1.2/files/vit_l.pt", # noqa 95 "vit_b_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/noisy-ox/1.2/files/vit_b.pt", # noqa 96 "vit_t_em_organelles": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/greedy-whale/1/files/vit_t.pt", # noqa 97 "vit_b_histopathology": "https://owncloud.gwdg.de/index.php/s/sBB4H8CTmIoBZsQ/download", 98 "vit_l_histopathology": "https://owncloud.gwdg.de/index.php/s/IZgnn1cpBq2PHod/download", 99 "vit_h_histopathology": "https://owncloud.gwdg.de/index.php/s/L7AcvVz7DoWJ2RZ/download", 100 "vit_b_medical_imaging": "https://owncloud.gwdg.de/index.php/s/f5Ol4FrjPQWfjUF/download", 101 } 102 103 decoder_urls = { 104 "vit_l_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/idealistic-rat/1.2/files/vit_l_decoder.pt", # noqa 105 "vit_b_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/diplomatic-bug/1.2/files/vit_b_decoder.pt", # noqa 106 "vit_t_lm_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/faithful-chicken/1.1/files/vit_t_decoder.pt", # noqa 107 "vit_l_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/humorous-crab/1.2/files/vit_l_decoder.pt", # noqa 108 "vit_b_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/noisy-ox/1.2/files/vit_b_decoder.pt", # noqa 109 "vit_t_em_organelles_decoder": "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/greedy-whale/1/files/vit_t_decoder.pt", # noqa 110 "vit_b_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/KO9AWqynI7SFOBj/download", 111 "vit_l_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/oIs6VSmkOp7XrKF/download", 112 "vit_h_histopathology_decoder": "https://owncloud.gwdg.de/index.php/s/1qAKxy5H0jgwZvM/download", 113 "vit_b_medical_imaging_decoder": "https://owncloud.gwdg.de/index.php/s/ahd3ZhZl2e0RIwz/download", 114 } 115 urls = {**encoder_urls, **decoder_urls} 116 117 models = pooch.create( 118 path=get_model_cache_directory(), 119 base_url="", 120 registry=registry, 121 urls=urls, 122 ) 123 return models
Return the segmentation models registry.
We recreate the model registry every time this function is called, so any user changes to the default micro-sam cache directory location are respected.
151def get_sam_model( 152 model_type: str = DEFAULT_SAM1_MODEL, 153 device: Optional[Union[str, torch.device]] = None, 154 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 155 return_sam: bool = False, 156 return_state: bool = False, 157 peft_kwargs: Optional[Dict] = None, 158 flexible_load_checkpoint: bool = False, 159 progress_bar_factory: Optional[Callable] = None, 160 decoder_path: Optional[Union[str, os.PathLike]] = None, 161 **model_kwargs, 162) -> SamPredictor: 163 r"""Get the Segment Anything Predictor. 164 165 This function will download the required model or load it from the cached weight file. 166 This location of the cache can be changed by setting the environment variable: MICROSAM_CACHEDIR. 167 The name of the requested model can be set via `model_type`. 168 See https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models 169 for an overview of the available models 170 171 Alternatively this function can also load a model from weights stored in a local filepath. 172 The corresponding file path is given via `checkpoint_path`. In this case `model_type` 173 must be given as the matching encoder architecture, e.g. "vit_b" if the weights are for 174 a SAM model with vit_b encoder. 175 176 By default the models are downloaded to a folder named 'micro_sam/models' 177 inside your default cache directory, eg: 178 * Mac: ~/Library/Caches/<AppName> 179 * Unix: ~/.cache/<AppName> or the value of the XDG_CACHE_HOME environment variable, if defined. 180 * Windows: C:\Users\<user>\AppData\Local\<AppAuthor>\<AppName>\Cache 181 See the pooch.os_cache() documentation for more details: 182 https://www.fatiando.org/pooch/latest/api/generated/pooch.os_cache.html 183 184 Args: 185 model_type: The Segment Anything model to use. Will use the 'vit_b_lm' model by default. 186 To get a list of all available model names you can call `micro_sam.v1.util.get_model_names`. 187 device: The device for the model. If 'None' is provided, will use GPU if available. 188 checkpoint_path: The path to a file with weights that should be used instead of using the 189 weights corresponding to `model_type`. If given, `model_type` must match the architecture 190 corresponding to the weight file. e.g. if you use weights for SAM with `vit_b` encoder 191 then `model_type` must be given as 'vit_b'. 192 return_sam: Return the sam model object as well as the predictor. By default, set to 'False'. 193 return_state: Return the unpickled checkpoint state. By default, set to 'False'. 194 peft_kwargs: Keyword arguments for th PEFT wrapper class. 195 If passed 'None', it does not initialize any parameter efficient finetuning. 196 flexible_load_checkpoint: Whether to adjust mismatching params while loading pretrained checkpoints. 197 By default, set to 'False'. 198 progress_bar_factory: A function to create a progress bar for the model download. 199 decoder_path: Optional path to weights for a segmentation decoder. If given and 200 `return_state=True`, the decoder state is added to the returned state as 201 'decoder_state'. This can be used to provide decoder-only weights that are 202 separate from the encoder checkpoint. 203 model_kwargs: Additional parameters necessary to initialize the Segment Anything model. 204 205 Returns: 206 The Segment Anything predictor. 207 """ 208 device = get_device(device) 209 210 # We support passing a local filepath to a checkpoint. 211 # In this case we do not download any weights but just use the local weight file, 212 # as it is, without copying it over anywhere or checking it's hashes. 213 214 # checkpoint_path has not been passed, we download a known model and derive the correct 215 # URL from the model_type. If the model_type is invalid pooch will raise an error. 216 _provided_checkpoint_path = checkpoint_path is not None 217 if checkpoint_path is None: 218 checkpoint_path, model_hash, downloaded_decoder_path = _download_sam_model(model_type, progress_bar_factory) 219 if decoder_path is None: 220 decoder_path = downloaded_decoder_path 221 222 # If checkpoint_path was passed, we use it instead of downloading a model. 223 else: 224 # Check if the file exists and raise an error otherwise. 225 # We can't check any hashes here, and we don't check if the file is actually a valid weight file. 226 # (If it isn't the model creation will fail below.) 227 if not os.path.exists(checkpoint_path): 228 raise ValueError(f"Checkpoint at '{checkpoint_path}' could not be found.") 229 model_hash = _compute_hash(checkpoint_path) 230 231 if decoder_path is not None and not os.path.exists(decoder_path): 232 raise ValueError(f"Decoder checkpoint at '{decoder_path}' could not be found.") 233 234 # Our fine-tuned model types have a suffix "_...". This suffix needs to be stripped 235 # before calling sam_model_registry. 236 abbreviated_model_type = model_type[:5] 237 if abbreviated_model_type not in SAM1_MODEL_TYPES: 238 raise ValueError(f"Invalid model_type: {abbreviated_model_type}. Expect one of {SAM1_MODEL_TYPES}") 239 if abbreviated_model_type == "vit_t" and not VIT_T_SUPPORT: 240 raise RuntimeError( 241 "'mobile_sam' is required for the vit-tiny. " 242 "You can install it via 'pip install git+https://github.com/ChaoningZhang/MobileSAM.git'" 243 ) 244 245 state, model_state = _load_checkpoint(checkpoint_path) 246 247 if _provided_checkpoint_path: 248 # To get the model weights, we prioritize having the correct 'checkpoint_path' over 'model_type' 249 # It is done to avoid strange parameter mismatch issues while incompatible model type and weights combination. 250 from micro_sam.v1.models.build_sam import _validate_model_type 251 _provided_model_type = _validate_model_type(model_state) 252 253 # Verify whether the 'abbreviated_model_type' matches the '_provided_model_type' 254 # Otherwise replace 'abbreviated_model_type' with the later. 255 if abbreviated_model_type != _provided_model_type: 256 # Printing the message below to avoid any filtering of warnings on user's end. 257 print( 258 f"CRITICAL WARNING: The chosen 'model_type' is '{abbreviated_model_type}', " 259 f"however the model checkpoint provided correspond to '{_provided_model_type}', which does not match. " 260 f"We internally switch the model type to the expected value, i.e. '{_provided_model_type}'. " 261 "However, please avoid mismatching combination of 'model_type' and 'checkpoint_path' in future." 262 ) 263 264 # Replace the extracted 'abbreviated_model_type' subjected to the model weights. 265 abbreviated_model_type = _provided_model_type 266 267 # Whether to update parameters necessary to initialize the model 268 if model_kwargs: # Checks whether model_kwargs have been provided or not 269 if abbreviated_model_type == "vit_t": 270 raise ValueError("'micro-sam' does not support changing the model parameters for 'mobile-sam'.") 271 sam = custom_models.sam_model_registry[abbreviated_model_type](**model_kwargs) 272 273 else: 274 sam = sam_model_registry[abbreviated_model_type]() 275 276 # Whether to use Parameter Efficient Finetuning methods to wrap around Segment Anything. 277 # Overwrites the SAM model by freezing the backbone and allow PEFT. 278 if peft_kwargs and isinstance(peft_kwargs, dict): 279 # NOTE: We bump out 'quantize' parameter, if found, as we do not quantize in inference. 280 peft_kwargs.pop("quantize", None) 281 282 if abbreviated_model_type == "vit_t": 283 raise ValueError("'micro-sam' does not support parameter efficient finetuning for 'mobile-sam'.") 284 285 sam = custom_models.peft_sam.PEFT_Sam(sam, **peft_kwargs).sam 286 # In case the model checkpoints have some issues when it is initialized with different parameters than default. 287 if flexible_load_checkpoint: 288 sam = _handle_checkpoint_loading(sam, model_state) 289 else: 290 sam.load_state_dict(model_state) 291 sam.to(device=device) 292 293 predictor = SamPredictor(sam) 294 predictor.model_type = abbreviated_model_type 295 predictor._hash = model_hash 296 predictor.model_name = model_type 297 predictor.checkpoint_path = checkpoint_path 298 299 # Add the decoder to the state if we have one and if the state is returned. 300 if decoder_path is not None and return_state: 301 state["decoder_state"] = torch.load(decoder_path, map_location=device, weights_only=False) 302 303 if return_sam and return_state: 304 return predictor, sam, state 305 if return_sam: 306 return predictor, sam 307 if return_state: 308 return predictor, state 309 return predictor
Get the Segment Anything Predictor.
This function will download the required model or load it from the cached weight file.
This location of the cache can be changed by setting the environment variable: MICROSAM_CACHEDIR.
The name of the requested model can be set via model_type.
See https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models
for an overview of the available models
Alternatively this function can also load a model from weights stored in a local filepath.
The corresponding file path is given via checkpoint_path. In this case model_type
must be given as the matching encoder architecture, e.g. "vit_b" if the weights are for
a SAM model with vit_b encoder.
By default the models are downloaded to a folder named 'micro_sam/models' inside your default cache directory, eg:
- Mac: ~/Library/Caches/
- Unix: ~/.cache/
or the value of the XDG_CACHE_HOME environment variable, if defined. - Windows: C:\Users<user>\AppData\Local<AppAuthor><AppName>\Cache See the pooch.os_cache() documentation for more details: https://www.fatiando.org/pooch/latest/api/generated/pooch.os_cache.html
Arguments:
- model_type: The Segment Anything model to use. Will use the 'vit_b_lm' model by default.
To get a list of all available model names you can call
micro_sam.v1.util.get_model_names. - device: The device for the model. If 'None' is provided, will use GPU if available.
- checkpoint_path: The path to a file with weights that should be used instead of using the
weights corresponding to
model_type. If given,model_typemust match the architecture corresponding to the weight file. e.g. if you use weights for SAM withvit_bencoder thenmodel_typemust be given as 'vit_b'. - return_sam: Return the sam model object as well as the predictor. By default, set to 'False'.
- return_state: Return the unpickled checkpoint state. By default, set to 'False'.
- peft_kwargs: Keyword arguments for th PEFT wrapper class. If passed 'None', it does not initialize any parameter efficient finetuning.
- flexible_load_checkpoint: Whether to adjust mismatching params while loading pretrained checkpoints. By default, set to 'False'.
- progress_bar_factory: A function to create a progress bar for the model download.
- decoder_path: Optional path to weights for a segmentation decoder. If given and
return_state=True, the decoder state is added to the returned state as 'decoder_state'. This can be used to provide decoder-only weights that are separate from the encoder checkpoint. - model_kwargs: Additional parameters necessary to initialize the Segment Anything model.
Returns:
The Segment Anything predictor.
345def export_custom_sam_model( 346 checkpoint_path: Union[str, os.PathLike], 347 model_type: str, 348 save_path: Union[str, os.PathLike], 349 with_segmentation_decoder: bool = False, 350 prefix: str = "sam.", 351) -> None: 352 """Export a finetuned Segment Anything Model to the standard model format. 353 354 The exported model can be used by the interactive annotation tools in `micro_sam.annotator`. 355 356 Args: 357 checkpoint_path: The path to the corresponding checkpoint if not in the default model folder. 358 model_type: The Segment Anything Model type corresponding to the checkpoint (vit_h, vit_b, vit_l or vit_t). 359 save_path: Where to save the exported model. 360 with_segmentation_decoder: Whether to store the decoder state in the model checkpoint as well. 361 If set to 'True', the model checkpoint will not be compatible with other tools besides 'micro-sam'. 362 prefix: The prefix to remove from the model parameter keys. 363 """ 364 state, model_state = _load_checkpoint(checkpoint_path=checkpoint_path) 365 model_state = OrderedDict([(k[len(prefix):] if k.startswith(prefix) else k, v) for k, v in model_state.items()]) 366 367 # Store the 'decoder_state' as well, if desired. 368 if with_segmentation_decoder: 369 if "decoder_state" not in state: 370 raise RuntimeError(f"'decoder_state' is not found in the model at '{checkpoint_path}'.") 371 decoder_state = state["decoder_state"] 372 save_state = {"model_state": model_state, "decoder_state": decoder_state} 373 else: 374 save_state = model_state 375 376 torch.save(save_state, save_path)
Export a finetuned Segment Anything Model to the standard model format.
The exported model can be used by the interactive annotation tools in micro_sam.annotator.
Arguments:
- checkpoint_path: The path to the corresponding checkpoint if not in the default model folder.
- model_type: The Segment Anything Model type corresponding to the checkpoint (vit_h, vit_b, vit_l or vit_t).
- save_path: Where to save the exported model.
- with_segmentation_decoder: Whether to store the decoder state in the model checkpoint as well. If set to 'True', the model checkpoint will not be compatible with other tools besides 'micro-sam'.
- prefix: The prefix to remove from the model parameter keys.
379def export_custom_qlora_model( 380 checkpoint_path: Optional[Union[str, os.PathLike]], 381 finetuned_path: Union[str, os.PathLike], 382 model_type: str, 383 save_path: Union[str, os.PathLike], 384) -> None: 385 """Export a finetuned Segment Anything Model, in QLoRA style, to LoRA-style checkpoint format. 386 387 The exported model can be used with the LoRA backbone by passing the relevant `peft_kwargs` to `get_sam_model`. 388 389 Args: 390 checkpoint_path: The path to the base foundation model from which the new model has been finetuned. 391 finetuned_path: The path to the new finetuned model, using QLoRA. 392 model_type: The Segment Anything Model type corresponding to the checkpoint. 393 save_path: Where to save the exported model. 394 """ 395 # Step 1: Get the base SAM model: used to start finetuning from. 396 _, sam = get_sam_model( 397 model_type=model_type, checkpoint_path=checkpoint_path, return_sam=True, 398 ) 399 400 # Step 2: Load the QLoRA-style finetuned model. 401 ft_state, ft_model_state = _load_checkpoint(finetuned_path) 402 403 # Step 3: Identify LoRA layers from QLoRA model. 404 # - differentiate between LoRA applied to the attention matrices and LoRA applied to the MLP layers. 405 # - then copy the LoRA layers from the QLoRA model to the new state dict 406 updated_model_state = {} 407 408 modified_attn_layers = set() 409 modified_mlp_layers = set() 410 411 for k, v in ft_model_state.items(): 412 if "blocks." in k: 413 layer_id = int(k.split("blocks.")[1].split(".")[0]) 414 if k.find("qkv.w_a_linear") != -1 or k.find("qkv.w_b_linear") != -1: 415 modified_attn_layers.add(layer_id) 416 updated_model_state[k] = v 417 if k.find("mlp.w_a_linear") != -1 or k.find("mlp.w_b_linear") != -1: 418 modified_mlp_layers.add(layer_id) 419 updated_model_state[k] = v 420 421 # Step 4: Next, we get all the remaining parameters from the base SAM model. 422 for k, v in sam.state_dict().items(): 423 if "blocks." in k: 424 layer_id = int(k.split("blocks.")[1].split(".")[0]) 425 if k.find("attn.qkv.") != -1: 426 if layer_id in modified_attn_layers: # We have LoRA in QKV layers, so we need to modify the key 427 k = k.replace("qkv", "qkv.qkv_proj") 428 elif k.find("mlp") != -1 and k.find("image_encoder") != -1: 429 if layer_id in modified_mlp_layers: # We have LoRA in MLP layers, so we need to modify the key 430 k = k.replace("mlp.", "mlp.mlp_layer.") 431 updated_model_state[k] = v 432 433 # Step 5: Finally, we replace the old model state with the new one (to retain other relevant stuff) 434 ft_state['model_state'] = updated_model_state 435 436 # Step 6: Store the new "state" to "save_path" 437 torch.save(ft_state, save_path)
Export a finetuned Segment Anything Model, in QLoRA style, to LoRA-style checkpoint format.
The exported model can be used with the LoRA backbone by passing the relevant peft_kwargs to get_sam_model.
Arguments:
- checkpoint_path: The path to the base foundation model from which the new model has been finetuned.
- finetuned_path: The path to the new finetuned model, using QLoRA.
- model_type: The Segment Anything Model type corresponding to the checkpoint.
- save_path: Where to save the exported model.
841def precompute_image_embeddings( 842 predictor: SamPredictor, 843 input_: np.ndarray, 844 save_path: Optional[Union[str, os.PathLike]] = None, 845 lazy_loading: bool = False, 846 ndim: Optional[int] = None, 847 tile_shape: Optional[Tuple[int, int]] = None, 848 halo: Optional[Tuple[int, int]] = None, 849 verbose: bool = True, 850 batch_size: Optional[int] = 1, 851 mask: Optional[np.typing.ArrayLike] = None, 852 pbar_init: Optional[callable] = None, 853 pbar_update: Optional[callable] = None, 854) -> ImageEmbeddings: 855 """Compute the image embeddings (output of the encoder) for the input. 856 857 If 'save_path' is given the embeddings will be loaded/saved in a zarr container. 858 859 Args: 860 predictor: The Segment Anything predictor. 861 input_: The input data. Can be 2 or 3 dimensional, corresponding to an image, volume or timeseries. 862 save_path: Path to save the embeddings in a zarr container. 863 By default, set to 'None', i.e. the computed embeddings will not be stored locally. 864 lazy_loading: Whether to load all embeddings into memory or return an 865 object to load them on demand when required. This only has an effect if 'save_path' is given 866 and if the input is 3 dimensional. By default, set to 'False'. 867 ndim: The dimensionality of the data. If not given will be deduced from the input data. 868 By default, set to 'None', i.e. will be computed from the provided `input_`. 869 tile_shape: Shape of tiles for tiled prediction. By default prediction is run without tiling. 870 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 871 verbose: Whether to be verbose in the computation. By default, set to 'True'. 872 batch_size: The batch size for precomputing image embeddings over tiles (or planes). By default, set to '1'. 873 Pass None to leave the choice to the backend, which is a single tile / plane for SAM1. 874 mask: An optional mask to define areas that are ignored in the computation. 875 The mask will be used within tiled embedding computation and tiles that don't contain any foreground 876 in the mask will be excluded from the computation. It does not have any effect for non-tiled embeddings. 877 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 878 Can be used together with pbar_update to handle napari progress bar in other thread. 879 To enable using this function within a threadworker. 880 pbar_update: Callback to update an external progress bar. 881 882 Returns: 883 The image embeddings. 884 """ 885 ndim = input_.ndim if ndim is None else ndim 886 # SAM1 has no per-device batch-size lookup, so the automatic choice is the single tile / slice. 887 batch_size = 1 if batch_size is None else batch_size 888 889 # Handle the embedding save_path. 890 # We don't have a save path, open in memory zarr file to hold tiled embeddings. 891 if save_path is None: 892 f = _open_embeddings(None) 893 894 # We have a save path and it already exists. Embeddings will be loaded from it, 895 # check that the saved embeddings in there match the parameters of the function call. 896 elif os.path.exists(save_path): 897 f = _open_embeddings(save_path, mode="a") 898 if _check_saved_embeddings(input_, predictor, f, save_path, tile_shape, halo): 899 # Stale embeddings (model or tiling changed): truncate and recompute, overwriting them. 900 f = _open_embeddings(save_path, mode="w") 901 902 # We have a save path and it does not exist yet. Create the zarr file to which the 903 # embeddings will then be saved. 904 else: 905 f = _open_embeddings(save_path, mode="a") 906 907 _, pbar_init, pbar_update, pbar_close = handle_pbar(verbose, pbar_init, pbar_update) 908 909 if ndim == 2 and tile_shape is None: 910 embeddings = _compute_2d(input_, predictor, f, save_path, pbar_init, pbar_update) 911 elif ndim == 2 and tile_shape is not None: 912 embeddings = _compute_tiled_2d( 913 input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask=mask 914 ) 915 elif ndim == 3 and tile_shape is None: 916 embeddings = _compute_3d(input_, predictor, f, save_path, lazy_loading, pbar_init, pbar_update, batch_size) 917 elif ndim == 3 and tile_shape is not None: 918 embeddings = _compute_tiled_3d( 919 input_, predictor, tile_shape, halo, f, pbar_init, pbar_update, batch_size, mask=mask 920 ) 921 else: 922 raise ValueError(f"Invalid dimesionality {input_.ndim}, expect 2 or 3 dim data.") 923 924 pbar_close() 925 return embeddings
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 Segment Anything predictor.
- input_: The input data. Can be 2 or 3 dimensional, corresponding to an image, volume or timeseries.
- save_path: Path to save the embeddings in a zarr container. By default, set to 'None', i.e. the computed embeddings will not be stored locally.
- lazy_loading: Whether to load all embeddings into memory or return an object to load them on demand when required. This only has an effect if 'save_path' is given and if the input is 3 dimensional. By default, set to 'False'.
- ndim: The dimensionality of the data. If not given will be deduced from the input data.
By default, set to 'None', i.e. will be computed from the provided
input_. - tile_shape: Shape of tiles for tiled prediction. By default prediction is run without tiling.
- halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
- verbose: Whether to be verbose in the computation. By default, set to 'True'.
- batch_size: The batch size for precomputing image embeddings over tiles (or planes). By default, set to '1'. Pass None to leave the choice to the backend, which is a single tile / plane for SAM1.
- mask: An optional mask to define areas that are ignored in the computation. The mask will be used within tiled embedding computation and tiles that don't contain any foreground in the mask will be excluded from the computation. It does not have any effect for non-tiled embeddings.
- pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. Can be used together with pbar_update to handle napari progress bar in other thread. To enable using this function within a threadworker.
- pbar_update: Callback to update an external progress bar.
Returns:
The image embeddings.
928def set_precomputed( 929 predictor: SamPredictor, image_embeddings: ImageEmbeddings, i: Optional[int] = None, tile_id: Optional[int] = None, 930) -> SamPredictor: 931 """Set the precomputed image embeddings for a predictor. 932 933 Args: 934 predictor: The Segment Anything predictor. 935 image_embeddings: The precomputed image embeddings computed by `precompute_image_embeddings`. 936 i: Index for the image data. Required if `image` has three spatial dimensions 937 or a time dimension and two spatial dimensions. 938 tile_id: Index for the tile. This is required if the embeddings are tiled. 939 940 Returns: 941 The predictor with set features. 942 """ 943 if tile_id is not None: 944 tile_features = image_embeddings["features"][str(tile_id)] 945 tile_image_embeddings = { 946 "features": tile_features, 947 "input_size": tile_features.attrs["input_size"], 948 "original_size": tile_features.attrs["original_size"] 949 } 950 return set_precomputed(predictor, tile_image_embeddings, i=i) 951 952 device = predictor.device 953 features = image_embeddings["features"] 954 assert features.ndim in (4, 5), f"{features.ndim}" 955 if features.ndim == 5 and i is None: 956 raise ValueError("The data is 3D so an index i is needed.") 957 elif features.ndim == 4 and i is not None: 958 raise ValueError("The data is 2D so an index is not needed.") 959 960 if i is None: 961 predictor.features = features.to(device) if torch.is_tensor(features) else \ 962 torch.from_numpy(features[:]).to(device) 963 else: 964 predictor.features = features[i].to(device) if torch.is_tensor(features) else \ 965 torch.from_numpy(features[i]).to(device) 966 967 predictor.original_size = image_embeddings["original_size"] 968 predictor.input_size = image_embeddings["input_size"] 969 predictor.is_image_set = True 970 971 return predictor
Set the precomputed image embeddings for a predictor.
Arguments:
- predictor: The Segment Anything predictor.
- image_embeddings: The precomputed image embeddings computed by
precompute_image_embeddings. - i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - tile_id: Index for the tile. This is required if the embeddings are tiled.
Returns:
The predictor with set features.