micro_sam.v2.training.joint_sam2_trainer
1import os 2import time 3import random 4from collections import defaultdict 5from typing import Callable, List, Optional 6 7import numpy as np 8 9import torch 10import torch.distributed as dist 11from torch.utils.tensorboard import SummaryWriter 12from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors 13 14from torch_em.trainer.logger_base import TorchEmLogger 15 16from .sam2_trainer import ( 17 Sam2Trainer, _colorize_instance_map, _overlay_binary_masks, _pinned_validation_rng, 18 VALIDATION_SEED, 19) 20 21# Gradients are all-reduced in flat buckets of at most this many bytes. Bigger buckets mean 22# fewer collectives but a larger temporary buffer; 128 MiB matches DDP's own default order. 23GRAD_SYNC_BUCKET_BYTES = 128 * 1024 * 1024 24 25 26def _grad_buckets(grads: List[torch.Tensor], bucket_bytes: int = GRAD_SYNC_BUCKET_BYTES): 27 """Group gradients by dtype into buckets of at most *bucket_bytes*, for flat all-reduce.""" 28 by_dtype = defaultdict(list) 29 for grad in grads: 30 by_dtype[grad.dtype].append(grad) 31 32 for dtype_grads in by_dtype.values(): 33 bucket, n_bytes = [], 0 34 for grad in dtype_grads: 35 grad_bytes = grad.numel() * grad.element_size() 36 if bucket and n_bytes + grad_bytes > bucket_bytes: 37 yield bucket 38 bucket, n_bytes = [], 0 39 bucket.append(grad) 40 n_bytes += grad_bytes 41 if bucket: 42 yield bucket 43 44 45class JointSam2Trainer(Sam2Trainer): 46 """Trainer for joint interactive + automatic segmentation with SAM2 and UniSAM2. 47 48 Uses a single **5-channel label tensor** per batch built by 49 :func:`~micro_sam.v2.datasets.generalist_loader._build_joint_datasets`: 50 51 - Channel 0 (int64): instance IDs -> interactive branch. 52 - Channels 1-4 (float32): foreground mask + directed distances -> automatic branch. 53 54 Both branches see the **same image patch**, which halves the number of data 55 loaders compared to using separate interactive and automatic datasets. 56 57 Each branch is trained with a separate forward-backward-step cycle per 58 iteration (matching micro-sam v1), so their loss scales never compete. 59 In DDP, only ``model`` (sam2_train_model) is DDP-wrapped; every gradient the 60 automatic backward produces - the ``unetr`` decoder *and* the shared image 61 encoder - is manually all_reduced via :meth:`_sync_automatic_grads`. 62 The shared encoder therefore takes two optimizer steps per batch, one per branch. 63 64 Args: 65 unetr: UniSAM2 model constructed with ``encoder=sam2_train_model.image_encoder`` 66 so the backbone is shared with the interactive model. 67 convert_inputs: Converts (x, y_instances) torch-em tuples from the 68 loader into ``BatchedVideoDatapoint`` expected by SAM2Train. 69 interactive_loss: Loss for the interactive branch (e.g. ``CustomSAM2Loss``). 70 automatic_loss: Loss for the automatic branch 71 (e.g. ``DirectedDistanceLoss``). 72 automatic_metric: Validation metric for the automatic branch. Defaults to 73 ``automatic_loss`` (matching train_automatic's ``metric=loss``). 74 automatic_metric_weight: Weight of the automatic metric in the combined validation 75 metric used for checkpointing and early stopping. Defaults to 1/4, putting 76 ``DirectedDistanceLoss``'s four summed terms on the scale of the interactive Dice 77 metric. Set to 0 to select purely on the interactive task. 78 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 79 finetuning uses 0.1. 80 kwargs: Forwarded to ``Sam2Trainer``. ``model`` should be the 81 sam2_train_model (or its DDP wrapper); ``train_loader`` and 82 ``val_loader`` must yield ``(x, y)`` where ``y`` has 5 channels as 83 described above. 84 """ 85 86 def __init__( 87 self, 88 unetr: torch.nn.Module, 89 convert_inputs: Callable, 90 interactive_loss: torch.nn.Module, 91 automatic_loss: torch.nn.Module, 92 automatic_metric: Optional[torch.nn.Module] = None, 93 automatic_metric_weight: float = 0.25, 94 clip_grad_norm: Optional[float] = None, 95 **kwargs, 96 ): 97 super().__init__( 98 convert_inputs=convert_inputs, loss=interactive_loss, clip_grad_norm=clip_grad_norm, **kwargs, 99 ) 100 self.unetr = unetr 101 self.automatic_loss = automatic_loss 102 # Automatic metric mirrors train_automatic's metric=loss convention when not given. 103 self.automatic_metric = automatic_metric if automatic_metric is not None else automatic_loss 104 self.automatic_metric_weight = automatic_metric_weight 105 106 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 107 # The encoder of the UniSAM2 is the SAM2 image encoder, which 'model_state' already holds. 108 decoder_state = {k: v for k, v in self.unetr.state_dict().items() if not k.startswith("encoder.")} 109 super().save_checkpoint(name, current_metric, best_metric, decoder_state=decoder_state, **extra_save_dict) 110 111 def load_checkpoint(self, checkpoint="best"): 112 save_dict = super().load_checkpoint(checkpoint) 113 if save_dict is not None: 114 # A checkpoint from before v6 holds 'unetr_state' and would otherwise resume with a random decoder. 115 assert "decoder_state" in save_dict, f"Not a v6 joint checkpoint, it holds {sorted(save_dict)}." 116 missing, unexpected = self.unetr.load_state_dict(save_dict["decoder_state"], strict=False) 117 assert not unexpected and all(key.startswith("encoder.") for key in missing), (missing, unexpected) 118 self.unetr.to(self.device) 119 return save_dict 120 121 def _skip_batch_without_objects(self, y): 122 """Whether any rank holds a batch without instances, which cannot be prompted. 123 124 Decided before the forward pass: its collectives would otherwise pair with the skip flag of a rank 125 that found no objects, and every rank has to skip the same iterations. 126 """ 127 skip = torch.tensor(int(not bool((y[:, 0] > 0).any())), device=self.device) 128 if dist.is_available() and dist.is_initialized(): 129 dist.all_reduce(skip, op=dist.ReduceOp.MAX) 130 return bool(skip.item()) 131 132 def _sync_decoder_buffers(self): 133 """Average the BatchNorm statistics of the decoder, which no DDP wrapper keeps in step across ranks.""" 134 if not (dist.is_available() and dist.is_initialized()): 135 return 136 for name, buffer in self.unetr.named_buffers(): 137 if name.startswith("encoder") or not buffer.is_floating_point(): 138 continue 139 dist.all_reduce(buffer, op=dist.ReduceOp.AVG) 140 141 def _interactive_step(self, x, y): 142 # Slice channel 0 (instance IDs) from the 5-channel joint label tensor. 143 return super()._interactive_step(x, y[:, 0:1].to(torch.int64)) 144 145 def _automatic_step(self, x, y, retain_grad=False): 146 x = x.to(self.device, non_blocking=True) 147 # Channels 1-4: foreground mask + 3 directed-distance channels. 148 y_dist = y[:, 1:].to(self.device, non_blocking=True) 149 pred = self.unetr(x) 150 if retain_grad: 151 pred.retain_grad() 152 return self.automatic_loss(pred, y_dist), y_dist, pred 153 154 def _sync_automatic_grads(self): 155 """All-reduce every gradient produced by the automatic backward pass. 156 157 The automatic branch bypasses the DDP wrapper, so nothing here has been reduced 158 already - including the encoder it shares with the interactive model. The gradients 159 are flattened into buckets before the collective, so the shared encoder costs a 160 handful of all-reduces per iteration instead of one per parameter tensor. 161 """ 162 if not (dist.is_available() and dist.is_initialized()): 163 return 164 grads = [p.grad for p in self.unetr.parameters() if p.grad is not None] 165 for bucket in _grad_buckets(grads): 166 flat = _flatten_dense_tensors(bucket) 167 dist.all_reduce(flat, op=dist.ReduceOp.AVG) 168 for grad, reduced in zip(bucket, _unflatten_dense_tensors(flat, bucket)): 169 grad.copy_(reduced) 170 171 def _clip_automatic_grads(self): 172 """Clip the automatic branch to the same norm as the interactive branch.""" 173 if self.clip_grad_norm is None: 174 return None 175 grad_norm = torch.nn.utils.clip_grad_norm_(self.unetr.parameters(), self.clip_grad_norm) 176 return grad_norm.item() 177 178 def _backprop_automatic(self, loss): 179 if self.scaler is not None: 180 self.scaler.scale(loss).backward() 181 if self.clip_grad_norm is not None: 182 self.scaler.unscale_(self.optimizer) 183 self._sync_automatic_grads() 184 grad_norm = self._clip_automatic_grads() 185 self.scaler.step(self.optimizer) 186 self.scaler.update() 187 else: 188 loss.backward() 189 self._sync_automatic_grads() 190 grad_norm = self._clip_automatic_grads() 191 self.optimizer.step() 192 return grad_norm 193 194 def _train_epoch_impl(self, progress, forward_context, backprop): 195 self.model.train() 196 self.unetr.train() 197 198 if hasattr(self.train_loader, "batch_sampler") and \ 199 hasattr(self.train_loader.batch_sampler, "set_epoch"): 200 self.train_loader.batch_sampler.set_epoch(self._epoch) 201 202 n_iter = 0 203 t_per_iter = time.time() 204 input_check_done = False 205 206 for x, y in self.train_loader: 207 input_check_done = self._check_input_normalization(x, input_check_done) 208 if self._skip_batch_without_objects(y): 209 continue 210 211 self.optimizer.zero_grad() 212 with forward_context(): 213 inter_loss, batch, outputs = self._interactive_step(x, y) 214 self._sam2_backprop(inter_loss) 215 216 log_imgs = (self._iteration % self.log_image_interval == 0) 217 self.optimizer.zero_grad() 218 with forward_context(): 219 auto_loss, y_dist, pred = self._automatic_step(x, y, retain_grad=log_imgs) 220 self._backprop_automatic(auto_loss) 221 222 if self.logger is not None: 223 lr = self.optimizer.param_groups[0]["lr"] 224 # Materialize both losses in one host sync instead of one per .item() call. 225 inter_value, auto_value = torch.stack( 226 [inter_loss.detach().float(), auto_loss.detach().float()] 227 ).tolist() 228 self.logger.log_train( 229 self._iteration, inter_value + auto_value, lr, inter_value, auto_value, 230 x=x if log_imgs else None, 231 y=y if log_imgs else None, 232 batch=batch if log_imgs else None, 233 outputs=outputs if log_imgs else None, 234 y_dist=y_dist if log_imgs else None, 235 pred=pred if log_imgs else None, 236 ) 237 238 self._iteration += 1 239 n_iter += 1 240 if self._iteration >= self.max_iteration: 241 break 242 progress.update(1) 243 244 return (time.time() - t_per_iter) / n_iter 245 246 def _validate_impl(self, forward_context): 247 self.model.eval() 248 self.unetr.eval() 249 250 # Accumulated on the device as [inter_loss, inter_metric, auto_loss, auto_metric], so the 251 # whole pass costs one host sync instead of four per iteration. 252 totals = torch.zeros(4, device=self.device) 253 n_iter = 0 254 input_check_done = False 255 log_x = log_y = log_batch = log_outputs = log_y_dist = log_pred = None 256 257 # Pick one validation sample to log via reservoir sampling, seeded per epoch. 258 log_rng = random.Random(VALIDATION_SEED + self._epoch) 259 260 self._sync_decoder_buffers() 261 # Pin the RNGs so the sampled prompts are identical every epoch. 262 with _pinned_validation_rng(self.model): 263 with torch.no_grad(): 264 for i, (x, y) in enumerate(self.val_loader): 265 input_check_done = self._check_input_normalization(x, input_check_done) 266 if self._skip_batch_without_objects(y): 267 continue 268 with forward_context(): 269 inter_loss, batch, outputs = self._interactive_step(x, y) 270 inter_metric = self.metric(outputs, batch.masks) 271 auto_loss, y_dist, pred = self._automatic_step(x, y) 272 auto_metric = self.automatic_metric(pred, y_dist) 273 totals += torch.stack([ 274 inter_loss.detach().float(), inter_metric.detach().float(), 275 auto_loss.detach().float(), auto_metric.detach().float(), 276 ]) 277 n_iter += 1 278 if log_rng.random() < 1.0 / (i + 1): 279 log_x, log_y, log_batch, log_outputs = x, y, batch, outputs 280 log_y_dist, log_pred = y_dist, pred 281 282 totals /= max(n_iter, 1) 283 combined = totals[1] + self.automatic_metric_weight * totals[3] 284 stats = torch.cat([totals, combined.unsqueeze(0)]) 285 286 # Synchronize across DDP ranks so every rank makes the same early-stopping decision. 287 if dist.is_available() and dist.is_initialized(): 288 dist.all_reduce(stats, op=dist.ReduceOp.AVG) 289 290 inter_loss_val, inter_metric_val, auto_loss_val, auto_metric_val, combined_metric = stats.tolist() 291 292 if self.logger is not None: 293 self.logger.log_validation( 294 self._iteration, inter_loss_val, inter_metric_val, auto_loss_val, auto_metric_val, 295 combined_metric, log_x, log_y, log_batch, log_outputs, log_y_dist, log_pred, 296 ) 297 298 return combined_metric 299 300 301class JointSam2Logger(TorchEmLogger): 302 """TensorBoard logger for JointSam2Trainer. Only rank 0 writes in DDP.""" 303 304 def __init__(self, trainer, save_root, **unused_kwargs): 305 super().__init__(trainer, save_root) 306 rank = getattr(trainer, "rank", None) 307 if rank is not None and rank != 0: 308 self.tb = None 309 return 310 self.log_dir = ( 311 f"./logs/{trainer.name}" if save_root is None 312 else os.path.join(save_root, "logs", trainer.name) 313 ) 314 os.makedirs(self.log_dir, exist_ok=True) 315 self.tb = SummaryWriter(self.log_dir) 316 self.log_image_interval = trainer.log_image_interval 317 318 def _masks_for_batch_item(self, batch, b=0, t=0): 319 b_indices = batch.obj_to_frame_idx[t, :, 1] 320 return batch.masks[t][b_indices == b] 321 322 def _log_interactive_images(self, step, x, y, batch, outputs, prefix): 323 is_3d = (x.ndim == 5) 324 raw = x[0, :3, 0].cpu().float() if is_3d else x[0, :3].cpu().float() 325 H, W = raw.shape[-2:] 326 self.tb.add_image(f"{prefix}/interactive/raw", raw, step) 327 328 gt_lbl = y[0, 0, 0].cpu().numpy() if is_3d else y[0, 0].cpu().numpy() 329 self.tb.add_image(f"{prefix}/interactive/gt_all", _colorize_instance_map(gt_lbl), step) 330 331 gt_chosen = self._masks_for_batch_item(batch, b=0, t=0) 332 self.tb.add_image( 333 f"{prefix}/interactive/gt_chosen", _overlay_binary_masks(gt_chosen, target_hw=(H, W)), step 334 ) 335 336 b_indices = batch.obj_to_frame_idx[0, :, 1] 337 pred_step0 = outputs[0]["multistep_pred_masks_high_res"][b_indices == 0, 0].detach() 338 self.tb.add_image( 339 f"{prefix}/interactive/predictions", _overlay_binary_masks(pred_step0 > 0, target_hw=(H, W)), step 340 ) 341 342 def _log_automatic_images(self, step, x, y_dist, pred, prefix): 343 from torch_em.trainer.tensorboard_logger import make_grid_image, normalize_im 344 345 selection = np.s_[0] if x.ndim == 4 else np.s_[0, :, x.shape[2] // 2] 346 image = normalize_im(x[selection].cpu()) 347 self.tb.add_image(f"{prefix}/automatic/input", image, step) 348 gradients = pred.grad if pred.grad is not None else None 349 im, im_name = make_grid_image(image, y_dist, pred, selection, gradients) 350 self.tb.add_image(f"{prefix}/automatic/{im_name}", im, step) 351 352 def log_train( 353 self, step, total_loss, lr, interactive_loss, auto_loss, 354 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None 355 ): 356 if self.tb is None: 357 return 358 self.tb.add_scalar("train/total_loss", total_loss, global_step=step) 359 self.tb.add_scalar("train/interactive_loss", interactive_loss, global_step=step) 360 self.tb.add_scalar("train/automatic_loss", auto_loss, global_step=step) 361 self.tb.add_scalar("train/learning_rate", lr, global_step=step) 362 if x is not None: 363 self._log_interactive_images(step, x, y, batch, outputs, "train") 364 self._log_automatic_images(step, x, y_dist, pred, "train") 365 366 def log_validation( 367 self, step, interactive_loss, interactive_metric, auto_loss, auto_metric, combined_metric, 368 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None, 369 ): 370 if self.tb is None: 371 return 372 self.tb.add_scalar("validation/interactive_loss", interactive_loss, global_step=step) 373 self.tb.add_scalar("validation/interactive_metric", interactive_metric, global_step=step) 374 self.tb.add_scalar("validation/automatic_loss", auto_loss, global_step=step) 375 self.tb.add_scalar("validation/automatic_metric", auto_metric, global_step=step) 376 self.tb.add_scalar("validation/combined_metric", combined_metric, global_step=step) 377 if x is not None: 378 self._log_interactive_images(step, x, y, batch, outputs, "validation") 379 self._log_automatic_images(step, x, y_dist, pred, "validation")
46class JointSam2Trainer(Sam2Trainer): 47 """Trainer for joint interactive + automatic segmentation with SAM2 and UniSAM2. 48 49 Uses a single **5-channel label tensor** per batch built by 50 :func:`~micro_sam.v2.datasets.generalist_loader._build_joint_datasets`: 51 52 - Channel 0 (int64): instance IDs -> interactive branch. 53 - Channels 1-4 (float32): foreground mask + directed distances -> automatic branch. 54 55 Both branches see the **same image patch**, which halves the number of data 56 loaders compared to using separate interactive and automatic datasets. 57 58 Each branch is trained with a separate forward-backward-step cycle per 59 iteration (matching micro-sam v1), so their loss scales never compete. 60 In DDP, only ``model`` (sam2_train_model) is DDP-wrapped; every gradient the 61 automatic backward produces - the ``unetr`` decoder *and* the shared image 62 encoder - is manually all_reduced via :meth:`_sync_automatic_grads`. 63 The shared encoder therefore takes two optimizer steps per batch, one per branch. 64 65 Args: 66 unetr: UniSAM2 model constructed with ``encoder=sam2_train_model.image_encoder`` 67 so the backbone is shared with the interactive model. 68 convert_inputs: Converts (x, y_instances) torch-em tuples from the 69 loader into ``BatchedVideoDatapoint`` expected by SAM2Train. 70 interactive_loss: Loss for the interactive branch (e.g. ``CustomSAM2Loss``). 71 automatic_loss: Loss for the automatic branch 72 (e.g. ``DirectedDistanceLoss``). 73 automatic_metric: Validation metric for the automatic branch. Defaults to 74 ``automatic_loss`` (matching train_automatic's ``metric=loss``). 75 automatic_metric_weight: Weight of the automatic metric in the combined validation 76 metric used for checkpointing and early stopping. Defaults to 1/4, putting 77 ``DirectedDistanceLoss``'s four summed terms on the scale of the interactive Dice 78 metric. Set to 0 to select purely on the interactive task. 79 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 80 finetuning uses 0.1. 81 kwargs: Forwarded to ``Sam2Trainer``. ``model`` should be the 82 sam2_train_model (or its DDP wrapper); ``train_loader`` and 83 ``val_loader`` must yield ``(x, y)`` where ``y`` has 5 channels as 84 described above. 85 """ 86 87 def __init__( 88 self, 89 unetr: torch.nn.Module, 90 convert_inputs: Callable, 91 interactive_loss: torch.nn.Module, 92 automatic_loss: torch.nn.Module, 93 automatic_metric: Optional[torch.nn.Module] = None, 94 automatic_metric_weight: float = 0.25, 95 clip_grad_norm: Optional[float] = None, 96 **kwargs, 97 ): 98 super().__init__( 99 convert_inputs=convert_inputs, loss=interactive_loss, clip_grad_norm=clip_grad_norm, **kwargs, 100 ) 101 self.unetr = unetr 102 self.automatic_loss = automatic_loss 103 # Automatic metric mirrors train_automatic's metric=loss convention when not given. 104 self.automatic_metric = automatic_metric if automatic_metric is not None else automatic_loss 105 self.automatic_metric_weight = automatic_metric_weight 106 107 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 108 # The encoder of the UniSAM2 is the SAM2 image encoder, which 'model_state' already holds. 109 decoder_state = {k: v for k, v in self.unetr.state_dict().items() if not k.startswith("encoder.")} 110 super().save_checkpoint(name, current_metric, best_metric, decoder_state=decoder_state, **extra_save_dict) 111 112 def load_checkpoint(self, checkpoint="best"): 113 save_dict = super().load_checkpoint(checkpoint) 114 if save_dict is not None: 115 # A checkpoint from before v6 holds 'unetr_state' and would otherwise resume with a random decoder. 116 assert "decoder_state" in save_dict, f"Not a v6 joint checkpoint, it holds {sorted(save_dict)}." 117 missing, unexpected = self.unetr.load_state_dict(save_dict["decoder_state"], strict=False) 118 assert not unexpected and all(key.startswith("encoder.") for key in missing), (missing, unexpected) 119 self.unetr.to(self.device) 120 return save_dict 121 122 def _skip_batch_without_objects(self, y): 123 """Whether any rank holds a batch without instances, which cannot be prompted. 124 125 Decided before the forward pass: its collectives would otherwise pair with the skip flag of a rank 126 that found no objects, and every rank has to skip the same iterations. 127 """ 128 skip = torch.tensor(int(not bool((y[:, 0] > 0).any())), device=self.device) 129 if dist.is_available() and dist.is_initialized(): 130 dist.all_reduce(skip, op=dist.ReduceOp.MAX) 131 return bool(skip.item()) 132 133 def _sync_decoder_buffers(self): 134 """Average the BatchNorm statistics of the decoder, which no DDP wrapper keeps in step across ranks.""" 135 if not (dist.is_available() and dist.is_initialized()): 136 return 137 for name, buffer in self.unetr.named_buffers(): 138 if name.startswith("encoder") or not buffer.is_floating_point(): 139 continue 140 dist.all_reduce(buffer, op=dist.ReduceOp.AVG) 141 142 def _interactive_step(self, x, y): 143 # Slice channel 0 (instance IDs) from the 5-channel joint label tensor. 144 return super()._interactive_step(x, y[:, 0:1].to(torch.int64)) 145 146 def _automatic_step(self, x, y, retain_grad=False): 147 x = x.to(self.device, non_blocking=True) 148 # Channels 1-4: foreground mask + 3 directed-distance channels. 149 y_dist = y[:, 1:].to(self.device, non_blocking=True) 150 pred = self.unetr(x) 151 if retain_grad: 152 pred.retain_grad() 153 return self.automatic_loss(pred, y_dist), y_dist, pred 154 155 def _sync_automatic_grads(self): 156 """All-reduce every gradient produced by the automatic backward pass. 157 158 The automatic branch bypasses the DDP wrapper, so nothing here has been reduced 159 already - including the encoder it shares with the interactive model. The gradients 160 are flattened into buckets before the collective, so the shared encoder costs a 161 handful of all-reduces per iteration instead of one per parameter tensor. 162 """ 163 if not (dist.is_available() and dist.is_initialized()): 164 return 165 grads = [p.grad for p in self.unetr.parameters() if p.grad is not None] 166 for bucket in _grad_buckets(grads): 167 flat = _flatten_dense_tensors(bucket) 168 dist.all_reduce(flat, op=dist.ReduceOp.AVG) 169 for grad, reduced in zip(bucket, _unflatten_dense_tensors(flat, bucket)): 170 grad.copy_(reduced) 171 172 def _clip_automatic_grads(self): 173 """Clip the automatic branch to the same norm as the interactive branch.""" 174 if self.clip_grad_norm is None: 175 return None 176 grad_norm = torch.nn.utils.clip_grad_norm_(self.unetr.parameters(), self.clip_grad_norm) 177 return grad_norm.item() 178 179 def _backprop_automatic(self, loss): 180 if self.scaler is not None: 181 self.scaler.scale(loss).backward() 182 if self.clip_grad_norm is not None: 183 self.scaler.unscale_(self.optimizer) 184 self._sync_automatic_grads() 185 grad_norm = self._clip_automatic_grads() 186 self.scaler.step(self.optimizer) 187 self.scaler.update() 188 else: 189 loss.backward() 190 self._sync_automatic_grads() 191 grad_norm = self._clip_automatic_grads() 192 self.optimizer.step() 193 return grad_norm 194 195 def _train_epoch_impl(self, progress, forward_context, backprop): 196 self.model.train() 197 self.unetr.train() 198 199 if hasattr(self.train_loader, "batch_sampler") and \ 200 hasattr(self.train_loader.batch_sampler, "set_epoch"): 201 self.train_loader.batch_sampler.set_epoch(self._epoch) 202 203 n_iter = 0 204 t_per_iter = time.time() 205 input_check_done = False 206 207 for x, y in self.train_loader: 208 input_check_done = self._check_input_normalization(x, input_check_done) 209 if self._skip_batch_without_objects(y): 210 continue 211 212 self.optimizer.zero_grad() 213 with forward_context(): 214 inter_loss, batch, outputs = self._interactive_step(x, y) 215 self._sam2_backprop(inter_loss) 216 217 log_imgs = (self._iteration % self.log_image_interval == 0) 218 self.optimizer.zero_grad() 219 with forward_context(): 220 auto_loss, y_dist, pred = self._automatic_step(x, y, retain_grad=log_imgs) 221 self._backprop_automatic(auto_loss) 222 223 if self.logger is not None: 224 lr = self.optimizer.param_groups[0]["lr"] 225 # Materialize both losses in one host sync instead of one per .item() call. 226 inter_value, auto_value = torch.stack( 227 [inter_loss.detach().float(), auto_loss.detach().float()] 228 ).tolist() 229 self.logger.log_train( 230 self._iteration, inter_value + auto_value, lr, inter_value, auto_value, 231 x=x if log_imgs else None, 232 y=y if log_imgs else None, 233 batch=batch if log_imgs else None, 234 outputs=outputs if log_imgs else None, 235 y_dist=y_dist if log_imgs else None, 236 pred=pred if log_imgs else None, 237 ) 238 239 self._iteration += 1 240 n_iter += 1 241 if self._iteration >= self.max_iteration: 242 break 243 progress.update(1) 244 245 return (time.time() - t_per_iter) / n_iter 246 247 def _validate_impl(self, forward_context): 248 self.model.eval() 249 self.unetr.eval() 250 251 # Accumulated on the device as [inter_loss, inter_metric, auto_loss, auto_metric], so the 252 # whole pass costs one host sync instead of four per iteration. 253 totals = torch.zeros(4, device=self.device) 254 n_iter = 0 255 input_check_done = False 256 log_x = log_y = log_batch = log_outputs = log_y_dist = log_pred = None 257 258 # Pick one validation sample to log via reservoir sampling, seeded per epoch. 259 log_rng = random.Random(VALIDATION_SEED + self._epoch) 260 261 self._sync_decoder_buffers() 262 # Pin the RNGs so the sampled prompts are identical every epoch. 263 with _pinned_validation_rng(self.model): 264 with torch.no_grad(): 265 for i, (x, y) in enumerate(self.val_loader): 266 input_check_done = self._check_input_normalization(x, input_check_done) 267 if self._skip_batch_without_objects(y): 268 continue 269 with forward_context(): 270 inter_loss, batch, outputs = self._interactive_step(x, y) 271 inter_metric = self.metric(outputs, batch.masks) 272 auto_loss, y_dist, pred = self._automatic_step(x, y) 273 auto_metric = self.automatic_metric(pred, y_dist) 274 totals += torch.stack([ 275 inter_loss.detach().float(), inter_metric.detach().float(), 276 auto_loss.detach().float(), auto_metric.detach().float(), 277 ]) 278 n_iter += 1 279 if log_rng.random() < 1.0 / (i + 1): 280 log_x, log_y, log_batch, log_outputs = x, y, batch, outputs 281 log_y_dist, log_pred = y_dist, pred 282 283 totals /= max(n_iter, 1) 284 combined = totals[1] + self.automatic_metric_weight * totals[3] 285 stats = torch.cat([totals, combined.unsqueeze(0)]) 286 287 # Synchronize across DDP ranks so every rank makes the same early-stopping decision. 288 if dist.is_available() and dist.is_initialized(): 289 dist.all_reduce(stats, op=dist.ReduceOp.AVG) 290 291 inter_loss_val, inter_metric_val, auto_loss_val, auto_metric_val, combined_metric = stats.tolist() 292 293 if self.logger is not None: 294 self.logger.log_validation( 295 self._iteration, inter_loss_val, inter_metric_val, auto_loss_val, auto_metric_val, 296 combined_metric, log_x, log_y, log_batch, log_outputs, log_y_dist, log_pred, 297 ) 298 299 return combined_metric
Trainer for joint interactive + automatic segmentation with SAM2 and UniSAM2.
Uses a single 5-channel label tensor per batch built by
~micro_sam.v2.datasets.generalist_loader._build_joint_datasets():
- Channel 0 (int64): instance IDs -> interactive branch.
- Channels 1-4 (float32): foreground mask + directed distances -> automatic branch.
Both branches see the same image patch, which halves the number of data loaders compared to using separate interactive and automatic datasets.
Each branch is trained with a separate forward-backward-step cycle per
iteration (matching micro-sam v1), so their loss scales never compete.
In DDP, only model (sam2_train_model) is DDP-wrapped; every gradient the
automatic backward produces - the unetr decoder and the shared image
encoder - is manually all_reduced via _sync_automatic_grads().
The shared encoder therefore takes two optimizer steps per batch, one per branch.
Arguments:
- unetr: UniSAM2 model constructed with
encoder=sam2_train_model.image_encoderso the backbone is shared with the interactive model. - convert_inputs: Converts (x, y_instances) torch-em tuples from the
loader into
BatchedVideoDatapointexpected by SAM2Train. - interactive_loss: Loss for the interactive branch (e.g.
CustomSAM2Loss). - automatic_loss: Loss for the automatic branch
(e.g.
DirectedDistanceLoss). - automatic_metric: Validation metric for the automatic branch. Defaults to
automatic_loss(matching train_automatic'smetric=loss). - automatic_metric_weight: Weight of the automatic metric in the combined validation
metric used for checkpointing and early stopping. Defaults to 1/4, putting
DirectedDistanceLoss's four summed terms on the scale of the interactive Dice metric. Set to 0 to select purely on the interactive task. - clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own finetuning uses 0.1.
- kwargs: Forwarded to
Sam2Trainer.modelshould be the sam2_train_model (or its DDP wrapper);train_loaderandval_loadermust yield(x, y)whereyhas 5 channels as described above.
87 def __init__( 88 self, 89 unetr: torch.nn.Module, 90 convert_inputs: Callable, 91 interactive_loss: torch.nn.Module, 92 automatic_loss: torch.nn.Module, 93 automatic_metric: Optional[torch.nn.Module] = None, 94 automatic_metric_weight: float = 0.25, 95 clip_grad_norm: Optional[float] = None, 96 **kwargs, 97 ): 98 super().__init__( 99 convert_inputs=convert_inputs, loss=interactive_loss, clip_grad_norm=clip_grad_norm, **kwargs, 100 ) 101 self.unetr = unetr 102 self.automatic_loss = automatic_loss 103 # Automatic metric mirrors train_automatic's metric=loss convention when not given. 104 self.automatic_metric = automatic_metric if automatic_metric is not None else automatic_loss 105 self.automatic_metric_weight = automatic_metric_weight
302class JointSam2Logger(TorchEmLogger): 303 """TensorBoard logger for JointSam2Trainer. Only rank 0 writes in DDP.""" 304 305 def __init__(self, trainer, save_root, **unused_kwargs): 306 super().__init__(trainer, save_root) 307 rank = getattr(trainer, "rank", None) 308 if rank is not None and rank != 0: 309 self.tb = None 310 return 311 self.log_dir = ( 312 f"./logs/{trainer.name}" if save_root is None 313 else os.path.join(save_root, "logs", trainer.name) 314 ) 315 os.makedirs(self.log_dir, exist_ok=True) 316 self.tb = SummaryWriter(self.log_dir) 317 self.log_image_interval = trainer.log_image_interval 318 319 def _masks_for_batch_item(self, batch, b=0, t=0): 320 b_indices = batch.obj_to_frame_idx[t, :, 1] 321 return batch.masks[t][b_indices == b] 322 323 def _log_interactive_images(self, step, x, y, batch, outputs, prefix): 324 is_3d = (x.ndim == 5) 325 raw = x[0, :3, 0].cpu().float() if is_3d else x[0, :3].cpu().float() 326 H, W = raw.shape[-2:] 327 self.tb.add_image(f"{prefix}/interactive/raw", raw, step) 328 329 gt_lbl = y[0, 0, 0].cpu().numpy() if is_3d else y[0, 0].cpu().numpy() 330 self.tb.add_image(f"{prefix}/interactive/gt_all", _colorize_instance_map(gt_lbl), step) 331 332 gt_chosen = self._masks_for_batch_item(batch, b=0, t=0) 333 self.tb.add_image( 334 f"{prefix}/interactive/gt_chosen", _overlay_binary_masks(gt_chosen, target_hw=(H, W)), step 335 ) 336 337 b_indices = batch.obj_to_frame_idx[0, :, 1] 338 pred_step0 = outputs[0]["multistep_pred_masks_high_res"][b_indices == 0, 0].detach() 339 self.tb.add_image( 340 f"{prefix}/interactive/predictions", _overlay_binary_masks(pred_step0 > 0, target_hw=(H, W)), step 341 ) 342 343 def _log_automatic_images(self, step, x, y_dist, pred, prefix): 344 from torch_em.trainer.tensorboard_logger import make_grid_image, normalize_im 345 346 selection = np.s_[0] if x.ndim == 4 else np.s_[0, :, x.shape[2] // 2] 347 image = normalize_im(x[selection].cpu()) 348 self.tb.add_image(f"{prefix}/automatic/input", image, step) 349 gradients = pred.grad if pred.grad is not None else None 350 im, im_name = make_grid_image(image, y_dist, pred, selection, gradients) 351 self.tb.add_image(f"{prefix}/automatic/{im_name}", im, step) 352 353 def log_train( 354 self, step, total_loss, lr, interactive_loss, auto_loss, 355 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None 356 ): 357 if self.tb is None: 358 return 359 self.tb.add_scalar("train/total_loss", total_loss, global_step=step) 360 self.tb.add_scalar("train/interactive_loss", interactive_loss, global_step=step) 361 self.tb.add_scalar("train/automatic_loss", auto_loss, global_step=step) 362 self.tb.add_scalar("train/learning_rate", lr, global_step=step) 363 if x is not None: 364 self._log_interactive_images(step, x, y, batch, outputs, "train") 365 self._log_automatic_images(step, x, y_dist, pred, "train") 366 367 def log_validation( 368 self, step, interactive_loss, interactive_metric, auto_loss, auto_metric, combined_metric, 369 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None, 370 ): 371 if self.tb is None: 372 return 373 self.tb.add_scalar("validation/interactive_loss", interactive_loss, global_step=step) 374 self.tb.add_scalar("validation/interactive_metric", interactive_metric, global_step=step) 375 self.tb.add_scalar("validation/automatic_loss", auto_loss, global_step=step) 376 self.tb.add_scalar("validation/automatic_metric", auto_metric, global_step=step) 377 self.tb.add_scalar("validation/combined_metric", combined_metric, global_step=step) 378 if x is not None: 379 self._log_interactive_images(step, x, y, batch, outputs, "validation") 380 self._log_automatic_images(step, x, y_dist, pred, "validation")
TensorBoard logger for JointSam2Trainer. Only rank 0 writes in DDP.
305 def __init__(self, trainer, save_root, **unused_kwargs): 306 super().__init__(trainer, save_root) 307 rank = getattr(trainer, "rank", None) 308 if rank is not None and rank != 0: 309 self.tb = None 310 return 311 self.log_dir = ( 312 f"./logs/{trainer.name}" if save_root is None 313 else os.path.join(save_root, "logs", trainer.name) 314 ) 315 os.makedirs(self.log_dir, exist_ok=True) 316 self.tb = SummaryWriter(self.log_dir) 317 self.log_image_interval = trainer.log_image_interval
353 def log_train( 354 self, step, total_loss, lr, interactive_loss, auto_loss, 355 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None 356 ): 357 if self.tb is None: 358 return 359 self.tb.add_scalar("train/total_loss", total_loss, global_step=step) 360 self.tb.add_scalar("train/interactive_loss", interactive_loss, global_step=step) 361 self.tb.add_scalar("train/automatic_loss", auto_loss, global_step=step) 362 self.tb.add_scalar("train/learning_rate", lr, global_step=step) 363 if x is not None: 364 self._log_interactive_images(step, x, y, batch, outputs, "train") 365 self._log_automatic_images(step, x, y_dist, pred, "train")
367 def log_validation( 368 self, step, interactive_loss, interactive_metric, auto_loss, auto_metric, combined_metric, 369 x=None, y=None, batch=None, outputs=None, y_dist=None, pred=None, 370 ): 371 if self.tb is None: 372 return 373 self.tb.add_scalar("validation/interactive_loss", interactive_loss, global_step=step) 374 self.tb.add_scalar("validation/interactive_metric", interactive_metric, global_step=step) 375 self.tb.add_scalar("validation/automatic_loss", auto_loss, global_step=step) 376 self.tb.add_scalar("validation/automatic_metric", auto_metric, global_step=step) 377 self.tb.add_scalar("validation/combined_metric", combined_metric, global_step=step) 378 if x is not None: 379 self._log_interactive_images(step, x, y, batch, outputs, "validation") 380 self._log_automatic_images(step, x, y_dist, pred, "validation")