|
| 1 | +import os |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | +import torch_em |
| 6 | + |
| 7 | +import micro_sam.training as sam_training |
| 8 | +from micro_sam.sample_data import fetch_tracking_example_data, fetch_tracking_segmentation_data |
| 9 | +from micro_sam.util import export_custom_sam_model |
| 10 | + |
| 11 | +DATA_FOLDER = "data" |
| 12 | + |
| 13 | + |
| 14 | +def get_dataloader(split, patch_shape, batch_size): |
| 15 | + """Return train or val data loader for finetuning SAM. |
| 16 | +
|
| 17 | + The data loader must be a torch data loader that retuns `x, y` tensors, |
| 18 | + where `x` is the image data and `y` are the labels. |
| 19 | + The labels have to be in a label mask instance segmentation format. |
| 20 | + I.e. a tensor of the same spatial shape as `x`, with each object mask having its own ID. |
| 21 | + Important: the ID 0 is reseved for background, and the IDs must be consecutive |
| 22 | +
|
| 23 | + Here, we use `torch_em.default_segmentation_loader` for creating a suitable data loader from |
| 24 | + the example hela data. You can either adapt this for your own data (see comments below) |
| 25 | + or write a suitable torch dataloader yourself. |
| 26 | + """ |
| 27 | + assert split in ("train", "val") |
| 28 | + os.makedirs(DATA_FOLDER, exist_ok=True) |
| 29 | + |
| 30 | + # This will download the image and segmentation data for training. |
| 31 | + image_dir = fetch_tracking_example_data(DATA_FOLDER) |
| 32 | + segmentation_dir = fetch_tracking_segmentation_data(DATA_FOLDER) |
| 33 | + |
| 34 | + # torch_em.default_segmentation_loader is a convenience function to build a torch dataloader |
| 35 | + # from image data and labels for training segmentation models. |
| 36 | + # It supports image data in various formats. Here, we load image data and labels from the two |
| 37 | + # folders with tif images that were downloaded by the example data functionality, by specifying |
| 38 | + # `raw_key` and `label_key` as `*.tif`. This means all images in the respective folders that end with |
| 39 | + # .tif will be loadded. |
| 40 | + # The function supports many other file formats. For example, if you have tif stacks with multiple slices |
| 41 | + # instead of multiple tif images in a foldder, then you can pass raw_key=label_key=None. |
| 42 | + |
| 43 | + # Load images from multiple files in folder via pattern (here: all tif files) |
| 44 | + raw_key, label_key = "*.tif", "*.tif" |
| 45 | + # Alternative: if you have tif stacks you can just set raw_key and label_key to None |
| 46 | + # raw_key, label_key= None, None |
| 47 | + |
| 48 | + # The 'roi' argument can be used to subselect parts of the data. |
| 49 | + # Here, we use it to select the first 70 frames fro the test split and the other frames for the val split. |
| 50 | + if split == "train": |
| 51 | + roi = np.s_[:70, :, :] |
| 52 | + else: |
| 53 | + roi = np.s_[70:, :, :] |
| 54 | + |
| 55 | + loader = torch_em.default_segmentation_loader( |
| 56 | + raw_paths=image_dir, raw_key=raw_key, |
| 57 | + label_paths=segmentation_dir, label_key=label_key, |
| 58 | + patch_shape=patch_shape, batch_size=batch_size, |
| 59 | + ndim=2, is_seg_dataset=True, rois=roi, |
| 60 | + label_transform=torch_em.transform.label.connected_components, |
| 61 | + ) |
| 62 | + return loader |
| 63 | + |
| 64 | + |
| 65 | +def run_training(checkpoint_name, model_type): |
| 66 | + """Run the actual model training.""" |
| 67 | + |
| 68 | + # All hyperparameters for training. |
| 69 | + batch_size = 1 # the training batch size |
| 70 | + patch_shape = (1, 512, 512) # the size of patches for training |
| 71 | + n_objects_per_batch = 25 # the number of objects per batch that will be sampled |
| 72 | + device = torch.device("cuda") # the device/GPU used for training |
| 73 | + n_iterations = 10000 # how long we train (in iterations) |
| 74 | + |
| 75 | + # Get the dataloaders. |
| 76 | + train_loader = get_dataloader("train", patch_shape, batch_size) |
| 77 | + val_loader = get_dataloader("val", patch_shape, batch_size) |
| 78 | + |
| 79 | + # Get the segment anything model, the optimizer and the LR scheduler |
| 80 | + model = sam_training.get_trainable_sam_model(model_type=model_type, device=device) |
| 81 | + optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) |
| 82 | + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.9, patience=10, verbose=True) |
| 83 | + |
| 84 | + # This class creates all the training data for a batch (inputs, prompts and labels). |
| 85 | + convert_inputs = sam_training.ConvertToSamInputs() |
| 86 | + |
| 87 | + # the trainer which performs training and validation (implemented using "torch_em") |
| 88 | + trainer = sam_training.SamTrainer( |
| 89 | + name=checkpoint_name, |
| 90 | + train_loader=train_loader, |
| 91 | + val_loader=val_loader, |
| 92 | + model=model, |
| 93 | + optimizer=optimizer, |
| 94 | + # currently we compute loss batch-wise, else we pass channelwise True |
| 95 | + loss=torch_em.loss.DiceLoss(channelwise=False), |
| 96 | + metric=torch_em.loss.DiceLoss(), |
| 97 | + device=device, |
| 98 | + lr_scheduler=scheduler, |
| 99 | + logger=sam_training.SamLogger, |
| 100 | + log_image_interval=10, |
| 101 | + mixed_precision=True, |
| 102 | + convert_inputs=convert_inputs, |
| 103 | + n_objects_per_batch=n_objects_per_batch, |
| 104 | + n_sub_iteration=8, |
| 105 | + compile_model=False |
| 106 | + ) |
| 107 | + trainer.fit(n_iterations) |
| 108 | + |
| 109 | + |
| 110 | +def export_model(checkpoint_name, model_type): |
| 111 | + """Export the trained model.""" |
| 112 | + # export the model after training so that it can be used by the rest of the micro_sam library |
| 113 | + export_path = "./finetuned_hela_model.pth" |
| 114 | + checkpoint_path = os.path.join("checkpoints", checkpoint_name, "best.pt") |
| 115 | + export_custom_sam_model( |
| 116 | + checkpoint_path=checkpoint_path, |
| 117 | + model_type=model_type, |
| 118 | + save_path=export_path, |
| 119 | + ) |
| 120 | + |
| 121 | + |
| 122 | +def main(): |
| 123 | + """Finetune a Segment Anything model. |
| 124 | +
|
| 125 | + This example uses image data and segmentations from the cell tracking challenge, |
| 126 | + but can easily be adapted for other data (including data you have annoated with micro_sam beforehand). |
| 127 | + """ |
| 128 | + # The model_type determines which base model is used to initialize the weights that are finetuned. |
| 129 | + # We use vit_b here because it can be trained faster. Note that vit_h usually yields higher quality results. |
| 130 | + model_type = "vit_b" |
| 131 | + |
| 132 | + # The name of the checkpoint. The checkpoints will be stored in './checkpoints/<checkpoint_name>' |
| 133 | + checkpoint_name = "sam_hela" |
| 134 | + |
| 135 | + run_training(checkpoint_name, model_type) |
| 136 | + export_model(checkpoint_name, model_type) |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == "__main__": |
| 140 | + main() |
0 commit comments