micro_sam.v1.training.joint_sam_trainer
1import os 2import time 3from collections import OrderedDict 4 5import numpy as np 6 7import torch 8from torchvision.utils import make_grid 9from torch.utils.tensorboard import SummaryWriter 10 11from torch_em.trainer.logger_base import TorchEmLogger 12from torch_em.trainer.tensorboard_logger import normalize_im 13 14from .sam_trainer import SamTrainer 15 16 17class JointSamTrainer(SamTrainer): 18 """Trainer class for jointly training the Segment Anything model with an additional convolutional decoder. 19 20 This class is inherited from `SamTrainer`. 21 Check out https://github.com/computational-cell-analytics/micro-sam/blob/main/micro_sam/v1/training/sam_trainer.py 22 for details on its implementation. 23 24 Args: 25 unetr: The UNet-style model with vision transformer as the image encoder. 26 Required to perform automatic instance segmentation. 27 instance_loss: The loss to compare the predictions (for instance segmentation) and the targets. 28 instance_metric: The metric to compare the predictions and the targets. 29 kwargs: The keyword arguments of the `SamTrainer` (and `DefaultTrainer`) class. 30 """ 31 32 def __init__( 33 self, unetr: torch.nn.Module, instance_loss: torch.nn.Module, instance_metric: torch.nn.Module, **kwargs 34 ): 35 super().__init__(**kwargs) 36 self.unetr = unetr 37 self.instance_loss = instance_loss 38 self.instance_metric = instance_metric 39 40 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 41 current_unetr_state = self.unetr.state_dict() 42 decoder_state = [] 43 for k, v in current_unetr_state.items(): 44 if not k.startswith("encoder"): 45 decoder_state.append((k, v)) 46 decoder_state = OrderedDict(decoder_state) 47 48 super().save_checkpoint( 49 name, current_metric=current_metric, best_metric=best_metric, decoder_state=decoder_state, **extra_save_dict 50 ) 51 52 def load_checkpoint(self, checkpoint="best"): 53 save_dict = super().load_checkpoint(checkpoint) 54 55 # let's get the image encoder params from sam 56 sam_state = save_dict["model_state"] 57 encoder_state = [] 58 prune_prefix = "sam.image_" 59 for k, v in sam_state.items(): 60 if k.startswith(prune_prefix): 61 encoder_state.append((k[len(prune_prefix):], v)) 62 encoder_state = OrderedDict(encoder_state) 63 64 # let's get the decoder params from unetr 65 decoder_state = save_dict["decoder_state"] 66 67 # now let's merge the two to get the params for the unetr 68 unetr_state = OrderedDict(list(encoder_state.items()) + list(decoder_state.items())) 69 70 self.unetr.load_state_dict(unetr_state) 71 self.unetr.to(self.device) 72 return save_dict 73 74 def _instance_iteration(self, x, y, metric_for_val=False): 75 """Perform the segmentation of distance maps and 76 compute the loss (and metric) between the prediction and target. 77 """ 78 outputs = self.unetr(x.to(self.device)) 79 loss = self.instance_loss(outputs, y.to(self.device)) 80 if metric_for_val: 81 metric = self.instance_metric(outputs, y.to(self.device)) 82 return loss, metric 83 else: 84 return loss 85 86 def _train_epoch_impl(self, progress, forward_context, backprop): 87 self.model.train() 88 self.unetr.train() 89 90 input_check_done = False 91 92 n_iter = 0 93 t_per_iter = time.time() 94 for x, y in self.train_loader: 95 labels_instances = y[:, 0, ...].unsqueeze(1) 96 labels_for_unetr = y[:, 1:, ...] 97 98 input_check_done = self._check_input_normalization(x, input_check_done) 99 100 self.optimizer.zero_grad() 101 102 with forward_context(): 103 # 1. train for the interactive segmentation 104 ( 105 loss, mask_loss, iou_regression_loss, model_iou, sampled_binary_y 106 ) = self._interactive_train_iteration(x, labels_instances) 107 108 backprop(loss) 109 110 self.optimizer.zero_grad() 111 112 with forward_context(): 113 # 2. train for the automatic instance segmentation 114 unetr_loss = self._instance_iteration(x, labels_for_unetr) 115 116 backprop(unetr_loss) 117 118 if self.logger is not None: 119 lr = [pm["lr"] for pm in self.optimizer.param_groups][0] 120 samples = sampled_binary_y if self._iteration % self.log_image_interval == 0 else None 121 self.logger.log_train( 122 self._iteration, loss, lr, x, labels_instances, samples, 123 mask_loss, iou_regression_loss, model_iou, unetr_loss 124 ) 125 126 self._iteration += 1 127 n_iter += 1 128 if self._iteration >= self.max_iteration: 129 break 130 progress.update(1) 131 132 t_per_iter = (time.time() - t_per_iter) / n_iter 133 return t_per_iter 134 135 def _validate_impl(self, forward_context): 136 self.model.eval() 137 self.unetr.eval() 138 139 input_check_done = False 140 141 val_iteration = 0 142 metric_val, loss_val, model_iou_val = 0.0, 0.0, 0.0 143 mask_loss_val, iou_loss_val, unetr_loss_val = 0.0, 0.0, 0.0 144 145 with torch.no_grad(): 146 for x, y in self.val_loader: 147 labels_instances = y[:, 0, ...].unsqueeze(1) 148 labels_for_unetr = y[:, 1:, ...] 149 150 input_check_done = self._check_input_normalization(x, input_check_done) 151 152 with forward_context(): 153 # 1. validate for the interactive segmentation 154 ( 155 loss, mask_loss, iou_regression_loss, model_iou, sampled_binary_y, metric 156 ) = self._interactive_val_iteration(x, labels_instances, val_iteration) 157 158 with forward_context(): 159 # 2. validate for the automatic instance segmentation 160 unetr_loss, unetr_metric = self._instance_iteration(x, labels_for_unetr, metric_for_val=True) 161 162 loss_val += loss.item() 163 metric_val += metric.item() + (unetr_metric.item() / 3) 164 mask_loss_val += mask_loss.item() 165 iou_loss_val += iou_regression_loss.item() 166 model_iou_val += model_iou.item() 167 unetr_loss_val += unetr_loss.item() 168 val_iteration += 1 169 170 loss_val /= len(self.val_loader) 171 metric_val /= len(self.val_loader) 172 mask_loss_val /= len(self.val_loader) 173 iou_loss_val /= len(self.val_loader) 174 model_iou_val /= len(self.val_loader) 175 unetr_loss_val /= len(self.val_loader) 176 177 if self.logger is not None: 178 self.logger.log_validation( 179 self._iteration, metric_val, loss_val, x, labels_instances, sampled_binary_y, 180 mask_loss_val, iou_loss_val, model_iou_val, unetr_loss_val 181 ) 182 183 return metric_val 184 185 186class JointSamLogger(TorchEmLogger): 187 """@private""" 188 def __init__(self, trainer, save_root, **unused_kwargs): 189 super().__init__(trainer, save_root) 190 self.log_dir = f"./logs/{trainer.name}" if save_root is None else\ 191 os.path.join(save_root, "logs", trainer.name) 192 os.makedirs(self.log_dir, exist_ok=True) 193 194 self.tb = SummaryWriter(self.log_dir) 195 self.log_image_interval = trainer.log_image_interval 196 197 def add_image(self, x, y, samples, name, step): 198 selection = np.s_[0] if x.ndim == 4 else np.s_[0, :, x.shape[2] // 2] 199 200 image = normalize_im(x[selection].cpu()) 201 202 self.tb.add_image(tag=f"{name}/input", img_tensor=image, global_step=step) 203 self.tb.add_image(tag=f"{name}/target", img_tensor=y[selection], global_step=step) 204 sample_grid = make_grid([sample[0] for sample in samples], nrow=4, padding=4) 205 self.tb.add_image(tag=f"{name}/samples", img_tensor=sample_grid, global_step=step) 206 207 def log_train( 208 self, step, loss, lr, x, y, samples, mask_loss, iou_regression_loss, model_iou, instance_loss 209 ): 210 self.tb.add_scalar(tag="train/loss", scalar_value=loss, global_step=step) 211 self.tb.add_scalar(tag="train/mask_loss", scalar_value=mask_loss, global_step=step) 212 self.tb.add_scalar(tag="train/iou_loss", scalar_value=iou_regression_loss, global_step=step) 213 self.tb.add_scalar(tag="train/model_iou", scalar_value=model_iou, global_step=step) 214 self.tb.add_scalar(tag="train/instance_loss", scalar_value=instance_loss, global_step=step) 215 self.tb.add_scalar(tag="train/learning_rate", scalar_value=lr, global_step=step) 216 if step % self.log_image_interval == 0: 217 self.add_image(x, y, samples, "train", step) 218 219 def log_validation( 220 self, step, metric, loss, x, y, samples, mask_loss, iou_regression_loss, model_iou, instance_loss 221 ): 222 self.tb.add_scalar(tag="validation/loss", scalar_value=loss, global_step=step) 223 self.tb.add_scalar(tag="validation/mask_loss", scalar_value=mask_loss, global_step=step) 224 self.tb.add_scalar(tag="validation/iou_loss", scalar_value=iou_regression_loss, global_step=step) 225 self.tb.add_scalar(tag="validation/model_iou", scalar_value=model_iou, global_step=step) 226 self.tb.add_scalar(tag="validation/instance_loss", scalar_value=instance_loss, global_step=step) 227 self.tb.add_scalar(tag="validation/metric", scalar_value=metric, global_step=step) 228 self.add_image(x, y, samples, "validation", step)
18class JointSamTrainer(SamTrainer): 19 """Trainer class for jointly training the Segment Anything model with an additional convolutional decoder. 20 21 This class is inherited from `SamTrainer`. 22 Check out https://github.com/computational-cell-analytics/micro-sam/blob/main/micro_sam/v1/training/sam_trainer.py 23 for details on its implementation. 24 25 Args: 26 unetr: The UNet-style model with vision transformer as the image encoder. 27 Required to perform automatic instance segmentation. 28 instance_loss: The loss to compare the predictions (for instance segmentation) and the targets. 29 instance_metric: The metric to compare the predictions and the targets. 30 kwargs: The keyword arguments of the `SamTrainer` (and `DefaultTrainer`) class. 31 """ 32 33 def __init__( 34 self, unetr: torch.nn.Module, instance_loss: torch.nn.Module, instance_metric: torch.nn.Module, **kwargs 35 ): 36 super().__init__(**kwargs) 37 self.unetr = unetr 38 self.instance_loss = instance_loss 39 self.instance_metric = instance_metric 40 41 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 42 current_unetr_state = self.unetr.state_dict() 43 decoder_state = [] 44 for k, v in current_unetr_state.items(): 45 if not k.startswith("encoder"): 46 decoder_state.append((k, v)) 47 decoder_state = OrderedDict(decoder_state) 48 49 super().save_checkpoint( 50 name, current_metric=current_metric, best_metric=best_metric, decoder_state=decoder_state, **extra_save_dict 51 ) 52 53 def load_checkpoint(self, checkpoint="best"): 54 save_dict = super().load_checkpoint(checkpoint) 55 56 # let's get the image encoder params from sam 57 sam_state = save_dict["model_state"] 58 encoder_state = [] 59 prune_prefix = "sam.image_" 60 for k, v in sam_state.items(): 61 if k.startswith(prune_prefix): 62 encoder_state.append((k[len(prune_prefix):], v)) 63 encoder_state = OrderedDict(encoder_state) 64 65 # let's get the decoder params from unetr 66 decoder_state = save_dict["decoder_state"] 67 68 # now let's merge the two to get the params for the unetr 69 unetr_state = OrderedDict(list(encoder_state.items()) + list(decoder_state.items())) 70 71 self.unetr.load_state_dict(unetr_state) 72 self.unetr.to(self.device) 73 return save_dict 74 75 def _instance_iteration(self, x, y, metric_for_val=False): 76 """Perform the segmentation of distance maps and 77 compute the loss (and metric) between the prediction and target. 78 """ 79 outputs = self.unetr(x.to(self.device)) 80 loss = self.instance_loss(outputs, y.to(self.device)) 81 if metric_for_val: 82 metric = self.instance_metric(outputs, y.to(self.device)) 83 return loss, metric 84 else: 85 return loss 86 87 def _train_epoch_impl(self, progress, forward_context, backprop): 88 self.model.train() 89 self.unetr.train() 90 91 input_check_done = False 92 93 n_iter = 0 94 t_per_iter = time.time() 95 for x, y in self.train_loader: 96 labels_instances = y[:, 0, ...].unsqueeze(1) 97 labels_for_unetr = y[:, 1:, ...] 98 99 input_check_done = self._check_input_normalization(x, input_check_done) 100 101 self.optimizer.zero_grad() 102 103 with forward_context(): 104 # 1. train for the interactive segmentation 105 ( 106 loss, mask_loss, iou_regression_loss, model_iou, sampled_binary_y 107 ) = self._interactive_train_iteration(x, labels_instances) 108 109 backprop(loss) 110 111 self.optimizer.zero_grad() 112 113 with forward_context(): 114 # 2. train for the automatic instance segmentation 115 unetr_loss = self._instance_iteration(x, labels_for_unetr) 116 117 backprop(unetr_loss) 118 119 if self.logger is not None: 120 lr = [pm["lr"] for pm in self.optimizer.param_groups][0] 121 samples = sampled_binary_y if self._iteration % self.log_image_interval == 0 else None 122 self.logger.log_train( 123 self._iteration, loss, lr, x, labels_instances, samples, 124 mask_loss, iou_regression_loss, model_iou, unetr_loss 125 ) 126 127 self._iteration += 1 128 n_iter += 1 129 if self._iteration >= self.max_iteration: 130 break 131 progress.update(1) 132 133 t_per_iter = (time.time() - t_per_iter) / n_iter 134 return t_per_iter 135 136 def _validate_impl(self, forward_context): 137 self.model.eval() 138 self.unetr.eval() 139 140 input_check_done = False 141 142 val_iteration = 0 143 metric_val, loss_val, model_iou_val = 0.0, 0.0, 0.0 144 mask_loss_val, iou_loss_val, unetr_loss_val = 0.0, 0.0, 0.0 145 146 with torch.no_grad(): 147 for x, y in self.val_loader: 148 labels_instances = y[:, 0, ...].unsqueeze(1) 149 labels_for_unetr = y[:, 1:, ...] 150 151 input_check_done = self._check_input_normalization(x, input_check_done) 152 153 with forward_context(): 154 # 1. validate for the interactive segmentation 155 ( 156 loss, mask_loss, iou_regression_loss, model_iou, sampled_binary_y, metric 157 ) = self._interactive_val_iteration(x, labels_instances, val_iteration) 158 159 with forward_context(): 160 # 2. validate for the automatic instance segmentation 161 unetr_loss, unetr_metric = self._instance_iteration(x, labels_for_unetr, metric_for_val=True) 162 163 loss_val += loss.item() 164 metric_val += metric.item() + (unetr_metric.item() / 3) 165 mask_loss_val += mask_loss.item() 166 iou_loss_val += iou_regression_loss.item() 167 model_iou_val += model_iou.item() 168 unetr_loss_val += unetr_loss.item() 169 val_iteration += 1 170 171 loss_val /= len(self.val_loader) 172 metric_val /= len(self.val_loader) 173 mask_loss_val /= len(self.val_loader) 174 iou_loss_val /= len(self.val_loader) 175 model_iou_val /= len(self.val_loader) 176 unetr_loss_val /= len(self.val_loader) 177 178 if self.logger is not None: 179 self.logger.log_validation( 180 self._iteration, metric_val, loss_val, x, labels_instances, sampled_binary_y, 181 mask_loss_val, iou_loss_val, model_iou_val, unetr_loss_val 182 ) 183 184 return metric_val
Trainer class for jointly training the Segment Anything model with an additional convolutional decoder.
This class is inherited from SamTrainer.
Check out https://github.com/computational-cell-analytics/micro-sam/blob/main/micro_sam/v1/training/sam_trainer.py
for details on its implementation.
Arguments:
- unetr: The UNet-style model with vision transformer as the image encoder. Required to perform automatic instance segmentation.
- instance_loss: The loss to compare the predictions (for instance segmentation) and the targets.
- instance_metric: The metric to compare the predictions and the targets.
- kwargs: The keyword arguments of the
SamTrainer(andDefaultTrainer) class.