micro_sam.v1.training.training

   1import os
   2import time
   3import warnings
   4from glob import glob
   5from collections import OrderedDict
   6from contextlib import contextmanager, nullcontext
   7from typing import Any, Callable, Dict, List, Optional, Tuple, Union
   8
   9import numpy as np
  10from tqdm import tqdm
  11import imageio.v3 as imageio
  12
  13import torch
  14from torch.optim import Optimizer
  15from torch.utils.data import random_split
  16from torch.utils.data import DataLoader, Dataset
  17from torch.optim.lr_scheduler import _LRScheduler
  18
  19try:
  20    from qtpy.QtCore import QObject
  21except Exception:
  22    QObject = Any
  23
  24from elf.io import open_file
  25
  26import torch_em
  27from torch_em.util import load_data
  28from torch_em.data.datasets.util import split_kwargs
  29
  30from . import sam_trainer as trainers
  31from ..instance_segmentation import get_unetr
  32from ..models.peft_sam import ClassicalSurgery
  33from . import joint_sam_trainer as joint_trainers
  34from ...util import get_device, training_autocast_dtype
  35from ..util import get_model_names, export_custom_sam_model, get_sam_model
  36from .util import get_trainable_sam_model, ConvertToSamInputs, require_8bit, get_raw_transform
  37
  38
  39FilePath = Union[str, os.PathLike]
  40
  41
  42def _check_loader(loader, with_segmentation_decoder, name=None, verify_n_labels_in_loader=None):
  43    x, _ = next(iter(loader))
  44
  45    # Raw data: check that we have 1 or 3 channels.
  46    n_channels = x.shape[1]
  47    if n_channels not in (1, 3):
  48        raise ValueError(
  49            "Invalid number of channels for the input data from the data loader. "
  50            f"Expect 1 or 3 channels, got {n_channels}."
  51        )
  52
  53    # Raw data: check that it is between [0, 255]
  54    minval, maxval = x.min(), x.max()
  55    if minval < 0 or minval > 255:
  56        raise ValueError(
  57            "Invalid data range for the input data from the data loader. "
  58            f"The input has to be in range [0, 255], but got minimum value {minval}."
  59        )
  60    if maxval < 1 or maxval > 255:
  61        raise ValueError(
  62            "Invalid data range for the input data from the data loader. "
  63            f"The input has to be in range [0, 255], but got maximum value {maxval}."
  64        )
  65
  66    # Target data: the check depends on whether we train with or without decoder.
  67    # NOTE: Verification step to check whether all labels from dataloader are valid (i.e. have atleast one instance).
  68
  69    def _check_instance_channel(instance_channel):
  70        unique_vals = torch.unique(instance_channel)
  71        if (unique_vals < 0).any():
  72            raise ValueError(
  73                "The target channel with the instance segmentation must not have negative values."
  74            )
  75        if len(unique_vals) == 1:
  76            raise ValueError(
  77                "The target channel with the instance segmentation must have at least one instance."
  78            )
  79        if not torch.allclose(unique_vals, unique_vals.round(), atol=1e-7):
  80            raise ValueError(
  81                "All values in the target channel with the instance segmentation must be integer."
  82            )
  83
  84    counter = 0
  85    name = "" if name is None else f"'{name}'"
  86    for x, y in tqdm(
  87        loader,
  88        desc=f"Verifying labels in {name} dataloader",
  89        total=verify_n_labels_in_loader if verify_n_labels_in_loader is not None else None,
  90    ):
  91        n_channels_y = y.shape[1]
  92        if with_segmentation_decoder:
  93            if n_channels_y != 4:
  94                raise ValueError(
  95                    "Invalid number of channels in the target data from the data loader. "
  96                    "Expect 4 channel for training with an instance segmentation decoder, "
  97                    f"but got {n_channels_y} channels."
  98                )
  99            # Check instance channel per sample in a batch
 100            for per_y_sample in y:
 101                _check_instance_channel(per_y_sample[0])
 102
 103            targets_min, targets_max = y[:, 1:].min(), y[:, 1:].max()
 104            if targets_min < 0 or targets_min > 1:
 105                raise ValueError(
 106                    "Invalid value range in the target data from the value loader. "
 107                    "Expect the 3 last target channels (for normalized distances and foreground probabilities) "
 108                    f"to be in range [0.0, 1.0], but got min {targets_min}"
 109                )
 110            if targets_max < 0 or targets_max > 1:
 111                raise ValueError(
 112                    "Invalid value range in the target data from the value loader. "
 113                    "Expect the 3 last target channels (for normalized distances and foreground probabilities) "
 114                    f"to be in range [0.0, 1.0], but got max {targets_max}"
 115                )
 116
 117        else:
 118            if n_channels_y != 1:
 119                raise ValueError(
 120                    "Invalid number of channels in the target data from the data loader. "
 121                    "Expect 1 channel for training without an instance segmentation decoder, "
 122                    f"but got {n_channels_y} channels."
 123                )
 124            # Check instance channel per sample in a batch
 125            for per_y_sample in y:
 126                _check_instance_channel(per_y_sample)
 127
 128        counter += 1
 129        if verify_n_labels_in_loader is not None and counter > verify_n_labels_in_loader:
 130            break
 131
 132
 133# Make the progress bar callbacks compatible with a tqdm progress bar interface.
 134class _ProgressBarWrapper:
 135    def __init__(self, signals):
 136        self._signals = signals
 137        self._total = None
 138
 139    @property
 140    def total(self):
 141        return self._total
 142
 143    @total.setter
 144    def total(self, value):
 145        self._signals.pbar_total.emit(value)
 146        self._total = value
 147
 148    def update(self, steps):
 149        self._signals.pbar_update.emit(steps)
 150
 151    def set_description(self, desc, **kwargs):
 152        self._signals.pbar_description.emit(desc)
 153
 154
 155@contextmanager
 156def _filter_warnings(ignore_warnings):
 157    if ignore_warnings:
 158        with warnings.catch_warnings():
 159            warnings.simplefilter("ignore")
 160            yield
 161    else:
 162        with nullcontext():
 163            yield
 164
 165
 166def _count_parameters(model_parameters):
 167    params = sum(p.numel() for p in model_parameters if p.requires_grad)
 168    params = params / 1e6
 169    print(f"The number of trainable parameters for the provided model is {params} (~{round(params, 2)}M)")
 170
 171
 172def _get_trainer_fit_params(n_epochs, n_iterations, save_every_kth_epoch, pbar_signals, overwrite_training):
 173    if n_iterations is None:
 174        trainer_fit_params = {"epochs": n_epochs}
 175    else:
 176        trainer_fit_params = {"iterations": n_iterations}
 177
 178    if save_every_kth_epoch is not None:
 179        trainer_fit_params["save_every_kth_epoch"] = save_every_kth_epoch
 180
 181    if pbar_signals is not None:
 182        progress_bar_wrapper = _ProgressBarWrapper(pbar_signals)
 183        trainer_fit_params["progress"] = progress_bar_wrapper
 184
 185    # Avoid overwriting a trained model, if desired by the user.
 186    trainer_fit_params["overwrite_training"] = overwrite_training
 187    return trainer_fit_params
 188
 189
 190def _get_optimizer_and_scheduler(model_params, lr, optimizer_class, scheduler_class, scheduler_kwargs):
 191    optimizer = optimizer_class(model_params, lr=lr)
 192    if scheduler_kwargs is None:
 193        scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 3}
 194    scheduler = scheduler_class(optimizer=optimizer, **scheduler_kwargs)
 195    return optimizer, scheduler
 196
 197
 198def train_sam(
 199    name: str,
 200    model_type: str,
 201    train_loader: DataLoader,
 202    val_loader: DataLoader,
 203    n_epochs: int = 100,
 204    early_stopping: Optional[int] = 10,
 205    n_objects_per_batch: Optional[int] = 25,
 206    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 207    with_segmentation_decoder: bool = True,
 208    freeze: Optional[List[str]] = None,
 209    device: Optional[Union[str, torch.device]] = None,
 210    lr: float = 1e-5,
 211    n_sub_iteration: int = 8,
 212    save_root: Optional[Union[str, os.PathLike]] = None,
 213    mask_prob: float = 0.5,
 214    n_iterations: Optional[int] = None,
 215    scheduler_class: Optional[_LRScheduler] = torch.optim.lr_scheduler.ReduceLROnPlateau,
 216    scheduler_kwargs: Optional[Dict[str, Any]] = None,
 217    save_every_kth_epoch: Optional[int] = None,
 218    pbar_signals: Optional[QObject] = None,
 219    optimizer_class: Optional[Optimizer] = torch.optim.AdamW,
 220    peft_kwargs: Optional[Dict] = None,
 221    ignore_warnings: bool = True,
 222    verify_n_labels_in_loader: Optional[int] = 50,
 223    box_distortion_factor: Optional[float] = 0.025,
 224    overwrite_training: bool = True,
 225    strict_decoder_loading: bool = True,
 226    **model_kwargs,
 227) -> None:
 228    """Run training for a SAM model.
 229
 230    Args:
 231        name: The name of the model to be trained. The checkpoint and logs will have this name.
 232        model_type: The type of the SAM model.
 233        train_loader: The dataloader for training.
 234        val_loader: The dataloader for validation.
 235        n_epochs: The number of epochs to train for.
 236        early_stopping: Enable early stopping after this number of epochs without improvement.
 237            By default, the value is set to '10' epochs.
 238        n_objects_per_batch: The number of objects per batch used to compute
 239            the loss for interative segmentation. If None all objects will be used,
 240            if given objects will be randomly sub-sampled. By default, the number of objects per batch are '25'.
 241        checkpoint_path: Path to checkpoint for initializing the SAM model.
 242        with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation.
 243            By default, trains with the additional instance segmentation decoder.
 244        freeze: Specify parts of the model that should be frozen, namely: image_encoder, prompt_encoder and mask_decoder
 245            By default nothing is frozen and the full model is updated.
 246        device: The device to use for training. By default, automatically chooses the best available device to train.
 247        lr: The learning rate. By default, set to '1e-5'.
 248        n_sub_iteration: The number of iterative prompts per training iteration.
 249            By default, the number of iterations is set to '8'.
 250        save_root: Optional root directory for saving the checkpoints and logs.
 251            If not given the current working directory is used.
 252        mask_prob: The probability for using a mask as input in a given training sub-iteration.
 253            By default, set to '0.5'.
 254        n_iterations: The number of iterations to use for training. This will over-ride `n_epochs` if given.
 255        scheduler_class: The learning rate scheduler to update the learning rate.
 256            By default, `torch.optim.lr_scheduler.ReduceLROnPlateau` is used.
 257        scheduler_kwargs: The learning rate scheduler parameters.
 258            If passed 'None', the chosen default parameters are used in `ReduceLROnPlateau`.
 259        save_every_kth_epoch: Save checkpoints after every kth epoch separately.
 260        pbar_signals: Controls for napari progress bar.
 261        optimizer_class: The optimizer class. By default, `torch.optim.AdamW` is used.
 262        peft_kwargs: Keyword arguments for the PEFT wrapper class.
 263        ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
 264        verify_n_labels_in_loader: The number of labels to verify out of the train and validation dataloaders.
 265            By default, 50 batches of labels are verified from the dataloaders.
 266        box_distortion_factor: The factor for distorting the box annotations derived from the ground-truth masks.
 267            By default, the distortion factor is set to '0.025'.
 268        overwrite_training: Whether to overwrite the trained model stored at the same location.
 269            By default, overwrites the trained model at each run.
 270            If set to 'False', it will avoid retraining the model if the previous run was completed.
 271        strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present,
 272            exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output
 273            channels if they were pre-trained for a different task. If set to False, decoders with a different
 274            output dimension can be loaded; the output channels will be re-initialized.
 275        model_kwargs: Additional keyword arguments for the `micro_sam.v1.util.get_sam_model`.
 276    """
 277    with _filter_warnings(ignore_warnings):
 278
 279        t_start = time.time()
 280        if verify_n_labels_in_loader is not None:
 281            _check_loader(train_loader, with_segmentation_decoder, "train", verify_n_labels_in_loader)
 282            _check_loader(val_loader, with_segmentation_decoder, "val", verify_n_labels_in_loader)
 283
 284        device = get_device(device)
 285        # Get the trainable segment anything model.
 286        model, state = get_trainable_sam_model(
 287            model_type=model_type,
 288            device=device,
 289            freeze=freeze,
 290            checkpoint_path=checkpoint_path,
 291            return_state=True,
 292            peft_kwargs=peft_kwargs,
 293            **model_kwargs
 294        )
 295
 296        # This class creates all the training data for a batch (inputs, prompts and labels).
 297        convert_inputs = ConvertToSamInputs(transform=model.transform, box_distortion_factor=box_distortion_factor)
 298
 299        # Create the UNETR decoder (if train with it) and the optimizer.
 300        if with_segmentation_decoder:
 301
 302            # Get the UNETR.
 303            unetr = get_unetr(
 304                image_encoder=model.sam.image_encoder, decoder_state=state.get("decoder_state", None),
 305                device=device, flexible_load_checkpoint=not strict_decoder_loading,
 306            )
 307
 308            # Get the parameters for SAM and the decoder from UNETR.
 309            joint_model_params = [params for params in model.parameters()]  # sam parameters
 310            for param_name, params in unetr.named_parameters():  # unetr's decoder parameters
 311                if not param_name.startswith("encoder"):
 312                    joint_model_params.append(params)
 313
 314            model_params = joint_model_params
 315        else:
 316            model_params = model.parameters()
 317
 318        optimizer, scheduler = _get_optimizer_and_scheduler(
 319            model_params, lr, optimizer_class, scheduler_class, scheduler_kwargs
 320        )
 321
 322        # The hardware decides the precision. Training runs in bfloat16 only.
 323        mixed_precision = training_autocast_dtype(device) is not None
 324
 325        # The trainer which performs training and validation.
 326        if with_segmentation_decoder:
 327            instance_seg_loss = torch_em.loss.DiceBasedDistanceLoss(mask_distances_in_bg=True)
 328            trainer = joint_trainers.JointSamTrainer(
 329                name=name,
 330                save_root=save_root,
 331                train_loader=train_loader,
 332                val_loader=val_loader,
 333                model=model,
 334                optimizer=optimizer,
 335                device=device,
 336                lr_scheduler=scheduler,
 337                logger=joint_trainers.JointSamLogger,
 338                log_image_interval=100,
 339                mixed_precision=mixed_precision,
 340                mixed_precision_dtype="bfloat16",
 341                convert_inputs=convert_inputs,
 342                n_objects_per_batch=n_objects_per_batch,
 343                n_sub_iteration=n_sub_iteration,
 344                compile_model=False,
 345                unetr=unetr,
 346                instance_loss=instance_seg_loss,
 347                instance_metric=instance_seg_loss,
 348                early_stopping=early_stopping,
 349                mask_prob=mask_prob,
 350            )
 351        else:
 352            trainer = trainers.SamTrainer(
 353                name=name,
 354                train_loader=train_loader,
 355                val_loader=val_loader,
 356                model=model,
 357                optimizer=optimizer,
 358                device=device,
 359                lr_scheduler=scheduler,
 360                logger=trainers.SamLogger,
 361                log_image_interval=100,
 362                mixed_precision=mixed_precision,
 363                mixed_precision_dtype="bfloat16",
 364                convert_inputs=convert_inputs,
 365                n_objects_per_batch=n_objects_per_batch,
 366                n_sub_iteration=n_sub_iteration,
 367                compile_model=False,
 368                early_stopping=early_stopping,
 369                mask_prob=mask_prob,
 370                save_root=save_root,
 371            )
 372
 373        trainer_fit_params = _get_trainer_fit_params(
 374            n_epochs, n_iterations, save_every_kth_epoch, pbar_signals, overwrite_training
 375        )
 376        trainer.fit(**trainer_fit_params)
 377
 378        t_run = time.time() - t_start
 379        hours = int(t_run // 3600)
 380        minutes = int(t_run // 60)
 381        seconds = int(round(t_run % 60, 0))
 382        print("Training took", t_run, f"seconds (= {hours:02}:{minutes:02}:{seconds:02} hours)")
 383
 384
 385def export_instance_segmentation_model(
 386    trained_model_path: Union[str, os.PathLike],
 387    output_path: Union[str, os.PathLike],
 388    model_type: str,
 389    initial_checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 390) -> None:
 391    """Export a model trained for instance segmentation with `train_instance_segmentation`.
 392
 393    The exported model will be compatible with the micro_sam functions, CLI and napari plugin.
 394    It should only be used for automatic segmentation and may not work well for interactive segmentation.
 395
 396    Args:
 397        trained_model_path: The path to the checkpoint of the model trained for instance segmentation.
 398        output_path: The path where the exported model will be saved.
 399        model_type: The model type.
 400        initial_checkpoint_path: The initial checkpoint path the instance segmentation training was based on (optional).
 401    """
 402    state = torch.load(trained_model_path, weights_only=False, map_location="cpu")
 403    trained_state = state.get("model_state", state)
 404
 405    # Get the state of the encoder and instance segmentation decoder from the trained checkpoint.
 406    encoder_state = OrderedDict([(k, v) for k, v in trained_state.items() if k.startswith("encoder")])
 407    decoder_state = OrderedDict([(k, v) for k, v in trained_state.items() if not k.startswith("encoder")])
 408
 409    # Load the original state of the model that was used as the basis of instance segmentation training.
 410    predictor = get_sam_model(
 411        model_type=model_type, checkpoint_path=initial_checkpoint_path, device="cpu",
 412    )
 413    model_state = OrderedDict(predictor.model.state_dict())
 414
 415    # Replace the image encoder weights with the trained ones.
 416    # UNETR stores the image encoder as "encoder.*"; SAM uses "image_encoder.*".
 417    for k in list(model_state.keys()):
 418        if k.startswith("image_encoder."):
 419            encoder_key = "encoder." + k[len("image_encoder."):]
 420            model_state[k] = encoder_state[encoder_key]
 421
 422    save_state = {"model_state": model_state, "decoder_state": decoder_state}
 423    torch.save(save_state, output_path)
 424
 425
 426def train_instance_segmentation(
 427    name: str,
 428    model_type: str,
 429    train_loader: DataLoader,
 430    val_loader: DataLoader,
 431    n_epochs: int = 100,
 432    early_stopping: Optional[int] = 10,
 433    loss: torch.nn.Module = torch_em.loss.DiceBasedDistanceLoss(mask_distances_in_bg=True),
 434    metric: Optional[torch.nn.Module] = None,
 435    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 436    freeze: Optional[List[str]] = None,
 437    device: Optional[Union[str, torch.device]] = None,
 438    lr: float = 1e-5,
 439    save_root: Optional[Union[str, os.PathLike]] = None,
 440    n_iterations: Optional[int] = None,
 441    scheduler_class: Optional[_LRScheduler] = torch.optim.lr_scheduler.ReduceLROnPlateau,
 442    scheduler_kwargs: Optional[Dict[str, Any]] = None,
 443    save_every_kth_epoch: Optional[int] = None,
 444    pbar_signals: Optional[QObject] = None,
 445    optimizer_class: Optional[Optimizer] = torch.optim.AdamW,
 446    peft_kwargs: Optional[Dict] = None,
 447    ignore_warnings: bool = True,
 448    overwrite_training: bool = True,
 449    strict_decoder_loading: bool = True,
 450    **model_kwargs,
 451) -> None:
 452    """Train a UNETR for instance segmentation using the SAM encoder as backbone.
 453
 454    This setting corresponds to training a SAM model with an instance segmentation decoder,
 455    without training the model parts for interactive segmentation,
 456    i.e. without training the prompt encoder and mask decoder.
 457
 458    The checkpoint of the trained model, which will be saved in 'checkpoints/<name>',
 459    will not be compatible with the micro_sam functionality.
 460    You can call the function `export_instance_segmentation_model` with the path to the checkpoint to export it
 461    in a format that is compatible with micro_sam functionality.
 462    Note that the exported model should only be used for automatic segmentation via AIS.
 463
 464    Args:
 465        name: The name of the model to be trained. The checkpoint and logs will have this name.
 466        model_type: The type of the SAM model.
 467        train_loader: The dataloader for training.
 468        val_loader: The dataloader for validation.
 469        n_epochs: The number of epochs to train for.
 470        early_stopping: Enable early stopping after this number of epochs without improvement.
 471            By default, the value is set to '10' epochs.
 472        loss: The loss function to train the instance segmentation model.
 473            By default, the value is set to 'torch_em.loss.DiceBasedDistanceLoss'
 474        metric: The metric for the instance segmentation training.
 475            By default the loss function is used as the metric.
 476        checkpoint_path: Path to checkpoint for initializing the SAM model.
 477        freeze: Specify parts of the model that should be frozen. Here, only the image_encoder can be frozen.
 478            By default nothing is frozen and the full model is updated.
 479        device: The device to use for training. By default, automatically chooses the best available device to train.
 480        lr: The learning rate. By default, set to '1e-5'.
 481        save_root: Optional root directory for saving the checkpoints and logs.
 482            If not given the current working directory is used.
 483        n_iterations: The number of iterations to use for training. This will over-ride `n_epochs` if given.
 484        scheduler_class: The learning rate scheduler to update the learning rate.
 485            By default, `torch.optim.lr_scheduler.ReduceLROnPlateau` is used.
 486        scheduler_kwargs: The learning rate scheduler parameters.
 487            If passed 'None', the chosen default parameters are used in `ReduceLROnPlateau`.
 488        save_every_kth_epoch: Save checkpoints after every kth epoch separately.
 489        pbar_signals: Controls for napari progress bar.
 490        optimizer_class: The optimizer class. By default, `torch.optim.AdamW` is used.
 491        peft_kwargs: Keyword arguments for the PEFT wrapper class.
 492        ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
 493        overwrite_training: Whether to overwrite the trained model stored at the same location.
 494            By default, overwrites the trained model at each run.
 495            If set to 'False', it will avoid retraining the model if the previous run was completed.
 496        strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present,
 497            exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output
 498            channels if they were pre-trained for a different task. If set to False, decoders with a different
 499            output dimension can be loaded; the output channels will be re-initialized.
 500        model_kwargs: Additional keyword arguments for the `micro_sam.v1.util.get_sam_model`.
 501    """
 502
 503    with _filter_warnings(ignore_warnings):
 504        t_start = time.time()
 505
 506        sam_model, state = get_trainable_sam_model(
 507            model_type=model_type,
 508            device=device,
 509            checkpoint_path=checkpoint_path,
 510            return_state=True,
 511            peft_kwargs=peft_kwargs,
 512            freeze=freeze,
 513            **model_kwargs
 514        )
 515        device = get_device(device)
 516        model = get_unetr(
 517            image_encoder=sam_model.sam.image_encoder, decoder_state=state.get("decoder_state", None),
 518            device=device, flexible_load_checkpoint=not strict_decoder_loading,
 519        )
 520
 521        optimizer, scheduler = _get_optimizer_and_scheduler(
 522            model.parameters(), lr, optimizer_class, scheduler_class, scheduler_kwargs
 523        )
 524        trainer = torch_em.trainer.DefaultTrainer(
 525            name=name,
 526            model=model,
 527            train_loader=train_loader,
 528            val_loader=val_loader,
 529            device=device,
 530            # The hardware decides the precision. Training runs in bfloat16 only.
 531            mixed_precision=training_autocast_dtype(device) is not None,
 532            mixed_precision_dtype="bfloat16",
 533            log_image_interval=50,
 534            compile_model=False,
 535            save_root=save_root,
 536            loss=loss,
 537            metric=loss if metric is None else metric,
 538            optimizer=optimizer,
 539            lr_scheduler=scheduler,
 540            early_stopping=early_stopping,
 541        )
 542
 543        trainer_fit_params = _get_trainer_fit_params(
 544            n_epochs, n_iterations, save_every_kth_epoch, pbar_signals, overwrite_training
 545        )
 546        trainer.fit(**trainer_fit_params)
 547
 548        t_run = time.time() - t_start
 549        hours = int(t_run // 3600)
 550        minutes = int(t_run // 60)
 551        seconds = int(round(t_run % 60, 0))
 552        print("Training took", t_run, f"seconds (= {hours:02}:{minutes:02}:{seconds:02} hours)")
 553
 554
 555def _update_patch_shape(patch_shape, raw_paths, raw_key, with_channels):
 556    if isinstance(raw_paths, (str, os.PathLike)):
 557        path = raw_paths
 558    else:
 559        path = raw_paths[0]
 560    assert isinstance(path, (str, os.PathLike, np.ndarray, torch.Tensor))
 561
 562    # Check the underlying data dimensionality.
 563    if raw_key is None and isinstance(path, (np.ndarray, torch.Tensor)):
 564        ndim = path.ndim
 565    elif raw_key is None:  # If no key is given and this is not a tensor/array then we assume it's an image file.
 566        ndim = imageio.imread(path).ndim
 567    else:  # Otherwise we try to open the file from key.
 568        try:  # First try to open it with elf.
 569            with open_file(path, "r") as f:
 570                ndim = f[raw_key].ndim
 571        except ValueError:  # This may fail for images in a folder with different sizes.
 572            # In that case we read one of the images.
 573            image_path = glob(os.path.join(path, raw_key))[0]
 574            ndim = imageio.imread(image_path).ndim
 575
 576    if not isinstance(patch_shape, tuple):
 577        patch_shape = tuple(patch_shape)
 578
 579    if ndim == 2:
 580        assert len(patch_shape) == 2
 581        return patch_shape
 582    elif ndim == 3 and len(patch_shape) == 2 and not with_channels:
 583        return (1,) + patch_shape
 584    elif ndim == 4 and len(patch_shape) == 2 and with_channels:
 585        return (1,) + patch_shape
 586    else:
 587        return patch_shape
 588
 589
 590def _determine_dataset_and_channels(raw_paths, raw_key, label_paths, label_key, with_channels, **kwargs):
 591    # By default, let the 'default_segmentation_dataset' heuristic decide for itself.
 592    is_seg_dataset = kwargs.pop("is_seg_dataset", None)
 593
 594    # Check if the input data is in numpy or torch. In this case determine we use
 595    # the image collection dataset heuristic (torch_em will figure it out),
 596    # and we determine the number of channels.
 597    if isinstance(raw_paths, list) and isinstance(raw_paths[0], (np.ndarray, torch.Tensor)):
 598        is_seg_dataset = False
 599        if with_channels is None:
 600            with_channels = raw_paths[0].ndim == 3 and raw_paths.shape[-1] == 3
 601        return is_seg_dataset, with_channels
 602
 603    # Check if the raw inputs are RGB or not. If yes, use 'ImageCollectionDataset'.
 604    # Get valid raw paths to make checks possible.
 605    if raw_key and "*" in raw_key:  # Use the wildcard pattern to find the filepath to only one image.
 606        rpath = glob(os.path.join(raw_paths if isinstance(raw_paths, str) else raw_paths[0], raw_key))[0]
 607    else:  # Otherwise, either 'raw_key' is None or container format, supported by 'elf', then we load 1 filepath.
 608        rpath = raw_paths if isinstance(raw_paths, str) else raw_paths[0]
 609
 610    # Load one of the raw inputs to validate whether it is RGB or not.
 611    test_raw_inputs = load_data(path=rpath, key=raw_key if raw_key and "*" not in raw_key else None)
 612    if test_raw_inputs.ndim == 3:
 613        if test_raw_inputs.shape[-1] == 3:  # i.e. if it is an RGB image and has channels last.
 614            is_seg_dataset = False  # we use 'ImageCollectionDataset' in this case.
 615            # We need to provide a list of inputs to 'ImageCollectionDataset'.
 616            raw_paths = [raw_paths] if isinstance(raw_paths, str) else raw_paths
 617            label_paths = [label_paths] if isinstance(label_paths, str) else label_paths
 618
 619            # This is not relevant for 'ImageCollectionDataset'. Hence, we set 'with_channels' to 'False'.
 620            with_channels = False if with_channels is None else with_channels
 621
 622        elif test_raw_inputs.shape[0] == 3:  # i.e. if it is a RGB image and has 3 channels first.
 623            # This is relevant for 'SegmentationDataset'. If not provided by the user, we set this to 'True'.
 624            with_channels = True if with_channels is None else with_channels
 625
 626    # Set 'with_channels' to 'False', i.e. the default behavior of 'default_segmentation_dataset'
 627    # Otherwise, let the user make the choice as priority, else set this to our suggested default.
 628    with_channels = False if with_channels is None else with_channels
 629
 630    return is_seg_dataset, with_channels
 631
 632
 633def default_sam_dataset(
 634    raw_paths: Union[List[Union[np.ndarray, torch.Tensor]], List[FilePath], FilePath],
 635    raw_key: Optional[str],
 636    label_paths: Union[List[Union[np.ndarray, torch.Tensor]], List[FilePath], FilePath],
 637    label_key: Optional[str],
 638    patch_shape: Tuple[int],
 639    with_segmentation_decoder: bool,
 640    with_channels: Optional[bool] = None,
 641    train_instance_segmentation_only: bool = False,
 642    sampler: Optional[Callable] = None,
 643    raw_transform: Optional[Callable] = None,
 644    n_samples: Optional[int] = None,
 645    is_train: bool = True,
 646    min_size: int = 25,
 647    max_sampling_attempts: Optional[int] = None,
 648    rois: Optional[Union[slice, Tuple[slice, ...]]] = None,
 649    is_multi_tensor: bool = True,
 650    **kwargs,
 651) -> Dataset:
 652    """Create a PyTorch Dataset for training a SAM model.
 653
 654    Args:
 655        raw_paths: The path(s) to the image data used for training.
 656            Can either be multiple 2D images or volumetric data.
 657            The data can also be passed as a list of numpy arrays or torch tensors.
 658        raw_key: The key for accessing the image data. Internal filepath for hdf5-like input
 659            or a glob pattern for selecting multiple files.
 660            Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
 661        label_paths: The path(s) to the label data used for training.
 662            Can either be multiple 2D images or volumetric data.
 663            The data can also be passed as a list of numpy arrays or torch tensors.
 664        label_key: The key for accessing the label data. Internal filepath for hdf5-like input
 665            or a glob pattern for selecting multiple files.
 666            Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
 667        patch_shape: The shape for training patches.
 668        with_segmentation_decoder: Whether to train with additional segmentation decoder.
 669        with_channels: Whether the image data has channels. By default, it makes the decision based on inputs.
 670        train_instance_segmentation_only: Set this argument to True in order to
 671            pass the dataset to `train_instance_segmentation`. By default, set to 'False'.
 672        sampler: A sampler to reject batches according to a given criterion.
 673        raw_transform: Transformation applied to the image data.
 674            If not given the data will be cast to 8bit.
 675        n_samples: The number of samples for this dataset.
 676        is_train: Whether this dataset is used for training or validation. By default, set to 'True'.
 677        min_size: Minimal object size. Smaller objects will be filtered. By default, set to '25'.
 678        max_sampling_attempts: Number of sampling attempts to make from a dataset.
 679        rois: The region of interest(s) for the data.
 680        is_multi_tensor: Whether the input data to data transforms is multiple tensors or not.
 681        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
 682
 683    Returns:
 684        The segmentation dataset.
 685    """
 686
 687    # Check if this dataset should be used for instance segmentation only training.
 688    # If yes, we set return_instances to False, since the instance channel must not
 689    # be passed for this training mode.
 690    return_instances = True
 691    if train_instance_segmentation_only:
 692        if not with_segmentation_decoder:
 693            raise ValueError(
 694                "If 'train_instance_segmentation_only' is True, then 'with_segmentation_decoder' must also be True."
 695            )
 696        return_instances = False
 697
 698    # If a sampler is not passed, then we set a MinInstanceSampler, which requires 3 distinct instances per sample.
 699    # This is necessary, because training for interactive segmentation does not work on 'empty' images.
 700    # However, if we train only the automatic instance segmentation decoder, then this sampler is not required
 701    # and we do not set a default sampler.
 702    if sampler is None and not train_instance_segmentation_only:
 703        sampler = torch_em.data.sampler.MinInstanceSampler(2, min_size=min_size)
 704
 705    is_seg_dataset, with_channels = _determine_dataset_and_channels(
 706        raw_paths, raw_key, label_paths, label_key, with_channels, **kwargs
 707    )
 708    # Since `is_seg_dataset` is selected and sorted above, let's remove it out of running kwargs, if available.
 709    kwargs.pop("is_seg_dataset", None)
 710
 711    # Set the data transformations.
 712    if raw_transform is None:
 713        raw_transform = require_8bit
 714
 715    # Prepare the label transform.
 716    if with_segmentation_decoder:
 717        default_label_transform = torch_em.transform.label.PerObjectDistanceTransform(
 718            distances=True,
 719            boundary_distances=True,
 720            directed_distances=False,
 721            foreground=True,
 722            instances=return_instances,
 723            min_size=min_size,
 724        )
 725    else:
 726        default_label_transform = torch_em.transform.label.MinSizeLabelTransform(min_size=min_size)
 727
 728    # Allow combining label transforms.
 729    custom_label_transform = kwargs.pop("label_transform", None)
 730    if custom_label_transform is None:
 731        label_transform = default_label_transform
 732    else:
 733        label_transform = torch_em.transform.generic.Compose(
 734            custom_label_transform, default_label_transform, is_multi_tensor=is_multi_tensor
 735        )
 736
 737    # Check the patch shape to add a singleton if required.
 738    patch_shape = _update_patch_shape(
 739        patch_shape=patch_shape, raw_paths=raw_paths, raw_key=raw_key, with_channels=with_channels,
 740    )
 741
 742    # Set a minimum number of samples per epoch.
 743    if n_samples is None:
 744        loader = torch_em.default_segmentation_loader(
 745            raw_paths=raw_paths,
 746            raw_key=raw_key,
 747            label_paths=label_paths,
 748            label_key=label_key,
 749            batch_size=1,
 750            patch_shape=patch_shape,
 751            with_channels=with_channels,
 752            ndim=2,
 753            is_seg_dataset=is_seg_dataset,
 754            raw_transform=raw_transform,
 755            rois=rois,
 756            **kwargs
 757        )
 758        n_samples = max(len(loader), 100 if is_train else 5)
 759
 760    dataset = torch_em.default_segmentation_dataset(
 761        raw_paths=raw_paths,
 762        raw_key=raw_key,
 763        label_paths=label_paths,
 764        label_key=label_key,
 765        patch_shape=patch_shape,
 766        raw_transform=raw_transform,
 767        label_transform=label_transform,
 768        with_channels=with_channels,
 769        ndim=2,
 770        sampler=sampler,
 771        n_samples=n_samples,
 772        is_seg_dataset=is_seg_dataset,
 773        rois=rois,
 774        **kwargs,
 775    )
 776
 777    if max_sampling_attempts is not None:
 778        if isinstance(dataset, torch_em.data.concat_dataset.ConcatDataset):
 779            for ds in dataset.datasets:
 780                ds.max_sampling_attempts = max_sampling_attempts
 781        else:
 782            dataset.max_sampling_attempts = max_sampling_attempts
 783
 784    return dataset
 785
 786
 787def default_sam_loader(**kwargs) -> DataLoader:
 788    """Create a PyTorch DataLoader for training a SAM model.
 789
 790    Args:
 791        kwargs: Keyword arguments for `micro_sam.v1.training.default_sam_dataset` or for the PyTorch DataLoader.
 792
 793    Returns:
 794        The DataLoader.
 795    """
 796    sam_ds_kwargs, extra_kwargs = split_kwargs(default_sam_dataset, **kwargs)
 797
 798    # There might be additional parameters supported by `torch_em.default_segmentation_dataset`,
 799    # which the users can provide to get their desired segmentation dataset.
 800    extra_ds_kwargs, loader_kwargs = split_kwargs(torch_em.default_segmentation_dataset, **extra_kwargs)
 801    ds_kwargs = {**sam_ds_kwargs, **extra_ds_kwargs}
 802
 803    ds = default_sam_dataset(**ds_kwargs)
 804    return torch_em.segmentation.get_data_loader(ds, **loader_kwargs)
 805
 806
 807CONFIGURATIONS = {
 808    "Minimal": {"model_type": "vit_t", "n_objects_per_batch": 4, "n_sub_iteration": 4},
 809    "CPU": {"model_type": "vit_b", "n_objects_per_batch": 10},
 810    "gtx1080": {"model_type": "vit_t", "n_objects_per_batch": 5},
 811    "gtx3080": {
 812        "model_type": "vit_b", "n_objects_per_batch": 5,
 813        "peft_kwargs": {"attention_layers_to_update": [11], "peft_module": ClassicalSurgery}
 814    },
 815    "rtx5000": {"model_type": "vit_b", "n_objects_per_batch": 10},
 816    "V100": {"model_type": "vit_b"},
 817    "A100": {"model_type": "vit_h"},
 818}
 819"""Best training configurations for given hardware resources.
 820"""
 821
 822
 823def _find_best_configuration():
 824    if torch.cuda.is_available():
 825
 826        # Check how much memory we have and select the best matching GPU
 827        # for the available VRAM size.
 828        _, vram = torch.cuda.mem_get_info()
 829        vram = vram / 1e9  # in GB
 830
 831        # Maybe we can get more configurations in the future.
 832        if vram > 80:  # More than 80 GB: use the A100 configurations.
 833            return "A100"
 834        elif vram > 30:  # More than 30 GB: use the V100 configurations.
 835            return "V100"
 836        elif vram > 14:  # More than 14 GB: use the RTX5000 configurations.
 837            return "rtx5000"
 838        elif vram > 8:  # More than 8 GB: use the GTX3080 configurations.
 839            return "gtx3080"
 840        else:  # Otherwise: not enough memory to train on the GPU, use CPU instead.
 841            return "CPU"
 842    else:
 843        return "CPU"
 844
 845
 846def train_sam_for_configuration(
 847    name: str,
 848    train_loader: DataLoader,
 849    val_loader: DataLoader,
 850    configuration: Optional[str] = None,
 851    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 852    with_segmentation_decoder: bool = True,
 853    train_instance_segmentation_only: bool = False,
 854    model_type: Optional[str] = None,
 855    **kwargs,
 856) -> None:
 857    """Run training for a SAM model with the configuration for a given hardware resource.
 858
 859    Selects the best training settings for the given configuration.
 860    The available configurations are listed in `CONFIGURATIONS`.
 861
 862    Args:
 863        name: The name of the model to be trained. The checkpoint and logs folder will have this name.
 864        train_loader: The dataloader for training.
 865        val_loader: The dataloader for validation.
 866        configuration: The configuration (= name of hardware resource).
 867            By default, it is automatically selected for the best VRAM combination.
 868        checkpoint_path: Path to checkpoint for initializing the SAM model.
 869        with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation.
 870            By default, trains with the additional instance segmentation decoder.
 871        train_instance_segmentation_only: Whether to train a model only for automatic instance segmentation
 872            using the training implementation `train_instance_segmentation`. By default, `train_sam` is used.
 873        model_type: Over-ride the default model type.
 874            This can be used to use one of the micro_sam models as starting point
 875            instead of a default sam model.
 876        kwargs: Additional keyword parameters that will be passed to `train_sam`.
 877    """
 878    if configuration is None:  # Automatically choose based on available VRAM combination.
 879        configuration = _find_best_configuration()
 880
 881    if configuration in CONFIGURATIONS:
 882        train_kwargs = CONFIGURATIONS[configuration]
 883    else:
 884        raise ValueError(f"Invalid configuration {configuration} expect one of {list(CONFIGURATIONS.keys())}")
 885
 886    if model_type is None:
 887        model_type = train_kwargs.pop("model_type")
 888    else:
 889        expected_model_type = train_kwargs.pop("model_type")
 890        if model_type[:5] != expected_model_type:
 891            warnings.warn("You have specified a different model type.")
 892
 893    train_kwargs.update(**kwargs)
 894    if train_instance_segmentation_only:
 895        instance_seg_kwargs, extra_kwargs = split_kwargs(train_instance_segmentation, **train_kwargs)
 896        model_kwargs, extra_kwargs = split_kwargs(get_sam_model, **extra_kwargs)
 897        instance_seg_kwargs.update(**model_kwargs)
 898
 899        train_instance_segmentation(
 900            name=name,
 901            train_loader=train_loader,
 902            val_loader=val_loader,
 903            checkpoint_path=checkpoint_path,
 904            model_type=model_type,
 905            **instance_seg_kwargs,
 906        )
 907    else:
 908        train_sam(
 909            name=name,
 910            train_loader=train_loader,
 911            val_loader=val_loader,
 912            checkpoint_path=checkpoint_path,
 913            with_segmentation_decoder=with_segmentation_decoder,
 914            model_type=model_type,
 915            **train_kwargs
 916        )
 917
 918
 919def _export_helper(save_root, checkpoint_name, output_path, model_type, with_segmentation_decoder, val_loader):
 920
 921    # Whether the model is stored in the current working directory or in another location.
 922    if save_root is None:
 923        save_root = os.getcwd()  # Map this to current working directory, if not specified by the user.
 924
 925    # Get the 'best' model checkpoint ready for export.
 926    best_checkpoint = os.path.join(save_root, "checkpoints", checkpoint_name, "best.pt")
 927    if not os.path.exists(best_checkpoint):
 928        raise FileNotFoundError(f"The trained model not found at the expected location: '{best_checkpoint}'.")
 929
 930    # Export the model if an output path has been given.
 931    if output_path:
 932
 933        # If the filepath has a pytorch-specific ending, then we just export the checkpoint.
 934        if os.path.splitext(output_path)[1] in (".pt", ".pth"):
 935            export_custom_sam_model(
 936                checkpoint_path=best_checkpoint,
 937                model_type=model_type[:5],
 938                save_path=output_path,
 939                with_segmentation_decoder=with_segmentation_decoder,
 940            )
 941
 942        # Otherwise we export it as bioimage.io model.
 943        else:
 944            from micro_sam.v1.bioimageio import export_sam_model
 945
 946            # Load image and corresponding labels from the val loader.
 947            with torch.no_grad():
 948                image_data, label_data = next(iter(val_loader))
 949                image_data, label_data = image_data.numpy().squeeze(), label_data.numpy().squeeze()
 950
 951                # Select the first channel of the label image if we have a channel axis, i.e. contains the labels
 952                if label_data.ndim == 3:
 953                    label_data = label_data[0]  # Gets the channel with instances.
 954                assert image_data.shape == label_data.shape
 955                label_data = label_data.astype("uint32")
 956
 957                export_sam_model(
 958                    image=image_data,
 959                    label_image=label_data,
 960                    model_type=model_type[:5],
 961                    name=checkpoint_name,
 962                    output_path=output_path,
 963                    checkpoint_path=best_checkpoint,
 964                )
 965
 966        # The final path where the model has been stored.
 967        final_path = output_path
 968
 969    else:  # If no exports have been made, inform the user about the best checkpoint.
 970        final_path = best_checkpoint
 971
 972    return final_path
 973
 974
 975def _parse_segmentation_decoder(segmentation_decoder):
 976    if segmentation_decoder in ("None", "none"):
 977        with_segmentation_decoder, train_instance_segmentation_only = False, False
 978    elif segmentation_decoder == "instances":
 979        with_segmentation_decoder, train_instance_segmentation_only = True, False
 980    elif segmentation_decoder == "instances_only":
 981        with_segmentation_decoder, train_instance_segmentation_only = True, True
 982    else:
 983        raise ValueError(
 984            "The 'segmentation_decoder' argument currently supports the values:\n"
 985            f"'instances', 'instances_only', or 'None'. You have passed {segmentation_decoder}."
 986        )
 987    return with_segmentation_decoder, train_instance_segmentation_only
 988
 989
 990def main(argv=None):
 991    """@private"""
 992    import argparse
 993
 994    available_models = list(get_model_names())
 995    available_models = ", ".join(available_models)
 996
 997    available_configurations = list(CONFIGURATIONS.keys())
 998    available_configurations = ", ".join(available_configurations)
 999
1000    parser = argparse.ArgumentParser(description="Finetune Segment Anything Models on custom data.")
1001
1002    # Images and labels for training.
1003    parser.add_argument(
1004        "--images", required=True, type=str, nargs="*",
1005        help="Filepath to images or the directory where the image data is stored."
1006    )
1007    parser.add_argument(
1008        "--labels", required=True, type=str, nargs="*",
1009        help="Filepath to ground-truth labels or the directory where the label data is stored."
1010    )
1011    parser.add_argument(
1012        "--image_key", type=str, default=None,
1013        help="The key for accessing image data, either a pattern / wildcard or with elf.io.open_file. "
1014    )
1015    parser.add_argument(
1016        "--label_key", type=str, default=None,
1017        help="The key for accessing label data, either a pattern / wildcard or with elf.io.open_file. "
1018    )
1019
1020    # Images and labels for validation.
1021    # NOTE: This isn't required, i.e. we create a val-split on-the-fly from the training data if not provided.
1022    # Users can choose to have their explicit validation set via this feature as well.
1023    parser.add_argument(
1024        "--val_images", type=str, nargs="*",
1025        help="Filepath to images for validation or the directory where the image data is stored."
1026    )
1027    parser.add_argument(
1028        "--val_labels", type=str, nargs="*",
1029        help="Filepath to ground-truth labels for validation or the directory where the label data is stored."
1030    )
1031    parser.add_argument(
1032        "--val_image_key", type=str, default=None,
1033        help="The key for accessing image data for validation, either a pattern / wildcard or with elf.io.open_file."
1034    )
1035    parser.add_argument(
1036        "--val_label_key", type=str, default=None,
1037        help="The key for accessing label data for validation, either a pattern / wildcard or with elf.io.open_file."
1038    )
1039
1040    # Other necessary stuff for training.
1041    parser.add_argument(
1042        "--configuration", type=str, default=_find_best_configuration(),
1043        help=f"The configuration for finetuning the Segment Anything Model, one of {available_configurations}."
1044    )
1045
1046    def none_or_str(value):
1047        if value.lower() == 'none':
1048            return None
1049        return value
1050
1051    # This could be extended to train for semantic segmentation or other options.
1052    parser.add_argument(
1053        "--segmentation_decoder", type=none_or_str, default="instances",
1054        help="Whether to finetune Segment Anything Model with an additional segmentation decoder. "
1055        "The following options are possible:\n"
1056        "- 'instances' to train with an additional decoder for automatic instance segmentation. "
1057        "  This option enables using the automatic instance segmentation (AIS) mode.\n"
1058        "- 'instances_only' to train only the instance segmentation decoder. "
1059        "  In this case the parts of SAM that are used for interactive segmentation will not be trained.\n"
1060        "- 'None' to train without an additional segmentation decoder."
1061        "  This options trains only the parts of the original SAM.\n"
1062        "By default the option 'instances' is used."
1063    )
1064
1065    # Optional advanced settings a user can opt to change the values for.
1066    parser.add_argument(
1067        "-d", "--device", type=str, default=None,
1068        help="The device to use for finetuning. Can be one of 'cuda', 'cpu' or 'mps' (only MAC). "
1069        "By default the most performant available device will be selected."
1070    )
1071    parser.add_argument(
1072        "--patch_shape", type=int, nargs="*", default=(512, 512),
1073        help="The choice of patch shape for training Segment Anything Model. "
1074        "By default, a patch size of 512x512 is used."
1075    )
1076    parser.add_argument(
1077        "-m", "--model_type", type=str, default=None,
1078        help=f"The Segment Anything Model that will be used for finetuning, one of {available_models}."
1079    )
1080    parser.add_argument(
1081        "--checkpoint_path", type=str, default=None,
1082        help="Checkpoint from which the SAM model will be loaded for finetuning."
1083    )
1084    parser.add_argument(
1085        "-s", "--save_root", type=str, default=None,
1086        help="The directory where the trained models and corresponding logs will be stored. "
1087        "By default, there are stored in your current working directory."
1088    )
1089    parser.add_argument(
1090        "--trained_model_name", type=str, default="sam_model",
1091        help="The custom name of trained model sub-folder. Allows users to have several trained models "
1092        "under the same 'save_root'."
1093    )
1094    parser.add_argument(
1095        "--output_path", type=str, default=None,
1096        help="The directory (eg. '/path/to/folder') or filepath (eg. '/path/to/model.pt') to export the trained model."
1097    )
1098    parser.add_argument(
1099        "--n_epochs", type=int, default=100,
1100        help="The total number of epochs to train the Segment Anything Model. By default, trains for 100 epochs."
1101    )
1102    parser.add_argument(
1103        "--num_workers", type=int, default=1, help="The number of workers for processing data with dataloaders."
1104    )
1105    parser.add_argument(
1106        "--batch_size", type=int, default=1,
1107        help="The choice of batch size for training the Segment Anything Model. By default the batch size is set to 1."
1108    )
1109    parser.add_argument(
1110        "--preprocess", type=str, default=None, choices=("normalize_minmax", "normalize_percentile"),
1111        help="Whether to normalize the raw inputs. By default, does not perform any preprocessing of input images "
1112        "Otherwise, choose from either 'normalize_percentile' or 'normalize_minmax'."
1113    )
1114
1115    args = parser.parse_args(argv)
1116
1117    # 1. Get all necessary stuff for training.
1118    checkpoint_name = args.trained_model_name
1119    config = args.configuration
1120    model_type = args.model_type
1121    checkpoint_path = args.checkpoint_path
1122    batch_size = args.batch_size
1123    patch_shape = args.patch_shape
1124    epochs = args.n_epochs
1125    num_workers = args.num_workers
1126    device = args.device
1127    save_root = args.save_root
1128    output_path = args.output_path
1129    with_segmentation_decoder, train_instance_segmentation_only = _parse_segmentation_decoder(args.segmentation_decoder)
1130
1131    # Get image paths and corresponding keys.
1132    train_images, train_gt, train_image_key, train_gt_key = args.images, args.labels, args.image_key, args.label_key
1133    val_images, val_gt, val_image_key, val_gt_key = args.val_images, args.val_labels, args.val_image_key, args.val_label_key  # noqa
1134
1135    # 2. Prepare the dataloaders.
1136
1137    # If the user wants to preprocess the inputs, we allow the possibility to do so.
1138    _raw_transform = get_raw_transform(args.preprocess)
1139
1140    # Get the dataset with files for training.
1141    dataset = default_sam_dataset(
1142        raw_paths=train_images,
1143        raw_key=train_image_key,
1144        label_paths=train_gt,
1145        label_key=train_gt_key,
1146        patch_shape=patch_shape,
1147        with_segmentation_decoder=with_segmentation_decoder,
1148        raw_transform=_raw_transform,
1149        train_instance_segmentation_only=train_instance_segmentation_only,
1150    )
1151
1152    # If val images are not exclusively provided, we create a val split from the training data.
1153    if val_images is None:
1154        assert val_gt is None and val_image_key is None and val_gt_key is None
1155        # Use 10% of the dataset for validation - at least one image - for validation.
1156        n_val = max(1, int(0.1 * len(dataset)))
1157        train_dataset, val_dataset = random_split(dataset, lengths=[len(dataset) - n_val, n_val])
1158
1159    else:  # If val images provided, we create a new dataset for it.
1160        train_dataset = dataset
1161        val_dataset = default_sam_dataset(
1162            raw_paths=val_images,
1163            raw_key=val_image_key,
1164            label_paths=val_gt,
1165            label_key=val_gt_key,
1166            patch_shape=patch_shape,
1167            with_segmentation_decoder=with_segmentation_decoder,
1168            train_instance_segmentation_only=train_instance_segmentation_only,
1169            raw_transform=_raw_transform,
1170        )
1171
1172    # Get the dataloaders from the datasets.
1173    train_loader = torch_em.get_data_loader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
1174    val_loader = torch_em.get_data_loader(val_dataset, batch_size=1, shuffle=True, num_workers=num_workers)
1175
1176    # 3. Train the Segment Anything Model.
1177
1178    # Get a valid model and other necessary parameters for training.
1179    if model_type is not None and model_type not in available_models:
1180        raise ValueError(f"'{model_type}' is not a valid choice of model.")
1181    if config is not None and config not in available_configurations:
1182        raise ValueError(f"'{config}' is not a valid choice of configuration.")
1183
1184    if model_type is None:  # If user does not specify the model, we use the default model corresponding to the config.
1185        model_type = CONFIGURATIONS[config]["model_type"]
1186
1187    train_sam_for_configuration(
1188        name=checkpoint_name,
1189        configuration=config,
1190        model_type=model_type,
1191        train_loader=train_loader,
1192        val_loader=val_loader,
1193        n_epochs=epochs,
1194        checkpoint_path=checkpoint_path,
1195        with_segmentation_decoder=with_segmentation_decoder,
1196        freeze=None,  # TODO: Allow for PEFT.
1197        device=device,
1198        save_root=save_root,
1199        peft_kwargs=None,  # TODO: Allow for PEFT.
1200        train_instance_segmentation_only=train_instance_segmentation_only,
1201    )
1202
1203    # 4. Export the model, if desired by the user
1204    if train_instance_segmentation_only and output_path:
1205        trained_path = os.path.join("" if save_root is None else save_root, "checkpoints", checkpoint_name, "best.pt")
1206        export_instance_segmentation_model(trained_path, output_path, model_type, checkpoint_path)
1207        final_path = output_path
1208    else:
1209        final_path = _export_helper(
1210            save_root, checkpoint_name, output_path, model_type, with_segmentation_decoder, val_loader,
1211        )
1212
1213    print(f"Training has finished. The trained model is saved at {final_path}.")
FilePath = typing.Union[str, os.PathLike]
def train_sam( name: str, model_type: str, train_loader: torch.utils.data.dataloader.DataLoader, val_loader: torch.utils.data.dataloader.DataLoader, n_epochs: int = 100, early_stopping: Optional[int] = 10, n_objects_per_batch: Optional[int] = 25, checkpoint_path: Union[str, os.PathLike, NoneType] = None, with_segmentation_decoder: bool = True, freeze: Optional[List[str]] = None, device: Union[str, torch.device, NoneType] = None, lr: float = 1e-05, n_sub_iteration: int = 8, save_root: Union[str, os.PathLike, NoneType] = None, mask_prob: float = 0.5, n_iterations: Optional[int] = None, scheduler_class: Optional[torch.optim.lr_scheduler._LRScheduler] = <class 'torch.optim.lr_scheduler.ReduceLROnPlateau'>, scheduler_kwargs: Optional[Dict[str, Any]] = None, save_every_kth_epoch: Optional[int] = None, pbar_signals: Optional[PyQt6.QtCore.QObject] = None, optimizer_class: Optional[torch.optim.optimizer.Optimizer] = <class 'torch.optim.adamw.AdamW'>, peft_kwargs: Optional[Dict] = None, ignore_warnings: bool = True, verify_n_labels_in_loader: Optional[int] = 50, box_distortion_factor: Optional[float] = 0.025, overwrite_training: bool = True, strict_decoder_loading: bool = True, **model_kwargs) -> None:
199def train_sam(
200    name: str,
201    model_type: str,
202    train_loader: DataLoader,
203    val_loader: DataLoader,
204    n_epochs: int = 100,
205    early_stopping: Optional[int] = 10,
206    n_objects_per_batch: Optional[int] = 25,
207    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
208    with_segmentation_decoder: bool = True,
209    freeze: Optional[List[str]] = None,
210    device: Optional[Union[str, torch.device]] = None,
211    lr: float = 1e-5,
212    n_sub_iteration: int = 8,
213    save_root: Optional[Union[str, os.PathLike]] = None,
214    mask_prob: float = 0.5,
215    n_iterations: Optional[int] = None,
216    scheduler_class: Optional[_LRScheduler] = torch.optim.lr_scheduler.ReduceLROnPlateau,
217    scheduler_kwargs: Optional[Dict[str, Any]] = None,
218    save_every_kth_epoch: Optional[int] = None,
219    pbar_signals: Optional[QObject] = None,
220    optimizer_class: Optional[Optimizer] = torch.optim.AdamW,
221    peft_kwargs: Optional[Dict] = None,
222    ignore_warnings: bool = True,
223    verify_n_labels_in_loader: Optional[int] = 50,
224    box_distortion_factor: Optional[float] = 0.025,
225    overwrite_training: bool = True,
226    strict_decoder_loading: bool = True,
227    **model_kwargs,
228) -> None:
229    """Run training for a SAM model.
230
231    Args:
232        name: The name of the model to be trained. The checkpoint and logs will have this name.
233        model_type: The type of the SAM model.
234        train_loader: The dataloader for training.
235        val_loader: The dataloader for validation.
236        n_epochs: The number of epochs to train for.
237        early_stopping: Enable early stopping after this number of epochs without improvement.
238            By default, the value is set to '10' epochs.
239        n_objects_per_batch: The number of objects per batch used to compute
240            the loss for interative segmentation. If None all objects will be used,
241            if given objects will be randomly sub-sampled. By default, the number of objects per batch are '25'.
242        checkpoint_path: Path to checkpoint for initializing the SAM model.
243        with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation.
244            By default, trains with the additional instance segmentation decoder.
245        freeze: Specify parts of the model that should be frozen, namely: image_encoder, prompt_encoder and mask_decoder
246            By default nothing is frozen and the full model is updated.
247        device: The device to use for training. By default, automatically chooses the best available device to train.
248        lr: The learning rate. By default, set to '1e-5'.
249        n_sub_iteration: The number of iterative prompts per training iteration.
250            By default, the number of iterations is set to '8'.
251        save_root: Optional root directory for saving the checkpoints and logs.
252            If not given the current working directory is used.
253        mask_prob: The probability for using a mask as input in a given training sub-iteration.
254            By default, set to '0.5'.
255        n_iterations: The number of iterations to use for training. This will over-ride `n_epochs` if given.
256        scheduler_class: The learning rate scheduler to update the learning rate.
257            By default, `torch.optim.lr_scheduler.ReduceLROnPlateau` is used.
258        scheduler_kwargs: The learning rate scheduler parameters.
259            If passed 'None', the chosen default parameters are used in `ReduceLROnPlateau`.
260        save_every_kth_epoch: Save checkpoints after every kth epoch separately.
261        pbar_signals: Controls for napari progress bar.
262        optimizer_class: The optimizer class. By default, `torch.optim.AdamW` is used.
263        peft_kwargs: Keyword arguments for the PEFT wrapper class.
264        ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
265        verify_n_labels_in_loader: The number of labels to verify out of the train and validation dataloaders.
266            By default, 50 batches of labels are verified from the dataloaders.
267        box_distortion_factor: The factor for distorting the box annotations derived from the ground-truth masks.
268            By default, the distortion factor is set to '0.025'.
269        overwrite_training: Whether to overwrite the trained model stored at the same location.
270            By default, overwrites the trained model at each run.
271            If set to 'False', it will avoid retraining the model if the previous run was completed.
272        strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present,
273            exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output
274            channels if they were pre-trained for a different task. If set to False, decoders with a different
275            output dimension can be loaded; the output channels will be re-initialized.
276        model_kwargs: Additional keyword arguments for the `micro_sam.v1.util.get_sam_model`.
277    """
278    with _filter_warnings(ignore_warnings):
279
280        t_start = time.time()
281        if verify_n_labels_in_loader is not None:
282            _check_loader(train_loader, with_segmentation_decoder, "train", verify_n_labels_in_loader)
283            _check_loader(val_loader, with_segmentation_decoder, "val", verify_n_labels_in_loader)
284
285        device = get_device(device)
286        # Get the trainable segment anything model.
287        model, state = get_trainable_sam_model(
288            model_type=model_type,
289            device=device,
290            freeze=freeze,
291            checkpoint_path=checkpoint_path,
292            return_state=True,
293            peft_kwargs=peft_kwargs,
294            **model_kwargs
295        )
296
297        # This class creates all the training data for a batch (inputs, prompts and labels).
298        convert_inputs = ConvertToSamInputs(transform=model.transform, box_distortion_factor=box_distortion_factor)
299
300        # Create the UNETR decoder (if train with it) and the optimizer.
301        if with_segmentation_decoder:
302
303            # Get the UNETR.
304            unetr = get_unetr(
305                image_encoder=model.sam.image_encoder, decoder_state=state.get("decoder_state", None),
306                device=device, flexible_load_checkpoint=not strict_decoder_loading,
307            )
308
309            # Get the parameters for SAM and the decoder from UNETR.
310            joint_model_params = [params for params in model.parameters()]  # sam parameters
311            for param_name, params in unetr.named_parameters():  # unetr's decoder parameters
312                if not param_name.startswith("encoder"):
313                    joint_model_params.append(params)
314
315            model_params = joint_model_params
316        else:
317            model_params = model.parameters()
318
319        optimizer, scheduler = _get_optimizer_and_scheduler(
320            model_params, lr, optimizer_class, scheduler_class, scheduler_kwargs
321        )
322
323        # The hardware decides the precision. Training runs in bfloat16 only.
324        mixed_precision = training_autocast_dtype(device) is not None
325
326        # The trainer which performs training and validation.
327        if with_segmentation_decoder:
328            instance_seg_loss = torch_em.loss.DiceBasedDistanceLoss(mask_distances_in_bg=True)
329            trainer = joint_trainers.JointSamTrainer(
330                name=name,
331                save_root=save_root,
332                train_loader=train_loader,
333                val_loader=val_loader,
334                model=model,
335                optimizer=optimizer,
336                device=device,
337                lr_scheduler=scheduler,
338                logger=joint_trainers.JointSamLogger,
339                log_image_interval=100,
340                mixed_precision=mixed_precision,
341                mixed_precision_dtype="bfloat16",
342                convert_inputs=convert_inputs,
343                n_objects_per_batch=n_objects_per_batch,
344                n_sub_iteration=n_sub_iteration,
345                compile_model=False,
346                unetr=unetr,
347                instance_loss=instance_seg_loss,
348                instance_metric=instance_seg_loss,
349                early_stopping=early_stopping,
350                mask_prob=mask_prob,
351            )
352        else:
353            trainer = trainers.SamTrainer(
354                name=name,
355                train_loader=train_loader,
356                val_loader=val_loader,
357                model=model,
358                optimizer=optimizer,
359                device=device,
360                lr_scheduler=scheduler,
361                logger=trainers.SamLogger,
362                log_image_interval=100,
363                mixed_precision=mixed_precision,
364                mixed_precision_dtype="bfloat16",
365                convert_inputs=convert_inputs,
366                n_objects_per_batch=n_objects_per_batch,
367                n_sub_iteration=n_sub_iteration,
368                compile_model=False,
369                early_stopping=early_stopping,
370                mask_prob=mask_prob,
371                save_root=save_root,
372            )
373
374        trainer_fit_params = _get_trainer_fit_params(
375            n_epochs, n_iterations, save_every_kth_epoch, pbar_signals, overwrite_training
376        )
377        trainer.fit(**trainer_fit_params)
378
379        t_run = time.time() - t_start
380        hours = int(t_run // 3600)
381        minutes = int(t_run // 60)
382        seconds = int(round(t_run % 60, 0))
383        print("Training took", t_run, f"seconds (= {hours:02}:{minutes:02}:{seconds:02} hours)")

Run training for a SAM model.

Arguments:
  • name: The name of the model to be trained. The checkpoint and logs will have this name.
  • model_type: The type of the SAM model.
  • train_loader: The dataloader for training.
  • val_loader: The dataloader for validation.
  • n_epochs: The number of epochs to train for.
  • early_stopping: Enable early stopping after this number of epochs without improvement. By default, the value is set to '10' epochs.
  • n_objects_per_batch: The number of objects per batch used to compute the loss for interative segmentation. If None all objects will be used, if given objects will be randomly sub-sampled. By default, the number of objects per batch are '25'.
  • checkpoint_path: Path to checkpoint for initializing the SAM model.
  • with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation. By default, trains with the additional instance segmentation decoder.
  • freeze: Specify parts of the model that should be frozen, namely: image_encoder, prompt_encoder and mask_decoder By default nothing is frozen and the full model is updated.
  • device: The device to use for training. By default, automatically chooses the best available device to train.
  • lr: The learning rate. By default, set to '1e-5'.
  • n_sub_iteration: The number of iterative prompts per training iteration. By default, the number of iterations is set to '8'.
  • save_root: Optional root directory for saving the checkpoints and logs. If not given the current working directory is used.
  • mask_prob: The probability for using a mask as input in a given training sub-iteration. By default, set to '0.5'.
  • n_iterations: The number of iterations to use for training. This will over-ride n_epochs if given.
  • scheduler_class: The learning rate scheduler to update the learning rate. By default, torch.optim.lr_scheduler.ReduceLROnPlateau is used.
  • scheduler_kwargs: The learning rate scheduler parameters. If passed 'None', the chosen default parameters are used in ReduceLROnPlateau.
  • save_every_kth_epoch: Save checkpoints after every kth epoch separately.
  • pbar_signals: Controls for napari progress bar.
  • optimizer_class: The optimizer class. By default, torch.optim.AdamW is used.
  • peft_kwargs: Keyword arguments for the PEFT wrapper class.
  • ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
  • verify_n_labels_in_loader: The number of labels to verify out of the train and validation dataloaders. By default, 50 batches of labels are verified from the dataloaders.
  • box_distortion_factor: The factor for distorting the box annotations derived from the ground-truth masks. By default, the distortion factor is set to '0.025'.
  • overwrite_training: Whether to overwrite the trained model stored at the same location. By default, overwrites the trained model at each run. If set to 'False', it will avoid retraining the model if the previous run was completed.
  • strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present, exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output channels if they were pre-trained for a different task. If set to False, decoders with a different output dimension can be loaded; the output channels will be re-initialized.
  • model_kwargs: Additional keyword arguments for the micro_sam.v1.util.get_sam_model.
def export_instance_segmentation_model( trained_model_path: Union[str, os.PathLike], output_path: Union[str, os.PathLike], model_type: str, initial_checkpoint_path: Union[str, os.PathLike, NoneType] = None) -> None:
386def export_instance_segmentation_model(
387    trained_model_path: Union[str, os.PathLike],
388    output_path: Union[str, os.PathLike],
389    model_type: str,
390    initial_checkpoint_path: Optional[Union[str, os.PathLike]] = None,
391) -> None:
392    """Export a model trained for instance segmentation with `train_instance_segmentation`.
393
394    The exported model will be compatible with the micro_sam functions, CLI and napari plugin.
395    It should only be used for automatic segmentation and may not work well for interactive segmentation.
396
397    Args:
398        trained_model_path: The path to the checkpoint of the model trained for instance segmentation.
399        output_path: The path where the exported model will be saved.
400        model_type: The model type.
401        initial_checkpoint_path: The initial checkpoint path the instance segmentation training was based on (optional).
402    """
403    state = torch.load(trained_model_path, weights_only=False, map_location="cpu")
404    trained_state = state.get("model_state", state)
405
406    # Get the state of the encoder and instance segmentation decoder from the trained checkpoint.
407    encoder_state = OrderedDict([(k, v) for k, v in trained_state.items() if k.startswith("encoder")])
408    decoder_state = OrderedDict([(k, v) for k, v in trained_state.items() if not k.startswith("encoder")])
409
410    # Load the original state of the model that was used as the basis of instance segmentation training.
411    predictor = get_sam_model(
412        model_type=model_type, checkpoint_path=initial_checkpoint_path, device="cpu",
413    )
414    model_state = OrderedDict(predictor.model.state_dict())
415
416    # Replace the image encoder weights with the trained ones.
417    # UNETR stores the image encoder as "encoder.*"; SAM uses "image_encoder.*".
418    for k in list(model_state.keys()):
419        if k.startswith("image_encoder."):
420            encoder_key = "encoder." + k[len("image_encoder."):]
421            model_state[k] = encoder_state[encoder_key]
422
423    save_state = {"model_state": model_state, "decoder_state": decoder_state}
424    torch.save(save_state, output_path)

Export a model trained for instance segmentation with train_instance_segmentation.

The exported model will be compatible with the micro_sam functions, CLI and napari plugin. It should only be used for automatic segmentation and may not work well for interactive segmentation.

Arguments:
  • trained_model_path: The path to the checkpoint of the model trained for instance segmentation.
  • output_path: The path where the exported model will be saved.
  • model_type: The model type.
  • initial_checkpoint_path: The initial checkpoint path the instance segmentation training was based on (optional).
def train_instance_segmentation( name: str, model_type: str, train_loader: torch.utils.data.dataloader.DataLoader, val_loader: torch.utils.data.dataloader.DataLoader, n_epochs: int = 100, early_stopping: Optional[int] = 10, loss: torch.nn.modules.module.Module = DiceBasedDistanceLoss( (foreground_loss): DiceLoss() (distance_loss): DiceLoss() ), metric: Optional[torch.nn.modules.module.Module] = None, checkpoint_path: Union[str, os.PathLike, NoneType] = None, freeze: Optional[List[str]] = None, device: Union[str, torch.device, NoneType] = None, lr: float = 1e-05, save_root: Union[str, os.PathLike, NoneType] = None, n_iterations: Optional[int] = None, scheduler_class: Optional[torch.optim.lr_scheduler._LRScheduler] = <class 'torch.optim.lr_scheduler.ReduceLROnPlateau'>, scheduler_kwargs: Optional[Dict[str, Any]] = None, save_every_kth_epoch: Optional[int] = None, pbar_signals: Optional[PyQt6.QtCore.QObject] = None, optimizer_class: Optional[torch.optim.optimizer.Optimizer] = <class 'torch.optim.adamw.AdamW'>, peft_kwargs: Optional[Dict] = None, ignore_warnings: bool = True, overwrite_training: bool = True, strict_decoder_loading: bool = True, **model_kwargs) -> None:
427def train_instance_segmentation(
428    name: str,
429    model_type: str,
430    train_loader: DataLoader,
431    val_loader: DataLoader,
432    n_epochs: int = 100,
433    early_stopping: Optional[int] = 10,
434    loss: torch.nn.Module = torch_em.loss.DiceBasedDistanceLoss(mask_distances_in_bg=True),
435    metric: Optional[torch.nn.Module] = None,
436    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
437    freeze: Optional[List[str]] = None,
438    device: Optional[Union[str, torch.device]] = None,
439    lr: float = 1e-5,
440    save_root: Optional[Union[str, os.PathLike]] = None,
441    n_iterations: Optional[int] = None,
442    scheduler_class: Optional[_LRScheduler] = torch.optim.lr_scheduler.ReduceLROnPlateau,
443    scheduler_kwargs: Optional[Dict[str, Any]] = None,
444    save_every_kth_epoch: Optional[int] = None,
445    pbar_signals: Optional[QObject] = None,
446    optimizer_class: Optional[Optimizer] = torch.optim.AdamW,
447    peft_kwargs: Optional[Dict] = None,
448    ignore_warnings: bool = True,
449    overwrite_training: bool = True,
450    strict_decoder_loading: bool = True,
451    **model_kwargs,
452) -> None:
453    """Train a UNETR for instance segmentation using the SAM encoder as backbone.
454
455    This setting corresponds to training a SAM model with an instance segmentation decoder,
456    without training the model parts for interactive segmentation,
457    i.e. without training the prompt encoder and mask decoder.
458
459    The checkpoint of the trained model, which will be saved in 'checkpoints/<name>',
460    will not be compatible with the micro_sam functionality.
461    You can call the function `export_instance_segmentation_model` with the path to the checkpoint to export it
462    in a format that is compatible with micro_sam functionality.
463    Note that the exported model should only be used for automatic segmentation via AIS.
464
465    Args:
466        name: The name of the model to be trained. The checkpoint and logs will have this name.
467        model_type: The type of the SAM model.
468        train_loader: The dataloader for training.
469        val_loader: The dataloader for validation.
470        n_epochs: The number of epochs to train for.
471        early_stopping: Enable early stopping after this number of epochs without improvement.
472            By default, the value is set to '10' epochs.
473        loss: The loss function to train the instance segmentation model.
474            By default, the value is set to 'torch_em.loss.DiceBasedDistanceLoss'
475        metric: The metric for the instance segmentation training.
476            By default the loss function is used as the metric.
477        checkpoint_path: Path to checkpoint for initializing the SAM model.
478        freeze: Specify parts of the model that should be frozen. Here, only the image_encoder can be frozen.
479            By default nothing is frozen and the full model is updated.
480        device: The device to use for training. By default, automatically chooses the best available device to train.
481        lr: The learning rate. By default, set to '1e-5'.
482        save_root: Optional root directory for saving the checkpoints and logs.
483            If not given the current working directory is used.
484        n_iterations: The number of iterations to use for training. This will over-ride `n_epochs` if given.
485        scheduler_class: The learning rate scheduler to update the learning rate.
486            By default, `torch.optim.lr_scheduler.ReduceLROnPlateau` is used.
487        scheduler_kwargs: The learning rate scheduler parameters.
488            If passed 'None', the chosen default parameters are used in `ReduceLROnPlateau`.
489        save_every_kth_epoch: Save checkpoints after every kth epoch separately.
490        pbar_signals: Controls for napari progress bar.
491        optimizer_class: The optimizer class. By default, `torch.optim.AdamW` is used.
492        peft_kwargs: Keyword arguments for the PEFT wrapper class.
493        ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
494        overwrite_training: Whether to overwrite the trained model stored at the same location.
495            By default, overwrites the trained model at each run.
496            If set to 'False', it will avoid retraining the model if the previous run was completed.
497        strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present,
498            exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output
499            channels if they were pre-trained for a different task. If set to False, decoders with a different
500            output dimension can be loaded; the output channels will be re-initialized.
501        model_kwargs: Additional keyword arguments for the `micro_sam.v1.util.get_sam_model`.
502    """
503
504    with _filter_warnings(ignore_warnings):
505        t_start = time.time()
506
507        sam_model, state = get_trainable_sam_model(
508            model_type=model_type,
509            device=device,
510            checkpoint_path=checkpoint_path,
511            return_state=True,
512            peft_kwargs=peft_kwargs,
513            freeze=freeze,
514            **model_kwargs
515        )
516        device = get_device(device)
517        model = get_unetr(
518            image_encoder=sam_model.sam.image_encoder, decoder_state=state.get("decoder_state", None),
519            device=device, flexible_load_checkpoint=not strict_decoder_loading,
520        )
521
522        optimizer, scheduler = _get_optimizer_and_scheduler(
523            model.parameters(), lr, optimizer_class, scheduler_class, scheduler_kwargs
524        )
525        trainer = torch_em.trainer.DefaultTrainer(
526            name=name,
527            model=model,
528            train_loader=train_loader,
529            val_loader=val_loader,
530            device=device,
531            # The hardware decides the precision. Training runs in bfloat16 only.
532            mixed_precision=training_autocast_dtype(device) is not None,
533            mixed_precision_dtype="bfloat16",
534            log_image_interval=50,
535            compile_model=False,
536            save_root=save_root,
537            loss=loss,
538            metric=loss if metric is None else metric,
539            optimizer=optimizer,
540            lr_scheduler=scheduler,
541            early_stopping=early_stopping,
542        )
543
544        trainer_fit_params = _get_trainer_fit_params(
545            n_epochs, n_iterations, save_every_kth_epoch, pbar_signals, overwrite_training
546        )
547        trainer.fit(**trainer_fit_params)
548
549        t_run = time.time() - t_start
550        hours = int(t_run // 3600)
551        minutes = int(t_run // 60)
552        seconds = int(round(t_run % 60, 0))
553        print("Training took", t_run, f"seconds (= {hours:02}:{minutes:02}:{seconds:02} hours)")

Train a UNETR for instance segmentation using the SAM encoder as backbone.

This setting corresponds to training a SAM model with an instance segmentation decoder, without training the model parts for interactive segmentation, i.e. without training the prompt encoder and mask decoder.

The checkpoint of the trained model, which will be saved in 'checkpoints/', will not be compatible with the micro_sam functionality. You can call the function export_instance_segmentation_model with the path to the checkpoint to export it in a format that is compatible with micro_sam functionality. Note that the exported model should only be used for automatic segmentation via AIS.

Arguments:
  • name: The name of the model to be trained. The checkpoint and logs will have this name.
  • model_type: The type of the SAM model.
  • train_loader: The dataloader for training.
  • val_loader: The dataloader for validation.
  • n_epochs: The number of epochs to train for.
  • early_stopping: Enable early stopping after this number of epochs without improvement. By default, the value is set to '10' epochs.
  • loss: The loss function to train the instance segmentation model. By default, the value is set to 'torch_em.loss.DiceBasedDistanceLoss'
  • metric: The metric for the instance segmentation training. By default the loss function is used as the metric.
  • checkpoint_path: Path to checkpoint for initializing the SAM model.
  • freeze: Specify parts of the model that should be frozen. Here, only the image_encoder can be frozen. By default nothing is frozen and the full model is updated.
  • device: The device to use for training. By default, automatically chooses the best available device to train.
  • lr: The learning rate. By default, set to '1e-5'.
  • save_root: Optional root directory for saving the checkpoints and logs. If not given the current working directory is used.
  • n_iterations: The number of iterations to use for training. This will over-ride n_epochs if given.
  • scheduler_class: The learning rate scheduler to update the learning rate. By default, torch.optim.lr_scheduler.ReduceLROnPlateau is used.
  • scheduler_kwargs: The learning rate scheduler parameters. If passed 'None', the chosen default parameters are used in ReduceLROnPlateau.
  • save_every_kth_epoch: Save checkpoints after every kth epoch separately.
  • pbar_signals: Controls for napari progress bar.
  • optimizer_class: The optimizer class. By default, torch.optim.AdamW is used.
  • peft_kwargs: Keyword arguments for the PEFT wrapper class.
  • ignore_warnings: Whether to ignore raised warnings. By default, set to 'True'.
  • overwrite_training: Whether to overwrite the trained model stored at the same location. By default, overwrites the trained model at each run. If set to 'False', it will avoid retraining the model if the previous run was completed.
  • strict_decoder_loading: Whether to require that the pre-trained decoder in the checkpoint, if present, exactly matches the instance segmentation decoder. Decoders may have a mismatch in the output channels if they were pre-trained for a different task. If set to False, decoders with a different output dimension can be loaded; the output channels will be re-initialized.
  • model_kwargs: Additional keyword arguments for the micro_sam.v1.util.get_sam_model.
def default_sam_dataset( raw_paths: Union[List[Union[numpy.ndarray, torch.Tensor]], List[Union[str, os.PathLike]], str, os.PathLike], raw_key: Optional[str], label_paths: Union[List[Union[numpy.ndarray, torch.Tensor]], List[Union[str, os.PathLike]], str, os.PathLike], label_key: Optional[str], patch_shape: Tuple[int], with_segmentation_decoder: bool, with_channels: Optional[bool] = None, train_instance_segmentation_only: bool = False, sampler: Optional[Callable] = None, raw_transform: Optional[Callable] = None, n_samples: Optional[int] = None, is_train: bool = True, min_size: int = 25, max_sampling_attempts: Optional[int] = None, rois: Union[slice, Tuple[slice, ...], NoneType] = None, is_multi_tensor: bool = True, **kwargs) -> torch.utils.data.dataset.Dataset:
634def default_sam_dataset(
635    raw_paths: Union[List[Union[np.ndarray, torch.Tensor]], List[FilePath], FilePath],
636    raw_key: Optional[str],
637    label_paths: Union[List[Union[np.ndarray, torch.Tensor]], List[FilePath], FilePath],
638    label_key: Optional[str],
639    patch_shape: Tuple[int],
640    with_segmentation_decoder: bool,
641    with_channels: Optional[bool] = None,
642    train_instance_segmentation_only: bool = False,
643    sampler: Optional[Callable] = None,
644    raw_transform: Optional[Callable] = None,
645    n_samples: Optional[int] = None,
646    is_train: bool = True,
647    min_size: int = 25,
648    max_sampling_attempts: Optional[int] = None,
649    rois: Optional[Union[slice, Tuple[slice, ...]]] = None,
650    is_multi_tensor: bool = True,
651    **kwargs,
652) -> Dataset:
653    """Create a PyTorch Dataset for training a SAM model.
654
655    Args:
656        raw_paths: The path(s) to the image data used for training.
657            Can either be multiple 2D images or volumetric data.
658            The data can also be passed as a list of numpy arrays or torch tensors.
659        raw_key: The key for accessing the image data. Internal filepath for hdf5-like input
660            or a glob pattern for selecting multiple files.
661            Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
662        label_paths: The path(s) to the label data used for training.
663            Can either be multiple 2D images or volumetric data.
664            The data can also be passed as a list of numpy arrays or torch tensors.
665        label_key: The key for accessing the label data. Internal filepath for hdf5-like input
666            or a glob pattern for selecting multiple files.
667            Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
668        patch_shape: The shape for training patches.
669        with_segmentation_decoder: Whether to train with additional segmentation decoder.
670        with_channels: Whether the image data has channels. By default, it makes the decision based on inputs.
671        train_instance_segmentation_only: Set this argument to True in order to
672            pass the dataset to `train_instance_segmentation`. By default, set to 'False'.
673        sampler: A sampler to reject batches according to a given criterion.
674        raw_transform: Transformation applied to the image data.
675            If not given the data will be cast to 8bit.
676        n_samples: The number of samples for this dataset.
677        is_train: Whether this dataset is used for training or validation. By default, set to 'True'.
678        min_size: Minimal object size. Smaller objects will be filtered. By default, set to '25'.
679        max_sampling_attempts: Number of sampling attempts to make from a dataset.
680        rois: The region of interest(s) for the data.
681        is_multi_tensor: Whether the input data to data transforms is multiple tensors or not.
682        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
683
684    Returns:
685        The segmentation dataset.
686    """
687
688    # Check if this dataset should be used for instance segmentation only training.
689    # If yes, we set return_instances to False, since the instance channel must not
690    # be passed for this training mode.
691    return_instances = True
692    if train_instance_segmentation_only:
693        if not with_segmentation_decoder:
694            raise ValueError(
695                "If 'train_instance_segmentation_only' is True, then 'with_segmentation_decoder' must also be True."
696            )
697        return_instances = False
698
699    # If a sampler is not passed, then we set a MinInstanceSampler, which requires 3 distinct instances per sample.
700    # This is necessary, because training for interactive segmentation does not work on 'empty' images.
701    # However, if we train only the automatic instance segmentation decoder, then this sampler is not required
702    # and we do not set a default sampler.
703    if sampler is None and not train_instance_segmentation_only:
704        sampler = torch_em.data.sampler.MinInstanceSampler(2, min_size=min_size)
705
706    is_seg_dataset, with_channels = _determine_dataset_and_channels(
707        raw_paths, raw_key, label_paths, label_key, with_channels, **kwargs
708    )
709    # Since `is_seg_dataset` is selected and sorted above, let's remove it out of running kwargs, if available.
710    kwargs.pop("is_seg_dataset", None)
711
712    # Set the data transformations.
713    if raw_transform is None:
714        raw_transform = require_8bit
715
716    # Prepare the label transform.
717    if with_segmentation_decoder:
718        default_label_transform = torch_em.transform.label.PerObjectDistanceTransform(
719            distances=True,
720            boundary_distances=True,
721            directed_distances=False,
722            foreground=True,
723            instances=return_instances,
724            min_size=min_size,
725        )
726    else:
727        default_label_transform = torch_em.transform.label.MinSizeLabelTransform(min_size=min_size)
728
729    # Allow combining label transforms.
730    custom_label_transform = kwargs.pop("label_transform", None)
731    if custom_label_transform is None:
732        label_transform = default_label_transform
733    else:
734        label_transform = torch_em.transform.generic.Compose(
735            custom_label_transform, default_label_transform, is_multi_tensor=is_multi_tensor
736        )
737
738    # Check the patch shape to add a singleton if required.
739    patch_shape = _update_patch_shape(
740        patch_shape=patch_shape, raw_paths=raw_paths, raw_key=raw_key, with_channels=with_channels,
741    )
742
743    # Set a minimum number of samples per epoch.
744    if n_samples is None:
745        loader = torch_em.default_segmentation_loader(
746            raw_paths=raw_paths,
747            raw_key=raw_key,
748            label_paths=label_paths,
749            label_key=label_key,
750            batch_size=1,
751            patch_shape=patch_shape,
752            with_channels=with_channels,
753            ndim=2,
754            is_seg_dataset=is_seg_dataset,
755            raw_transform=raw_transform,
756            rois=rois,
757            **kwargs
758        )
759        n_samples = max(len(loader), 100 if is_train else 5)
760
761    dataset = torch_em.default_segmentation_dataset(
762        raw_paths=raw_paths,
763        raw_key=raw_key,
764        label_paths=label_paths,
765        label_key=label_key,
766        patch_shape=patch_shape,
767        raw_transform=raw_transform,
768        label_transform=label_transform,
769        with_channels=with_channels,
770        ndim=2,
771        sampler=sampler,
772        n_samples=n_samples,
773        is_seg_dataset=is_seg_dataset,
774        rois=rois,
775        **kwargs,
776    )
777
778    if max_sampling_attempts is not None:
779        if isinstance(dataset, torch_em.data.concat_dataset.ConcatDataset):
780            for ds in dataset.datasets:
781                ds.max_sampling_attempts = max_sampling_attempts
782        else:
783            dataset.max_sampling_attempts = max_sampling_attempts
784
785    return dataset

Create a PyTorch Dataset for training a SAM model.

Arguments:
  • raw_paths: The path(s) to the image data used for training. Can either be multiple 2D images or volumetric data. The data can also be passed as a list of numpy arrays or torch tensors.
  • raw_key: The key for accessing the image data. Internal filepath for hdf5-like input or a glob pattern for selecting multiple files. Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
  • label_paths: The path(s) to the label data used for training. Can either be multiple 2D images or volumetric data. The data can also be passed as a list of numpy arrays or torch tensors.
  • label_key: The key for accessing the label data. Internal filepath for hdf5-like input or a glob pattern for selecting multiple files. Set to None when passing a list of file paths to regular images or numpy arrays / torch tensors.
  • patch_shape: The shape for training patches.
  • with_segmentation_decoder: Whether to train with additional segmentation decoder.
  • with_channels: Whether the image data has channels. By default, it makes the decision based on inputs.
  • train_instance_segmentation_only: Set this argument to True in order to pass the dataset to train_instance_segmentation. By default, set to 'False'.
  • sampler: A sampler to reject batches according to a given criterion.
  • raw_transform: Transformation applied to the image data. If not given the data will be cast to 8bit.
  • n_samples: The number of samples for this dataset.
  • is_train: Whether this dataset is used for training or validation. By default, set to 'True'.
  • min_size: Minimal object size. Smaller objects will be filtered. By default, set to '25'.
  • max_sampling_attempts: Number of sampling attempts to make from a dataset.
  • rois: The region of interest(s) for the data.
  • is_multi_tensor: Whether the input data to data transforms is multiple tensors or not.
  • kwargs: Additional keyword arguments for torch_em.default_segmentation_dataset.
Returns:

The segmentation dataset.

def default_sam_loader(**kwargs) -> torch.utils.data.dataloader.DataLoader:
788def default_sam_loader(**kwargs) -> DataLoader:
789    """Create a PyTorch DataLoader for training a SAM model.
790
791    Args:
792        kwargs: Keyword arguments for `micro_sam.v1.training.default_sam_dataset` or for the PyTorch DataLoader.
793
794    Returns:
795        The DataLoader.
796    """
797    sam_ds_kwargs, extra_kwargs = split_kwargs(default_sam_dataset, **kwargs)
798
799    # There might be additional parameters supported by `torch_em.default_segmentation_dataset`,
800    # which the users can provide to get their desired segmentation dataset.
801    extra_ds_kwargs, loader_kwargs = split_kwargs(torch_em.default_segmentation_dataset, **extra_kwargs)
802    ds_kwargs = {**sam_ds_kwargs, **extra_ds_kwargs}
803
804    ds = default_sam_dataset(**ds_kwargs)
805    return torch_em.segmentation.get_data_loader(ds, **loader_kwargs)

Create a PyTorch DataLoader for training a SAM model.

Arguments:
Returns:

The DataLoader.

CONFIGURATIONS = {'Minimal': {'model_type': 'vit_t', 'n_objects_per_batch': 4, 'n_sub_iteration': 4}, 'CPU': {'model_type': 'vit_b', 'n_objects_per_batch': 10}, 'gtx1080': {'model_type': 'vit_t', 'n_objects_per_batch': 5}, 'gtx3080': {'model_type': 'vit_b', 'n_objects_per_batch': 5, 'peft_kwargs': {'attention_layers_to_update': [11], 'peft_module': <class 'micro_sam.models.peft.ClassicalSurgery'>}}, 'rtx5000': {'model_type': 'vit_b', 'n_objects_per_batch': 10}, 'V100': {'model_type': 'vit_b'}, 'A100': {'model_type': 'vit_h'}}

Best training configurations for given hardware resources.

def train_sam_for_configuration( name: str, train_loader: torch.utils.data.dataloader.DataLoader, val_loader: torch.utils.data.dataloader.DataLoader, configuration: Optional[str] = None, checkpoint_path: Union[str, os.PathLike, NoneType] = None, with_segmentation_decoder: bool = True, train_instance_segmentation_only: bool = False, model_type: Optional[str] = None, **kwargs) -> None:
847def train_sam_for_configuration(
848    name: str,
849    train_loader: DataLoader,
850    val_loader: DataLoader,
851    configuration: Optional[str] = None,
852    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
853    with_segmentation_decoder: bool = True,
854    train_instance_segmentation_only: bool = False,
855    model_type: Optional[str] = None,
856    **kwargs,
857) -> None:
858    """Run training for a SAM model with the configuration for a given hardware resource.
859
860    Selects the best training settings for the given configuration.
861    The available configurations are listed in `CONFIGURATIONS`.
862
863    Args:
864        name: The name of the model to be trained. The checkpoint and logs folder will have this name.
865        train_loader: The dataloader for training.
866        val_loader: The dataloader for validation.
867        configuration: The configuration (= name of hardware resource).
868            By default, it is automatically selected for the best VRAM combination.
869        checkpoint_path: Path to checkpoint for initializing the SAM model.
870        with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation.
871            By default, trains with the additional instance segmentation decoder.
872        train_instance_segmentation_only: Whether to train a model only for automatic instance segmentation
873            using the training implementation `train_instance_segmentation`. By default, `train_sam` is used.
874        model_type: Over-ride the default model type.
875            This can be used to use one of the micro_sam models as starting point
876            instead of a default sam model.
877        kwargs: Additional keyword parameters that will be passed to `train_sam`.
878    """
879    if configuration is None:  # Automatically choose based on available VRAM combination.
880        configuration = _find_best_configuration()
881
882    if configuration in CONFIGURATIONS:
883        train_kwargs = CONFIGURATIONS[configuration]
884    else:
885        raise ValueError(f"Invalid configuration {configuration} expect one of {list(CONFIGURATIONS.keys())}")
886
887    if model_type is None:
888        model_type = train_kwargs.pop("model_type")
889    else:
890        expected_model_type = train_kwargs.pop("model_type")
891        if model_type[:5] != expected_model_type:
892            warnings.warn("You have specified a different model type.")
893
894    train_kwargs.update(**kwargs)
895    if train_instance_segmentation_only:
896        instance_seg_kwargs, extra_kwargs = split_kwargs(train_instance_segmentation, **train_kwargs)
897        model_kwargs, extra_kwargs = split_kwargs(get_sam_model, **extra_kwargs)
898        instance_seg_kwargs.update(**model_kwargs)
899
900        train_instance_segmentation(
901            name=name,
902            train_loader=train_loader,
903            val_loader=val_loader,
904            checkpoint_path=checkpoint_path,
905            model_type=model_type,
906            **instance_seg_kwargs,
907        )
908    else:
909        train_sam(
910            name=name,
911            train_loader=train_loader,
912            val_loader=val_loader,
913            checkpoint_path=checkpoint_path,
914            with_segmentation_decoder=with_segmentation_decoder,
915            model_type=model_type,
916            **train_kwargs
917        )

Run training for a SAM model with the configuration for a given hardware resource.

Selects the best training settings for the given configuration. The available configurations are listed in CONFIGURATIONS.

Arguments:
  • name: The name of the model to be trained. The checkpoint and logs folder will have this name.
  • train_loader: The dataloader for training.
  • val_loader: The dataloader for validation.
  • configuration: The configuration (= name of hardware resource). By default, it is automatically selected for the best VRAM combination.
  • checkpoint_path: Path to checkpoint for initializing the SAM model.
  • with_segmentation_decoder: Whether to train additional UNETR decoder for automatic instance segmentation. By default, trains with the additional instance segmentation decoder.
  • train_instance_segmentation_only: Whether to train a model only for automatic instance segmentation using the training implementation train_instance_segmentation. By default, train_sam is used.
  • model_type: Over-ride the default model type. This can be used to use one of the micro_sam models as starting point instead of a default sam model.
  • kwargs: Additional keyword parameters that will be passed to train_sam.