micro_sam.v1.bioimageio.model_export
1import os 2import shutil 3import tempfile 4from pathlib import Path 5from typing import Optional, Union 6 7import xarray 8import numpy as np 9import matplotlib.pyplot as plt 10from scipy.ndimage import binary_dilation, binary_erosion 11 12import bioimageio.core 13import bioimageio.spec.model.v0_5 as spec 14from bioimageio.spec import save_bioimageio_package 15from bioimageio.core.digest_spec import create_sample_for_model 16 17import torch 18 19from ... import util 20from ..util import models 21from .predictor_adaptor import PredictorAdaptor 22from ...prompt_generators import PointAndBoxPromptGenerator 23from ..prompt_based_segmentation import _compute_logits_from_mask 24from ..evaluation.model_comparison import _enhance_image, _overlay_outline, _overlay_box 25 26 27DEFAULTS = { 28 "authors": [ 29 spec.Author(name="Anwai Archit", affiliation="University Goettingen", github_user="anwai98"), 30 spec.Author(name="Constantin Pape", affiliation="University Goettingen", github_user="constantinpape"), 31 ], 32 "description": "Finetuned Segment Anything Model for Microscopy", 33 "cite": [ 34 spec.CiteEntry( 35 text="Archit et al. Segment Anything for Microscopy", 36 doi=spec.Doi("10.1038/s41592-024-02580-4") 37 ), 38 ], 39 "tags": ["segment-anything", "instance-segmentation"], 40} 41 42# Reference: https://github.com/bioimage-io/spec-bioimage-io/commit/39d343681d427ec93cf69eef7597d9eb9678deb1#diff-0bbdaa8196fa31f945afabcf04a4295ff098f1f24400ef9e59b0f684d411905eL269 # noqa 43# We had this parameter in bioimageio.spec. This has been removed. We just make a copy of the same parameter. 44ARBITRARY_SIZE = spec.ParameterizedSize(min=1, step=1) 45 46 47def _get_architecture_model_type(model_type): 48 # Derived models use their base SAM architecture. 49 return model_type[:5] 50 51 52def _create_test_inputs_and_outputs(image, labels, model_type, checkpoint_path, tmp_dir, with_decoder): 53 54 predictor = PredictorAdaptor(model_type=_get_architecture_model_type(model_type)) 55 predictor.load_state_dict(torch.load(checkpoint_path, map_location="cpu", weights_only=True)) 56 # Match the evaluation mode that BioImageIO uses. 57 predictor.eval() 58 59 input_ = util._to_image(image).transpose(2, 0, 1)[None] 60 image_path = os.path.join(tmp_dir, "input.npy") 61 np.save(image_path, input_) 62 63 if with_decoder: 64 # Test automatic instance segmentation through prompt-free inference. 65 with torch.no_grad(): 66 masks, scores, embeddings = predictor(image=torch.from_numpy(input_)) 67 if masks.shape[1] == 0: 68 raise RuntimeError( 69 "Automatic instance segmentation did not find any objects in the test image. " 70 "The exported model would fail its test procedure, which requires at least one object " 71 "in the mask output. Please use a test image in which the model finds instances." 72 ) 73 inputs = {"image": image_path} 74 else: 75 # For now we just generate a single box prompt here, but we could also generate more input prompts. 76 generator = PointAndBoxPromptGenerator( 77 n_positive_points=1, 78 n_negative_points=2, 79 dilation_strength=2, 80 get_point_prompts=True, 81 get_box_prompts=True, 82 ) 83 centers, bounding_boxes = util.get_centers_and_bounding_boxes(labels) 84 masks = util.segmentation_to_one_hot(labels.astype("int64"), segmentation_ids=[1, 2]) # type: ignore 85 point_prompts, point_labels, box_prompts, _ = generator(masks, [bounding_boxes[1], bounding_boxes[2]]) 86 87 box_prompts = box_prompts.numpy()[None] 88 point_prompts = point_prompts.numpy()[None] 89 point_labels = point_labels.numpy()[None] 90 91 # Generate logits from the two 92 mask_prompts = np.stack( 93 [_compute_logits_from_mask(labels == 1), _compute_logits_from_mask(labels == 2)] 94 )[None] 95 96 with torch.no_grad(): 97 masks, scores, embeddings = predictor( 98 image=torch.from_numpy(input_), 99 embeddings=None, 100 box_prompts=torch.from_numpy(box_prompts), 101 point_prompts=torch.from_numpy(point_prompts), 102 point_labels=torch.from_numpy(point_labels), 103 mask_prompts=torch.from_numpy(mask_prompts), 104 ) 105 106 box_prompt_path = os.path.join(tmp_dir, "box_prompts.npy") 107 point_prompt_path = os.path.join(tmp_dir, "point_prompts.npy") 108 point_label_path = os.path.join(tmp_dir, "point_labels.npy") 109 mask_prompt_path = os.path.join(tmp_dir, "mask_prompts.npy") 110 np.save(box_prompt_path, box_prompts.astype("int64")) 111 np.save(point_prompt_path, point_prompts) 112 np.save(point_label_path, point_labels) 113 np.save(mask_prompt_path, mask_prompts) 114 115 inputs = { 116 "image": image_path, 117 "box_prompts": box_prompt_path, 118 "point_prompts": point_prompt_path, 119 "point_labels": point_label_path, 120 "mask_prompts": mask_prompt_path, 121 } 122 123 mask_path = os.path.join(tmp_dir, "mask.npy") 124 score_path = os.path.join(tmp_dir, "scores.npy") 125 embed_path = os.path.join(tmp_dir, "embeddings.npy") 126 np.save(mask_path, masks.numpy()) 127 np.save(score_path, scores.numpy()) 128 np.save(embed_path, embeddings.numpy()) 129 130 outputs = {"mask": mask_path, "score": score_path, "embeddings": embed_path} 131 return inputs, outputs 132 133 134def _write_documentation(doc, model_type, tmp_dir): 135 tmp_doc_path = os.path.join(tmp_dir, "documentation.md") 136 137 if doc is None: 138 with open(tmp_doc_path, "w") as f: 139 f.write("# Segment Anything for Microscopy\n") 140 f.write("We extend Segment Anything, a vision foundation model for image segmentation ") 141 f.write("by training specialized models for microscopy data.\n") 142 return tmp_doc_path 143 144 elif os.path.exists(doc): 145 return doc 146 147 else: 148 with open(tmp_doc_path, "w") as f: 149 f.write(doc) 150 return tmp_doc_path 151 152 153def _get_checkpoint(model_type, checkpoint_path, tmp_dir): 154 # If we don't have a checkpoint we get the corresponding model from the registry. 155 if checkpoint_path is None: 156 model_registry = models() 157 checkpoint_path = model_registry.fetch(model_type) 158 decoder_name = f"{model_type}_decoder" 159 decoder_path = model_registry.fetch(decoder_name) if decoder_name in model_registry.registry else None 160 return checkpoint_path, decoder_path 161 162 # Otherwise we have to load the checkpoint to see if it is the state dict of an encoder, 163 # or the checkpoint for a custom SAM model. 164 state, model_state = util._load_checkpoint(checkpoint_path) 165 166 if "model_state" in state: # This is a finetuning checkpoint -> we have to resave the state. 167 new_checkpoint_path = os.path.join(tmp_dir, f"{model_type}.pt") 168 torch.save(model_state, new_checkpoint_path) 169 170 # We may also have an instance segmentation decoder in that case. 171 # If we have it we also resave this one and return it. 172 if "decoder_state" in state: 173 decoder_path = os.path.join(tmp_dir, f"{model_type}_decoder.pt") 174 decoder_state = state["decoder_state"] 175 torch.save(decoder_state, decoder_path) 176 else: 177 decoder_path = None 178 179 return new_checkpoint_path, decoder_path 180 181 else: # This is a SAM encoder state -> we don't have to resave. 182 return checkpoint_path, None 183 184 185def _get_weight_checkpoint(model_type, checkpoint_path, decoder_path, tmp_dir): 186 """Combine the SAM and decoder states for the exported architecture.""" 187 if decoder_path is None: 188 return checkpoint_path 189 190 weight_dir = os.path.join(tmp_dir, "combined_weights") 191 os.makedirs(weight_dir, exist_ok=True) 192 weight_path = os.path.join(weight_dir, f"{model_type}.pt") 193 194 model_state = torch.load(checkpoint_path, map_location="cpu", weights_only=True) 195 decoder_state = torch.load(decoder_path, map_location="cpu", weights_only=True) 196 torch.save({"model_state": model_state, "decoder_state": decoder_state}, weight_path) 197 return weight_path 198 199 200def _get_decoder_attachment(model_type, decoder_path, tmp_dir): 201 # Registry decoder files do not have an extension. 202 attachment_name = f"{_get_architecture_model_type(model_type)}_decoder.pt" 203 if os.path.basename(decoder_path) == attachment_name: 204 return decoder_path 205 attachment_path = os.path.join(tmp_dir, attachment_name) 206 shutil.copyfile(decoder_path, attachment_path) 207 return attachment_path 208 209 210# TODO: Update this with our latest yaml file updates. 211def _write_dependencies(dependency_file, require_mobile_sam, require_micro_sam): 212 if require_micro_sam: 213 content = """name: sam 214channels: 215 - conda-forge 216dependencies: 217 - micro_sam""" 218 else: 219 content = """name: sam 220channels: 221 - pytorch 222 - conda-forge 223dependencies: 224 - segment-anything""" 225 if require_mobile_sam: 226 content += """ 227 - timm 228 - pip: 229 - git+https://github.com/ChaoningZhang/MobileSAM.git""" 230 with open(dependency_file, "w") as f: 231 f.write(content) 232 233 234def _generate_covers(input_paths, result_paths, tmp_dir, with_decoder): 235 image = np.load(input_paths["image"]).squeeze() 236 mask = np.load(result_paths["mask"]) 237 238 # create the image overlay 239 if image.ndim == 2: 240 overlay = np.stack([image, image, image]).transpose((1, 2, 0)) 241 elif image.shape[0] == 3: 242 overlay = image.transpose((1, 2, 0)) 243 else: 244 overlay = image 245 overlay = _enhance_image(overlay.astype("float32")) 246 247 if with_decoder: 248 # Outline all automatic instances. 249 overlay = _overlay_outline(overlay, mask[0, :, 0].max(axis=0), outline_dilation=2) 250 else: 251 # overlay the mask as outline 252 overlay = _overlay_outline(overlay, mask[0, 0, 0], outline_dilation=2) 253 254 # overlay the bounding box prompt 255 prompts = np.load(input_paths["box_prompts"]) 256 prompt = prompts[0, 0][[1, 0, 3, 2]] 257 prompt = np.array([prompt[:2], prompt[2:]]) 258 overlay = _overlay_box(overlay, prompt, outline_dilation=4) 259 260 # write the cover image 261 fig, ax = plt.subplots(1) 262 ax.axis("off") 263 ax.imshow(overlay.astype("uint8")) 264 cover_path = os.path.join(tmp_dir, "cover.jpeg") 265 plt.savefig(cover_path, bbox_inches="tight") 266 plt.close() 267 268 covers = [cover_path] 269 return covers 270 271 272def _check_model(model_description, input_paths, result_paths, with_decoder): 273 image = xarray.DataArray(np.load(input_paths["image"]), dims=("batch", "channel", "y", "x")) 274 275 if with_decoder: 276 # Check automatic instance segmentation against its reference outputs. 277 mask = np.load(result_paths["mask"]) 278 scores = np.load(result_paths["score"]) 279 embeddings = np.load(result_paths["embeddings"]) 280 281 with bioimageio.core.create_prediction_pipeline(model_description, devices=["cpu"]) as pp: 282 sample = create_sample_for_model(model=model_description, inputs={"image": image}) 283 prediction = pp.predict_sample_without_blocking(sample) 284 assert np.allclose(mask, prediction.members["masks"].data) 285 assert np.allclose(scores, prediction.members["scores"].data) 286 assert np.allclose(embeddings, prediction.members["embeddings"].data) 287 return 288 289 # Load inputs. 290 embeddings = xarray.DataArray(np.load(result_paths["embeddings"]), dims=("batch", "channel", "y", "x")) 291 box_prompts = xarray.DataArray(np.load(input_paths["box_prompts"]), dims=("batch", "object", "channel")) 292 point_prompts = xarray.DataArray( 293 np.load(input_paths["point_prompts"]), dims=("batch", "object", "point", "channel") 294 ) 295 point_labels = xarray.DataArray(np.load(input_paths["point_labels"]), dims=("batch", "object", "point")) 296 mask_prompts = xarray.DataArray(np.load(input_paths["mask_prompts"]), dims=("batch", "object", "channel", "y", "x")) 297 298 # Load outputs. 299 mask = np.load(result_paths["mask"]) 300 301 # Match the device used to generate the reference outputs. 302 with bioimageio.core.create_prediction_pipeline(model_description, devices=["cpu"]) as pp: 303 304 # Check with all prompts. We only check the result for this setting, 305 # because this was used to generate the test data. 306 sample = create_sample_for_model( 307 model=model_description, 308 inputs={ 309 "image": image, 310 "box_prompts": box_prompts, 311 "point_prompts": point_prompts, 312 "point_labels": point_labels, 313 "mask_prompts": mask_prompts, 314 "embeddings": embeddings, 315 }, 316 ) 317 prediction = pp.predict_sample_without_blocking(sample) 318 319 predicted_mask = prediction.members["masks"].data 320 assert predicted_mask.shape == mask.shape 321 # The masks are binary and thresholded at logit 0 right after a bilinear upsample, so the 322 # export round-trip (direct PyTorch vs the reloaded bioimage.io pipeline) can flip pixels in 323 # a thin band along the mask boundary due to platform-level float / interpolation differences 324 # (notably on macOS/arm64). Such boundary flips are expected. Only a disagreement deeper than 325 # this band indicates a genuinely wrong export. So we ignore disagreements within 'band' px of 326 # the reference mask boundary and require the rest to match exactly. 327 mask_bool, predicted_bool = mask.astype(bool), predicted_mask.astype(bool) 328 disagree = np.logical_xor(mask_bool, predicted_bool) 329 330 band = 2 331 # Structuring element spanning only the trailing (y, x) axes, so the band stays within each 332 # spatial plane and does not bleed across the batch/object/channel axes. 333 structure = np.ones((1,) * (mask_bool.ndim - 2) + (3, 3), dtype=bool) 334 boundary = mask_bool ^ binary_erosion(mask_bool, structure=structure) 335 boundary_band = binary_dilation(boundary, structure=structure, iterations=band) 336 337 interior_disagree = int(np.logical_and(disagree, ~boundary_band).sum()) 338 assert interior_disagree == 0, ( 339 f"Exported mask mismatch: {interior_disagree} pixels differ away from the mask boundary " 340 f"({int(disagree.sum())} differing in total)." 341 ) 342 343 # Run the checks with partial prompts. 344 prompt_kwargs = [ 345 # With boxes. 346 {"box_prompts": box_prompts}, 347 # With point prompts. 348 {"point_prompts": point_prompts, "point_labels": point_labels}, 349 # With masks. 350 {"mask_prompts": mask_prompts}, 351 # With boxes and points. 352 {"box_prompts": box_prompts, "point_prompts": point_prompts, "point_labels": point_labels}, 353 # With boxes and masks. 354 {"box_prompts": box_prompts, "mask_prompts": mask_prompts}, 355 # With points and masks. 356 {"mask_prompts": mask_prompts, "point_prompts": point_prompts, "point_labels": point_labels}, 357 ] 358 359 for kwargs in prompt_kwargs: 360 sample = create_sample_for_model( 361 model=model_description, inputs={"image": image, "embeddings": embeddings, **kwargs}, 362 ) 363 prediction = pp.predict_sample_without_blocking(sample) 364 predicted_mask = prediction.members["masks"].data 365 assert predicted_mask.shape == mask.shape 366 367 # Use a fresh pipeline to verify image-only inference. 368 with bioimageio.core.create_prediction_pipeline(model_description, devices=["cpu"]) as pp: 369 sample = create_sample_for_model(model=model_description, inputs={"image": image}) 370 prediction = pp.predict_sample_without_blocking(sample) 371 predicted_mask = prediction.members["masks"].data 372 # AIS may return no objects. 373 assert predicted_mask.ndim == 5 374 assert predicted_mask.shape[-2:] == mask.shape[-2:] 375 376 377def _regenerate_reference_outputs(model_description, input_paths, result_paths): 378 """Regenerate reference outputs through the packaged model. 379 380 This avoids numerical differences between direct calls and BioImageIO calls. 381 """ 382 from bioimageio.core.digest_spec import get_test_input_sample 383 384 sample = get_test_input_sample(model_description) 385 # Keep reference generation deterministic across CI runners. 386 with bioimageio.core.create_prediction_pipeline(model_description, devices=["cpu"]) as pp: 387 pp.apply_preprocessing(sample) 388 prediction = pp.predict_sample_without_blocking( 389 sample, 390 skip_preprocessing=True, 391 skip_postprocessing=True, 392 skip_input_padding=True, 393 skip_output_cropping=True, 394 ) 395 pp.apply_postprocessing(prediction) 396 np.save(result_paths["mask"], np.asarray(prediction.members["masks"].data).astype("uint8")) 397 np.save(result_paths["score"], np.asarray(prediction.members["scores"].data).astype("float32")) 398 np.save(result_paths["embeddings"], np.asarray(prediction.members["embeddings"].data).astype("float32")) 399 400 401def _build_model_description( 402 name, input_paths, result_paths, weight_descriptions, doc_path, covers, extra_kwargs, with_decoder, **kwargs 403): 404 # Rebuild after reference generation to update the test tensor hashes. 405 if with_decoder: 406 # Prevent BioImageIO size probes from cropping instances. 407 test_image_shape = np.load(input_paths["image"], mmap_mode="r").shape 408 image_y_size = spec.ParameterizedSize(min=test_image_shape[-2], step=1) 409 image_x_size = spec.ParameterizedSize(min=test_image_shape[-1], step=1) 410 else: 411 image_y_size = image_x_size = ARBITRARY_SIZE 412 413 input_descriptions = [ 414 # First input: the image data. 415 spec.InputTensorDescr( 416 id=spec.TensorId("image"), 417 axes=[ 418 spec.BatchAxis(size=1), 419 # NOTE: to support 1 and 3 channels we can add another preprocessing. 420 # Best solution: Have a pre-processing for this! (1C -> RGB) 421 spec.ChannelAxis(channel_names=[spec.Identifier(cname) for cname in "RGB"]), 422 spec.SpaceInputAxis(id=spec.AxisId("y"), size=image_y_size), 423 spec.SpaceInputAxis(id=spec.AxisId("x"), size=image_x_size), 424 ], 425 test_tensor=spec.FileDescr(source=input_paths["image"]), 426 data=spec.IntervalOrRatioDataDescr(type="uint8") 427 ), 428 ] 429 430 # Decoder exports keep only the image input to test automatic instance segmentation. 431 if not with_decoder: 432 input_descriptions += [ 433 # Second input: the box prompts (optional) 434 spec.InputTensorDescr( 435 id=spec.TensorId("box_prompts"), 436 optional=True, 437 axes=[ 438 spec.BatchAxis(size=1), 439 spec.IndexInputAxis( 440 id=spec.AxisId("object"), 441 size=ARBITRARY_SIZE 442 ), 443 spec.ChannelAxis(channel_names=[spec.Identifier(bname) for bname in "hwxy"]), 444 ], 445 test_tensor=spec.FileDescr(source=input_paths["box_prompts"]), 446 data=spec.IntervalOrRatioDataDescr(type="int64") 447 ), 448 449 # Third input: the point prompt coordinates (optional) 450 spec.InputTensorDescr( 451 id=spec.TensorId("point_prompts"), 452 optional=True, 453 axes=[ 454 spec.BatchAxis(size=1), 455 spec.IndexInputAxis( 456 id=spec.AxisId("object"), 457 size=ARBITRARY_SIZE 458 ), 459 spec.IndexInputAxis( 460 id=spec.AxisId("point"), 461 size=ARBITRARY_SIZE 462 ), 463 spec.ChannelAxis(channel_names=[spec.Identifier(bname) for bname in "xy"]), 464 ], 465 test_tensor=spec.FileDescr(source=input_paths["point_prompts"]), 466 data=spec.IntervalOrRatioDataDescr(type="int64") 467 ), 468 469 # Fourth input: the point prompt labels (optional) 470 spec.InputTensorDescr( 471 id=spec.TensorId("point_labels"), 472 optional=True, 473 axes=[ 474 spec.BatchAxis(size=1), 475 spec.IndexInputAxis( 476 id=spec.AxisId("object"), 477 size=ARBITRARY_SIZE 478 ), 479 spec.IndexInputAxis( 480 id=spec.AxisId("point"), 481 size=ARBITRARY_SIZE 482 ), 483 ], 484 test_tensor=spec.FileDescr(source=input_paths["point_labels"]), 485 data=spec.IntervalOrRatioDataDescr(type="int64") 486 ), 487 488 # Fifth input: the mask prompts (optional) 489 spec.InputTensorDescr( 490 id=spec.TensorId("mask_prompts"), 491 optional=True, 492 axes=[ 493 spec.BatchAxis(size=1), 494 spec.IndexInputAxis( 495 id=spec.AxisId("object"), 496 size=ARBITRARY_SIZE 497 ), 498 spec.ChannelAxis(channel_names=["channel"]), 499 spec.SpaceInputAxis(id=spec.AxisId("y"), size=256), 500 spec.SpaceInputAxis(id=spec.AxisId("x"), size=256), 501 ], 502 test_tensor=spec.FileDescr(source=input_paths["mask_prompts"]), 503 data=spec.IntervalOrRatioDataDescr(type="float32") 504 ), 505 506 # Sixth input: the image embeddings (optional) 507 spec.InputTensorDescr( 508 id=spec.TensorId("embeddings"), 509 optional=True, 510 axes=[ 511 spec.BatchAxis(size=1), 512 # NOTE: we currently have to specify all the channel names 513 # (It would be nice to also support size) 514 spec.ChannelAxis(channel_names=[spec.Identifier(f"c{i}") for i in range(256)]), 515 spec.SpaceInputAxis(id=spec.AxisId("y"), size=64), 516 spec.SpaceInputAxis(id=spec.AxisId("x"), size=64), 517 ], 518 test_tensor=spec.FileDescr(source=result_paths["embeddings"]), 519 data=spec.IntervalOrRatioDataDescr(type="float32") 520 ), 521 ] 522 523 output_descriptions = [ 524 # First output: The mask predictions. 525 spec.OutputTensorDescr( 526 id=spec.TensorId("masks"), 527 axes=[ 528 spec.BatchAxis(size=1), 529 # NOTE: we use the data dependent size here to avoid dependency on optional inputs 530 spec.IndexOutputAxis( 531 id=spec.AxisId("object"), size=spec.DataDependentSize(), 532 ), 533 # NOTE: this could be a 3 once we use multi-masking 534 spec.ChannelAxis(channel_names=[spec.Identifier("mask")]), 535 spec.SpaceOutputAxis( 536 id=spec.AxisId("y"), 537 size=spec.SizeReference( 538 tensor_id=spec.TensorId("image"), axis_id=spec.AxisId("y"), 539 ) 540 ), 541 spec.SpaceOutputAxis( 542 id=spec.AxisId("x"), 543 size=spec.SizeReference( 544 tensor_id=spec.TensorId("image"), axis_id=spec.AxisId("x"), 545 ) 546 ) 547 ], 548 data=spec.IntervalOrRatioDataDescr(type="uint8"), 549 test_tensor=spec.FileDescr(source=result_paths["mask"]) 550 ), 551 552 # The score predictions 553 spec.OutputTensorDescr( 554 id=spec.TensorId("scores"), 555 axes=[ 556 spec.BatchAxis(size=1), 557 # NOTE: we use the data dependent size here to avoid dependency on optional inputs 558 spec.IndexOutputAxis( 559 id=spec.AxisId("object"), size=spec.DataDependentSize(), 560 ), 561 # NOTE: this could be a 3 once we use multi-masking 562 spec.ChannelAxis(channel_names=[spec.Identifier("mask")]), 563 ], 564 data=spec.IntervalOrRatioDataDescr(type="float32"), 565 test_tensor=spec.FileDescr(source=result_paths["score"]) 566 ), 567 568 # The image embeddings 569 spec.OutputTensorDescr( 570 id=spec.TensorId("embeddings"), 571 axes=[ 572 spec.BatchAxis(size=1), 573 spec.ChannelAxis(channel_names=[spec.Identifier(f"c{i}") for i in range(256)]), 574 spec.SpaceOutputAxis(id=spec.AxisId("y"), size=64), 575 spec.SpaceOutputAxis(id=spec.AxisId("x"), size=64), 576 ], 577 data=spec.IntervalOrRatioDataDescr(type="float32"), 578 test_tensor=spec.FileDescr(source=result_paths["embeddings"]) 579 ) 580 ] 581 582 return spec.ModelDescr( 583 name=name, 584 inputs=input_descriptions, 585 outputs=output_descriptions, 586 weights=weight_descriptions, 587 description=kwargs.get("description", DEFAULTS["description"]), 588 authors=kwargs.get("authors", DEFAULTS["authors"]), 589 cite=kwargs.get("cite", DEFAULTS["cite"]), 590 license=spec.LicenseId("CC-BY-4.0"), 591 documentation=spec.FileDescr(source=Path(doc_path)), 592 git_repo=spec.HttpUrl("https://github.com/computational-cell-analytics/micro-sam"), 593 tags=kwargs.get("tags", DEFAULTS["tags"]), 594 covers=[spec.FileDescr(source=Path(cover)) for cover in covers], 595 **extra_kwargs, 596 config=spec.Config( 597 bioimageio=spec.BioimageioConfig( 598 # Allow minor numerical differences in raw embeddings across devices. 599 reproducibility_tolerance=[ 600 spec.ReproducibilityTolerance( 601 mismatched_elements_per_million=1000, 602 output_ids=[spec.TensorId("embeddings")], 603 ) 604 ], 605 ), 606 ), 607 ) 608 609 610def export_sam_model( 611 image: np.ndarray, 612 label_image: np.ndarray, 613 model_type: str, 614 name: str, 615 output_path: Union[str, os.PathLike], 616 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 617 **kwargs 618) -> None: 619 """Export SAM model to BioImage.IO model format. 620 621 The exported model can be uploaded to [bioimage.io](https://bioimage.io/#/) and 622 be used in tools that support the BioImage.IO model format. 623 624 Models with a decoder expose only the image input. 625 Their test outputs use automatic instance segmentation. 626 Use micro_sam directly for prompted segmentation with these models. 627 Models without a decoder expose the interactive prompt inputs. 628 629 Args: 630 image: The image for generating test data. 631 label_image: The segmentation corresponding to `image`. 632 It is used to derive prompt inputs for the model. 633 model_type: The type of the SAM model. 634 name: The name of the exported model. 635 output_path: Where the exported model is saved. 636 checkpoint_path: Optional checkpoint for loading the SAM model. 637 """ 638 with tempfile.TemporaryDirectory() as tmp_dir: 639 checkpoint_path, decoder_path = _get_checkpoint(model_type, checkpoint_path, tmp_dir) 640 with_decoder = decoder_path is not None 641 weight_path = _get_weight_checkpoint(model_type, checkpoint_path, decoder_path, tmp_dir) 642 input_paths, result_paths = _create_test_inputs_and_outputs( 643 image, label_image, model_type, weight_path, tmp_dir, with_decoder=with_decoder, 644 ) 645 architecture_path = os.path.join(os.path.split(__file__)[0], "predictor_adaptor.py") 646 architecture = spec.ArchitectureFromFileDescr( 647 source=Path(architecture_path), 648 callable="PredictorAdaptor", 649 kwargs={"model_type": _get_architecture_model_type(model_type)} 650 ) 651 652 dependency_file = os.path.join(tmp_dir, "environment.yaml") 653 _write_dependencies( 654 dependency_file, require_mobile_sam=model_type.startswith("vit_t"), require_micro_sam=with_decoder, 655 ) 656 657 weight_descriptions = spec.WeightsDescr( 658 pytorch_state_dict=spec.PytorchStateDictWeightsDescr( 659 source=Path(weight_path), 660 architecture=architecture, 661 pytorch_version=spec.Version(torch.__version__), 662 dependencies=spec.FileDescr(source=dependency_file), 663 ) 664 ) 665 666 doc_path = _write_documentation(kwargs.get("documentation", None), model_type, tmp_dir) 667 668 covers = kwargs.pop("covers", None) 669 if covers is None: 670 covers = _generate_covers(input_paths, result_paths, tmp_dir, with_decoder=with_decoder) 671 else: 672 assert all(os.path.exists(cov) for cov in covers) 673 674 # the uploader information is only added if explicitly passed 675 extra_kwargs = {} 676 if "id" in kwargs: 677 extra_kwargs["id"] = kwargs["id"] 678 if "id_emoji" in kwargs: 679 extra_kwargs["id_emoji"] = kwargs["id_emoji"] 680 if "uploader" in kwargs: 681 extra_kwargs["uploader"] = kwargs["uploader"] 682 if "version" in kwargs: 683 extra_kwargs["version"] = kwargs["version"] 684 685 if with_decoder: 686 # Keep the decoder available as a standalone registry attachment. 687 attachment_path = _get_decoder_attachment(model_type, decoder_path, tmp_dir) 688 extra_kwargs["attachments"] = [spec.FileDescr(source=attachment_path)] 689 690 model_description = _build_model_description( 691 name, input_paths, result_paths, weight_descriptions, doc_path, covers, extra_kwargs, 692 with_decoder=with_decoder, **kwargs, 693 ) 694 695 if with_decoder: 696 # Rebuild the description after the reference output hashes change. 697 _regenerate_reference_outputs(model_description, input_paths, result_paths) 698 model_description = _build_model_description( 699 name, input_paths, result_paths, weight_descriptions, doc_path, covers, extra_kwargs, 700 with_decoder=with_decoder, **kwargs, 701 ) 702 703 _check_model(model_description, input_paths, result_paths, with_decoder=with_decoder) 704 705 save_bioimageio_package(model_description, output_path=output_path)
DEFAULTS =
{'authors': [Author(affiliation='University Goettingen', email=None, orcid=None, name='Anwai Archit', github_user='anwai98'), Author(affiliation='University Goettingen', email=None, orcid=None, name='Constantin Pape', github_user='constantinpape')], 'description': 'Finetuned Segment Anything Model for Microscopy', 'cite': [CiteEntry(text='Archit et al. Segment Anything for Microscopy', doi='10.1038/s41592-024-02580-4', url=None)], 'tags': ['segment-anything', 'instance-segmentation']}
ARBITRARY_SIZE =
ParameterizedSize(min=1, step=1)
def
export_sam_model( image: numpy.ndarray, label_image: numpy.ndarray, model_type: str, name: str, output_path: Union[str, os.PathLike], checkpoint_path: Union[str, os.PathLike, NoneType] = None, **kwargs) -> None:
611def export_sam_model( 612 image: np.ndarray, 613 label_image: np.ndarray, 614 model_type: str, 615 name: str, 616 output_path: Union[str, os.PathLike], 617 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 618 **kwargs 619) -> None: 620 """Export SAM model to BioImage.IO model format. 621 622 The exported model can be uploaded to [bioimage.io](https://bioimage.io/#/) and 623 be used in tools that support the BioImage.IO model format. 624 625 Models with a decoder expose only the image input. 626 Their test outputs use automatic instance segmentation. 627 Use micro_sam directly for prompted segmentation with these models. 628 Models without a decoder expose the interactive prompt inputs. 629 630 Args: 631 image: The image for generating test data. 632 label_image: The segmentation corresponding to `image`. 633 It is used to derive prompt inputs for the model. 634 model_type: The type of the SAM model. 635 name: The name of the exported model. 636 output_path: Where the exported model is saved. 637 checkpoint_path: Optional checkpoint for loading the SAM model. 638 """ 639 with tempfile.TemporaryDirectory() as tmp_dir: 640 checkpoint_path, decoder_path = _get_checkpoint(model_type, checkpoint_path, tmp_dir) 641 with_decoder = decoder_path is not None 642 weight_path = _get_weight_checkpoint(model_type, checkpoint_path, decoder_path, tmp_dir) 643 input_paths, result_paths = _create_test_inputs_and_outputs( 644 image, label_image, model_type, weight_path, tmp_dir, with_decoder=with_decoder, 645 ) 646 architecture_path = os.path.join(os.path.split(__file__)[0], "predictor_adaptor.py") 647 architecture = spec.ArchitectureFromFileDescr( 648 source=Path(architecture_path), 649 callable="PredictorAdaptor", 650 kwargs={"model_type": _get_architecture_model_type(model_type)} 651 ) 652 653 dependency_file = os.path.join(tmp_dir, "environment.yaml") 654 _write_dependencies( 655 dependency_file, require_mobile_sam=model_type.startswith("vit_t"), require_micro_sam=with_decoder, 656 ) 657 658 weight_descriptions = spec.WeightsDescr( 659 pytorch_state_dict=spec.PytorchStateDictWeightsDescr( 660 source=Path(weight_path), 661 architecture=architecture, 662 pytorch_version=spec.Version(torch.__version__), 663 dependencies=spec.FileDescr(source=dependency_file), 664 ) 665 ) 666 667 doc_path = _write_documentation(kwargs.get("documentation", None), model_type, tmp_dir) 668 669 covers = kwargs.pop("covers", None) 670 if covers is None: 671 covers = _generate_covers(input_paths, result_paths, tmp_dir, with_decoder=with_decoder) 672 else: 673 assert all(os.path.exists(cov) for cov in covers) 674 675 # the uploader information is only added if explicitly passed 676 extra_kwargs = {} 677 if "id" in kwargs: 678 extra_kwargs["id"] = kwargs["id"] 679 if "id_emoji" in kwargs: 680 extra_kwargs["id_emoji"] = kwargs["id_emoji"] 681 if "uploader" in kwargs: 682 extra_kwargs["uploader"] = kwargs["uploader"] 683 if "version" in kwargs: 684 extra_kwargs["version"] = kwargs["version"] 685 686 if with_decoder: 687 # Keep the decoder available as a standalone registry attachment. 688 attachment_path = _get_decoder_attachment(model_type, decoder_path, tmp_dir) 689 extra_kwargs["attachments"] = [spec.FileDescr(source=attachment_path)] 690 691 model_description = _build_model_description( 692 name, input_paths, result_paths, weight_descriptions, doc_path, covers, extra_kwargs, 693 with_decoder=with_decoder, **kwargs, 694 ) 695 696 if with_decoder: 697 # Rebuild the description after the reference output hashes change. 698 _regenerate_reference_outputs(model_description, input_paths, result_paths) 699 model_description = _build_model_description( 700 name, input_paths, result_paths, weight_descriptions, doc_path, covers, extra_kwargs, 701 with_decoder=with_decoder, **kwargs, 702 ) 703 704 _check_model(model_description, input_paths, result_paths, with_decoder=with_decoder) 705 706 save_bioimageio_package(model_description, output_path=output_path)
Export SAM model to BioImage.IO model format.
The exported model can be uploaded to bioimage.io and be used in tools that support the BioImage.IO model format.
Models with a decoder expose only the image input. Their test outputs use automatic instance segmentation. Use micro_sam directly for prompted segmentation with these models. Models without a decoder expose the interactive prompt inputs.
Arguments:
- image: The image for generating test data.
- label_image: The segmentation corresponding to
image. It is used to derive prompt inputs for the model. - model_type: The type of the SAM model.
- name: The name of the exported model.
- output_path: Where the exported model is saved.
- checkpoint_path: Optional checkpoint for loading the SAM model.