micro_sam.v2.training.sam2_trainer
1import os 2import time 3import random 4import warnings 5import contextlib 6from typing import Callable, Optional 7 8import numpy as np 9 10import torch 11import torch.nn.functional as F 12import torch.distributed as dist 13 14import torch_em 15from torch_em.trainer.logger_base import TorchEmLogger 16 17from micro_sam.util import training_autocast_dtype 18from micro_sam.v2.loss.custom_sam2_loss import CORE_LOSS_KEY, CustomSAM2Metric 19 20# Fixed seed for the main-process randomness during validation (prompt/correction-click 21# sampling in SAM2Train, object subsampling in ConvertToSam2VideoBatch). Worker-side crop 22# randomness is pinned separately via the val loader's deterministic worker_init_fn. 23VALIDATION_SEED = 42 24 25 26def _snapshot_rng(): 27 """Capture the global RNG state so it can be restored after deterministic validation.""" 28 cuda_state = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None 29 return random.getstate(), np.random.get_state(), torch.get_rng_state(), cuda_state 30 31 32def _restore_rng(state): 33 """Restore the global RNG state captured by _snapshot_rng.""" 34 py_state, np_state, torch_state, cuda_state = state 35 random.setstate(py_state) 36 np.random.set_state(np_state) 37 torch.set_rng_state(torch_state) 38 if cuda_state is not None: 39 torch.cuda.set_rng_state_all(cuda_state) 40 41 42def _seed_all(seed): 43 """Seed the python, numpy, and torch (CPU + CUDA) global RNGs.""" 44 random.seed(seed) 45 np.random.seed(seed) 46 torch.manual_seed(seed) 47 if torch.cuda.is_available(): 48 torch.cuda.manual_seed_all(seed) 49 50 51def _sam2_model_rng(model): 52 """Return SAM2Train's private numpy Generator, unwrapping DDP. None if the model has none.""" 53 if isinstance(model, torch.nn.parallel.DistributedDataParallel): 54 model = model.module 55 return getattr(model, "rng", None) 56 57 58@contextlib.contextmanager 59def _pinned_validation_rng(model): 60 """Pin every RNG that affects validation, then restore it on exit. 61 62 Covers SAM2Train's own ``numpy.random.Generator``, which ``np.random.seed`` does not reach. 63 """ 64 rng_state = _snapshot_rng() 65 model_rng = _sam2_model_rng(model) 66 model_rng_state = None if model_rng is None else model_rng.bit_generator.state 67 _seed_all(VALIDATION_SEED) 68 if model_rng is not None: 69 model_rng.bit_generator.state = np.random.default_rng(VALIDATION_SEED).bit_generator.state 70 try: 71 yield 72 finally: 73 _restore_rng(rng_state) 74 if model_rng is not None: 75 model_rng.bit_generator.state = model_rng_state 76 77 78def _get_cmap(): 79 from matplotlib import colormaps 80 return colormaps["tab20"] 81 82 83def _colorize_instance_map(label_hw): 84 """(H,W) int64 numpy -> (3,H,W) float32 [0,1], one tab20 color per instance ID.""" 85 cmap = _get_cmap() 86 H, W = label_hw.shape 87 rgb = np.zeros((H, W, 3), dtype=np.float32) 88 for i, uid in enumerate(np.unique(label_hw)): 89 if uid == 0: 90 continue 91 rgb[label_hw == uid] = np.array(cmap(i % 20)[:3], dtype=np.float32) 92 return rgb.transpose(2, 0, 1) 93 94 95def _overlay_binary_masks(masks_ohw, target_hw=None): 96 """(O,H,W) bool tensor -> (3,H,W) float32 [0,1] overlay, one tab20 color per object.""" 97 cmap = _get_cmap() 98 O, H, W = masks_ohw.shape 99 rgb = np.zeros((H, W, 3), dtype=np.float32) 100 for i in range(O): 101 rgb[masks_ohw[i].cpu().numpy().astype(bool)] = np.array(cmap(i % 20)[:3], dtype=np.float32) 102 result = rgb.transpose(2, 0, 1) 103 if target_hw is not None and (H, W) != target_hw: 104 t = torch.from_numpy(result).unsqueeze(0) 105 result = F.interpolate(t, size=target_hw, mode="bilinear", align_corners=False).squeeze(0).numpy() 106 return result 107 108 109class CheckpointAdapter: 110 """Mixin that saves and loads checkpoints against the module a DDP wrapper holds. 111 112 Gives one on-disk format regardless of how training ran, so checkpoints transfer between 113 single-GPU and DDP in both directions. 114 """ 115 116 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 117 original_model = self.model 118 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): 119 self.model = self.model.module 120 peft_config = getattr(self.model, "peft_config", None) 121 if peft_config is not None: 122 extra_save_dict.setdefault("peft_kwargs", peft_config) 123 try: 124 super().save_checkpoint(name, current_metric, best_metric, **extra_save_dict) 125 finally: 126 self.model = original_model 127 128 def load_checkpoint(self, checkpoint="best"): 129 original_model = self.model 130 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): 131 self.model = self.model.module 132 try: 133 return super().load_checkpoint(checkpoint) 134 finally: 135 self.model = original_model 136 137 138class Sam2Trainer(CheckpointAdapter, torch_em.trainer.DefaultTrainer): 139 """torch-em style trainer for interactive segmentation with SAM2Train. 140 141 Uses SAM2Train (full model with video memory) and SAM2's native prompting 142 strategy, which handles 2D (T=1) and 3D/video (T>1) batches uniformly: 143 - T=1: forces point-input mode, one correction round. 144 - T>1: mixes point/box/mask prompts across frames with iterative correction. 145 146 The prompting logic (initial point/box/mask selection, iterative correction 147 from error regions) is fully embedded in SAM2Train.forward(). No manual 148 iterative loop is needed here. 149 150 Args: 151 convert_inputs: Callable that converts (x, y) torch-em batches to 152 BatchedVideoDatapoint. Use ConvertToSam2VideoBatch. 153 loss: Loss module compatible with SAM2Train outputs. Defaults to 154 MultiStepMultiMasksAndIous when constructed via train_sam2(). 155 kwargs: Forwarded to torch_em.trainer.DefaultTrainer (model, 156 train_loader, val_loader, optimizer, device, lr_scheduler, 157 logger, save_root, etc.). mixed_precision and mixed_precision_dtype 158 default to what the device runs natively, see 159 `micro_sam.util.training_autocast_dtype`. 160 """ 161 162 def __init__( 163 self, 164 convert_inputs: Callable, 165 loss: torch.nn.Module, 166 metric: Optional[torch.nn.Module] = None, 167 clip_grad_norm: Optional[float] = None, 168 **kwargs, 169 ): 170 # The validation metric mirrors v1 SamTrainer: a best-mask Dice score (here on the 171 # initial SAM2 prompt response). Default to CustomSAM2Metric if none is given. 172 if metric is None: 173 metric = CustomSAM2Metric() 174 # The hardware decides the precision. SAM2 trains in bfloat16 only. 175 dtype = training_autocast_dtype(kwargs.get("device")) 176 kwargs.setdefault("mixed_precision", dtype is not None) 177 kwargs.setdefault("mixed_precision_dtype", "bfloat16") 178 super().__init__(loss=loss, metric=metric, **kwargs) 179 self.convert_inputs = convert_inputs 180 self.clip_grad_norm = clip_grad_norm 181 self.interactive_loss = loss 182 self._kwargs = kwargs 183 184 def _amp_context(self): 185 return torch.autocast(device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype)) 186 187 # The parent pairs its mixed epoch with _backprop_mixed. SAM2 needs _sam2_backprop in both. 188 def _train_epoch(self, progress): 189 return self._train_epoch_impl(progress, contextlib.nullcontext, self._sam2_backprop) 190 191 def _train_epoch_mixed(self, progress): 192 return self._train_epoch_impl(progress, self._amp_context, self._sam2_backprop) 193 194 def _validate(self): 195 return self._validate_impl(contextlib.nullcontext) 196 197 def _validate_mixed(self): 198 return self._validate_impl(self._amp_context) 199 200 def _check_input_normalization(self, x, input_check_done): 201 if not input_check_done: 202 data_min, data_max = x.min().item(), x.max().item() 203 # Raise an error, because training on inputs in [0, 255] gives a model that you cannot use. 204 if data_max > 1: 205 raise ValueError( 206 f"The training inputs have the range [{data_min:.3g}, {data_max:.3g}], but the SAM2 trainer " 207 "expects inputs in [0, 1]. Normalize the inputs to [0, 1], for example with " 208 "`micro_sam.v2.normalization.normalize_raw`." 209 ) 210 if data_min < 0: 211 warnings.warn( 212 f"The training inputs have the minimum {data_min:.3g}, but the SAM2 trainer expects inputs " 213 "in [0, 1]. Normalize the inputs to [0, 1]." 214 ) 215 input_check_done = True 216 return input_check_done 217 218 def _sam2_backprop(self, loss: torch.Tensor): 219 """Backward + optional gradient clipping + optimizer step. 220 221 Returns the pre-clip total gradient norm when clipping is enabled, else None. 222 """ 223 grad_norm = None 224 if self.scaler is not None: 225 self.scaler.scale(loss).backward() 226 if self.clip_grad_norm is not None: 227 self.scaler.unscale_(self.optimizer) 228 grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip_grad_norm) 229 self.scaler.step(self.optimizer) 230 self.scaler.update() 231 else: 232 loss.backward() 233 if self.clip_grad_norm is not None: 234 grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip_grad_norm) 235 self.optimizer.step() 236 return None if grad_norm is None else grad_norm.item() 237 238 def _interactive_step(self, x, y): 239 # Convert on the device: the 1024x1024 resize dominates and is ~13x faster there, and 240 # the source patches transfer 4x less data than the resized ones. The trailing .to() 241 # only moves the metadata tensors, which are built on the host. 242 x = x.to(self.device, non_blocking=True) 243 y = y.to(self.device, non_blocking=True) 244 batch = self.convert_inputs(x, y) 245 batch = batch.to(self.device, non_blocking=True) 246 outputs = self.model(batch) 247 loss = self.interactive_loss(outputs, batch.masks)[CORE_LOSS_KEY] 248 return loss, batch, outputs 249 250 def _train_epoch_impl(self, progress, forward_context, backprop): 251 # Advance the distributed sampler seed so each epoch has a different shuffle. 252 if hasattr(self.train_loader, "batch_sampler") and \ 253 hasattr(self.train_loader.batch_sampler, "set_epoch"): 254 self.train_loader.batch_sampler.set_epoch(self._epoch) 255 256 self.model.train() 257 n_iter = 0 258 t_per_iter = time.time() 259 input_check_done = False 260 261 for x, y in self.train_loader: 262 input_check_done = self._check_input_normalization(x, input_check_done) 263 self.optimizer.zero_grad() 264 265 with forward_context(): 266 loss, batch, outputs = self._interactive_step(x, y) 267 268 grad_norm = self._sam2_backprop(loss) 269 270 if self.logger is not None: 271 log_imgs = (self._iteration % self.log_image_interval == 0) 272 lr = self.optimizer.param_groups[0]["lr"] 273 with torch.no_grad(): 274 metric = self.metric(outputs, batch.masks).item() 275 n_frames = x.shape[2] if x.ndim == 5 else 1 276 self.logger.log_train( 277 self._iteration, loss.item(), lr, 278 metric=metric, grad_norm=grad_norm, n_frames=n_frames, 279 x=x if log_imgs else None, 280 y=y if log_imgs else None, 281 batch=batch if log_imgs else None, 282 outputs=outputs if log_imgs else None, 283 ) 284 285 self._iteration += 1 286 n_iter += 1 287 if self._iteration >= self.max_iteration: 288 break 289 progress.update(1) 290 291 return (time.time() - t_per_iter) / n_iter 292 293 def _validate_impl(self, forward_context): 294 self.model.eval() 295 val_loss = 0.0 296 val_dice_loss = 0.0 297 n_iter = 0 298 input_check_done = False 299 log_x = log_y = log_batch = log_outputs = None 300 301 # Pick one validation sample to log via reservoir sampling, seeded per epoch so the 302 # logged image panels show a different sample each epoch (the metric still covers all 303 # samples). This is decoupled from the pinned validation order below, so the metric 304 # stays reproducible while the logged sample varies. 305 log_rng = random.Random(VALIDATION_SEED + self._epoch) 306 307 # Pin the RNGs so the sampled prompts are identical every epoch. Worker-side crop 308 # randomness is pinned via the val loader's deterministic worker_init_fn. 309 with _pinned_validation_rng(self.model): 310 with torch.no_grad(): 311 for i, (x, y) in enumerate(self.val_loader): 312 input_check_done = self._check_input_normalization(x, input_check_done) 313 with forward_context(): 314 loss, batch, outputs = self._interactive_step(x, y) 315 val_loss += loss.item() 316 val_dice_loss += self.metric(outputs, batch.masks).item() 317 n_iter += 1 318 if log_rng.random() < 1.0 / (i + 1): 319 log_x, log_y, log_batch, log_outputs = x, y, batch, outputs 320 321 val_loss /= max(n_iter, 1) 322 val_dice_loss /= max(n_iter, 1) 323 324 # Synchronize across DDP ranks so every rank makes the same early-stopping 325 # decision. Without this, ranks can desync and deadlock. 326 if dist.is_available() and dist.is_initialized(): 327 stats = torch.tensor([val_loss, val_dice_loss], device=self.device) 328 dist.all_reduce(stats, op=dist.ReduceOp.AVG) 329 val_loss, val_dice_loss = stats[0].item(), stats[1].item() 330 331 if self.logger is not None: 332 self.logger.log_validation( 333 self._iteration, val_loss, val_dice_loss, log_x, log_y, log_batch, log_outputs, 334 ) 335 336 # Return the v1-style best-mask Dice loss (lower is better) so checkpoint and 337 # early-stopping selection track segmentation quality rather than the raw loss. 338 return val_dice_loss 339 340 341class Sam2Logger(TorchEmLogger): 342 """TensorBoard logger for Sam2Trainer. 343 344 Logs scalars every step; logs four image panels at log_image_interval: 345 raw - input image (first batch item, first frame) 346 gt_all - colorized instance map (all objects in the patch) 347 gt_chosen - overlay of the objects sampled for this training step 348 predictions - model's predicted masks for the chosen objects 349 Only rank 0 writes; all other ranks are no-ops. 350 """ 351 352 def __init__(self, trainer, save_root, **unused_kwargs): 353 super().__init__(trainer, save_root) 354 rank = getattr(trainer, "rank", None) 355 if rank is not None and rank != 0: 356 self.tb = None 357 return 358 self.log_dir = ( 359 f"./logs/{trainer.name}" 360 if save_root is None 361 else os.path.join(save_root, "logs", trainer.name) 362 ) 363 os.makedirs(self.log_dir, exist_ok=True) 364 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 365 self.log_image_interval = trainer.log_image_interval 366 367 def _masks_for_batch_item(self, batch, b=0, t=0): 368 """Return binary masks from batch.masks for a single batch item at frame t. 369 370 batch.masks is (T, O_total, H, W) where O_total spans all batch items. 371 batch.obj_to_frame_idx is (T, O_total, 2): [:, :, 1] gives the batch index 372 for each object slot. Filter to only the objects belonging to batch item b. 373 """ 374 b_indices = batch.obj_to_frame_idx[t, :, 1] # (O_total,) 375 return batch.masks[t][b_indices == b] # (O_b, H, W) 376 377 def _log_images(self, step, x, y, batch, outputs, prefix): 378 is_3d = (x.ndim == 5) 379 380 # Raw: first batch item, first frame, first 3 channels - already [0, 1] 381 raw = x[0, :3, 0].cpu().float() if is_3d else x[0, :3].cpu().float() 382 H, W = raw.shape[-2:] 383 self.tb.add_image(f"{prefix}/raw", raw, step) 384 385 # GT all: colorized instance map for first batch item (all objects in the patch) 386 gt_lbl = y[0, 0, 0].cpu().numpy() if is_3d else y[0, 0].cpu().numpy() 387 self.tb.add_image(f"{prefix}/gt_all", _colorize_instance_map(gt_lbl), step) 388 389 # GT chosen: objects sampled for batch item 0 at frame 0 (subset of gt_all) 390 gt_chosen = self._masks_for_batch_item(batch, b=0, t=0) 391 self.tb.add_image(f"{prefix}/gt_chosen", _overlay_binary_masks(gt_chosen, target_hw=(H, W)), step) 392 393 # Predictions: show step-0 prediction (initial response to the first prompt, before 394 # oracle corrections). Final corrected output is near-identical to GT by design, 395 # since SAM2Train uses GT-derived clicks for iterative correction. 396 # multistep_pred_masks_high_res: (O_total, num_steps, 1024, 1024) 397 b_indices = batch.obj_to_frame_idx[0, :, 1] 398 pred_step0 = outputs[0]["multistep_pred_masks_high_res"][b_indices == 0, 0].detach() 399 self.tb.add_image(f"{prefix}/predictions", _overlay_binary_masks(pred_step0 > 0, target_hw=(H, W)), step) 400 401 def log_train( 402 self, step, loss, lr, metric=None, grad_norm=None, n_frames=None, x=None, y=None, batch=None, outputs=None 403 ): 404 if self.tb is None: 405 return 406 self.tb.add_scalar("train/loss", loss, step) 407 self.tb.add_scalar("train/learning_rate", lr, step) 408 if metric is not None: 409 self.tb.add_scalar("train/metric", metric, step) 410 if grad_norm is not None: 411 self.tb.add_scalar("train/grad_norm", grad_norm, step) 412 if n_frames is not None: 413 self.tb.add_scalar("train/n_frames", n_frames, step) 414 if x is not None: 415 self._log_images(step, x, y, batch, outputs, "train") 416 417 def log_validation(self, step, loss, metric=None, x=None, y=None, batch=None, outputs=None): 418 if self.tb is None: 419 return 420 self.tb.add_scalar("validation/loss", loss, step) 421 if metric is not None: 422 self.tb.add_scalar("validation/metric", metric, step) 423 if x is not None: 424 self._log_images(step, x, y, batch, outputs, "validation") 425 426 427class UniSAM2Trainer(CheckpointAdapter, torch_em.trainer.DefaultTrainer): 428 """DefaultTrainer subclass for UniSAM2 automatic segmentation. 429 430 Adds two DDP-compatible behaviours on top of DefaultTrainer: 431 - :class:`CheckpointAdapter` saves and loads checkpoints unwrapped, so they 432 transfer between DDP and non-DDP models. 433 - :meth:`_validate_impl` all_reduces the validation loss across ranks 434 so every rank makes the same early-stopping decision, and passes 435 the last batch to the logger for image visualization. 436 """ 437 438 def _validate_impl(self, forward_context): 439 self.model.eval() 440 metric_val = 0.0 441 n_iter = 0 442 last_x = last_y = last_pred = None 443 444 # Pin synchronous crop sampling without advancing the training RNG state. 445 with _pinned_validation_rng(self.model): 446 with torch.no_grad(): 447 for x, y in self.val_loader: 448 x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) 449 with forward_context(): 450 pred, loss = self._forward_and_loss(x, y) 451 metric_val += loss.item() 452 n_iter += 1 453 last_x, last_y, last_pred = x, y, pred 454 455 metric_val /= max(n_iter, 1) 456 457 if dist.is_available() and dist.is_initialized(): 458 val_tensor = torch.tensor(metric_val, device=self.device) 459 dist.all_reduce(val_tensor, op=dist.ReduceOp.AVG) 460 metric_val = val_tensor.item() 461 462 if self.logger is not None: 463 self.logger.log_validation(self._iteration, metric_val, last_x, last_y, last_pred) 464 465 return metric_val 466 467 468class UniSAM2Logger(TorchEmLogger): 469 """TensorBoard logger for UniSAM2Trainer. 470 471 Only rank 0 writes; all other ranks get a no-op logger. 472 Logs scalars every step and per-channel images of input, target, and 473 prediction at the trainer's log_image_interval. 474 """ 475 476 def __init__(self, trainer, save_root, **unused_kwargs): 477 super().__init__(trainer, save_root) 478 rank = getattr(trainer, "rank", None) 479 if rank is not None and rank != 0: 480 self.tb = None 481 return 482 self.log_dir = ( 483 f"./logs/{trainer.name}" 484 if save_root is None 485 else os.path.join(save_root, "logs", trainer.name) 486 ) 487 os.makedirs(self.log_dir, exist_ok=True) 488 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 489 self.log_image_interval = trainer.log_image_interval 490 491 def _log_images(self, step, x, y, pred, prefix, gradients=None): 492 from torch_em.trainer.tensorboard_logger import make_grid_image, normalize_im 493 494 selection = np.s_[0] if x.ndim == 4 else np.s_[0, :, x.shape[2] // 2] 495 image = normalize_im(x[selection].cpu()) 496 self.tb.add_image(f"{prefix}/input", image, step) 497 im, im_name = make_grid_image(image, y, pred, selection, gradients) 498 self.tb.add_image(f"{prefix}/{im_name}", im, step) 499 500 def log_train(self, step, loss, lr, x, y, pred, log_gradients=False): 501 if self.tb is None: 502 return 503 self.tb.add_scalar("train/loss", loss.item() if hasattr(loss, "item") else loss, step) 504 self.tb.add_scalar("train/learning_rate", lr, step) 505 if step % self.log_image_interval == 0: 506 gradients = pred.grad if log_gradients else None 507 self._log_images(step, x, y, pred, "train", gradients=gradients) 508 509 def log_validation(self, step, metric, x, y, pred): 510 if self.tb is None: 511 return 512 self.tb.add_scalar("validation/loss", metric, step) 513 if x is not None: 514 self._log_images(step, x, y, pred, "validation")
110class CheckpointAdapter: 111 """Mixin that saves and loads checkpoints against the module a DDP wrapper holds. 112 113 Gives one on-disk format regardless of how training ran, so checkpoints transfer between 114 single-GPU and DDP in both directions. 115 """ 116 117 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 118 original_model = self.model 119 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): 120 self.model = self.model.module 121 peft_config = getattr(self.model, "peft_config", None) 122 if peft_config is not None: 123 extra_save_dict.setdefault("peft_kwargs", peft_config) 124 try: 125 super().save_checkpoint(name, current_metric, best_metric, **extra_save_dict) 126 finally: 127 self.model = original_model 128 129 def load_checkpoint(self, checkpoint="best"): 130 original_model = self.model 131 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): 132 self.model = self.model.module 133 try: 134 return super().load_checkpoint(checkpoint) 135 finally: 136 self.model = original_model
Mixin that saves and loads checkpoints against the module a DDP wrapper holds.
Gives one on-disk format regardless of how training ran, so checkpoints transfer between single-GPU and DDP in both directions.
117 def save_checkpoint(self, name, current_metric, best_metric, **extra_save_dict): 118 original_model = self.model 119 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): 120 self.model = self.model.module 121 peft_config = getattr(self.model, "peft_config", None) 122 if peft_config is not None: 123 extra_save_dict.setdefault("peft_kwargs", peft_config) 124 try: 125 super().save_checkpoint(name, current_metric, best_metric, **extra_save_dict) 126 finally: 127 self.model = original_model
139class Sam2Trainer(CheckpointAdapter, torch_em.trainer.DefaultTrainer): 140 """torch-em style trainer for interactive segmentation with SAM2Train. 141 142 Uses SAM2Train (full model with video memory) and SAM2's native prompting 143 strategy, which handles 2D (T=1) and 3D/video (T>1) batches uniformly: 144 - T=1: forces point-input mode, one correction round. 145 - T>1: mixes point/box/mask prompts across frames with iterative correction. 146 147 The prompting logic (initial point/box/mask selection, iterative correction 148 from error regions) is fully embedded in SAM2Train.forward(). No manual 149 iterative loop is needed here. 150 151 Args: 152 convert_inputs: Callable that converts (x, y) torch-em batches to 153 BatchedVideoDatapoint. Use ConvertToSam2VideoBatch. 154 loss: Loss module compatible with SAM2Train outputs. Defaults to 155 MultiStepMultiMasksAndIous when constructed via train_sam2(). 156 kwargs: Forwarded to torch_em.trainer.DefaultTrainer (model, 157 train_loader, val_loader, optimizer, device, lr_scheduler, 158 logger, save_root, etc.). mixed_precision and mixed_precision_dtype 159 default to what the device runs natively, see 160 `micro_sam.util.training_autocast_dtype`. 161 """ 162 163 def __init__( 164 self, 165 convert_inputs: Callable, 166 loss: torch.nn.Module, 167 metric: Optional[torch.nn.Module] = None, 168 clip_grad_norm: Optional[float] = None, 169 **kwargs, 170 ): 171 # The validation metric mirrors v1 SamTrainer: a best-mask Dice score (here on the 172 # initial SAM2 prompt response). Default to CustomSAM2Metric if none is given. 173 if metric is None: 174 metric = CustomSAM2Metric() 175 # The hardware decides the precision. SAM2 trains in bfloat16 only. 176 dtype = training_autocast_dtype(kwargs.get("device")) 177 kwargs.setdefault("mixed_precision", dtype is not None) 178 kwargs.setdefault("mixed_precision_dtype", "bfloat16") 179 super().__init__(loss=loss, metric=metric, **kwargs) 180 self.convert_inputs = convert_inputs 181 self.clip_grad_norm = clip_grad_norm 182 self.interactive_loss = loss 183 self._kwargs = kwargs 184 185 def _amp_context(self): 186 return torch.autocast(device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype)) 187 188 # The parent pairs its mixed epoch with _backprop_mixed. SAM2 needs _sam2_backprop in both. 189 def _train_epoch(self, progress): 190 return self._train_epoch_impl(progress, contextlib.nullcontext, self._sam2_backprop) 191 192 def _train_epoch_mixed(self, progress): 193 return self._train_epoch_impl(progress, self._amp_context, self._sam2_backprop) 194 195 def _validate(self): 196 return self._validate_impl(contextlib.nullcontext) 197 198 def _validate_mixed(self): 199 return self._validate_impl(self._amp_context) 200 201 def _check_input_normalization(self, x, input_check_done): 202 if not input_check_done: 203 data_min, data_max = x.min().item(), x.max().item() 204 # Raise an error, because training on inputs in [0, 255] gives a model that you cannot use. 205 if data_max > 1: 206 raise ValueError( 207 f"The training inputs have the range [{data_min:.3g}, {data_max:.3g}], but the SAM2 trainer " 208 "expects inputs in [0, 1]. Normalize the inputs to [0, 1], for example with " 209 "`micro_sam.v2.normalization.normalize_raw`." 210 ) 211 if data_min < 0: 212 warnings.warn( 213 f"The training inputs have the minimum {data_min:.3g}, but the SAM2 trainer expects inputs " 214 "in [0, 1]. Normalize the inputs to [0, 1]." 215 ) 216 input_check_done = True 217 return input_check_done 218 219 def _sam2_backprop(self, loss: torch.Tensor): 220 """Backward + optional gradient clipping + optimizer step. 221 222 Returns the pre-clip total gradient norm when clipping is enabled, else None. 223 """ 224 grad_norm = None 225 if self.scaler is not None: 226 self.scaler.scale(loss).backward() 227 if self.clip_grad_norm is not None: 228 self.scaler.unscale_(self.optimizer) 229 grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip_grad_norm) 230 self.scaler.step(self.optimizer) 231 self.scaler.update() 232 else: 233 loss.backward() 234 if self.clip_grad_norm is not None: 235 grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip_grad_norm) 236 self.optimizer.step() 237 return None if grad_norm is None else grad_norm.item() 238 239 def _interactive_step(self, x, y): 240 # Convert on the device: the 1024x1024 resize dominates and is ~13x faster there, and 241 # the source patches transfer 4x less data than the resized ones. The trailing .to() 242 # only moves the metadata tensors, which are built on the host. 243 x = x.to(self.device, non_blocking=True) 244 y = y.to(self.device, non_blocking=True) 245 batch = self.convert_inputs(x, y) 246 batch = batch.to(self.device, non_blocking=True) 247 outputs = self.model(batch) 248 loss = self.interactive_loss(outputs, batch.masks)[CORE_LOSS_KEY] 249 return loss, batch, outputs 250 251 def _train_epoch_impl(self, progress, forward_context, backprop): 252 # Advance the distributed sampler seed so each epoch has a different shuffle. 253 if hasattr(self.train_loader, "batch_sampler") and \ 254 hasattr(self.train_loader.batch_sampler, "set_epoch"): 255 self.train_loader.batch_sampler.set_epoch(self._epoch) 256 257 self.model.train() 258 n_iter = 0 259 t_per_iter = time.time() 260 input_check_done = False 261 262 for x, y in self.train_loader: 263 input_check_done = self._check_input_normalization(x, input_check_done) 264 self.optimizer.zero_grad() 265 266 with forward_context(): 267 loss, batch, outputs = self._interactive_step(x, y) 268 269 grad_norm = self._sam2_backprop(loss) 270 271 if self.logger is not None: 272 log_imgs = (self._iteration % self.log_image_interval == 0) 273 lr = self.optimizer.param_groups[0]["lr"] 274 with torch.no_grad(): 275 metric = self.metric(outputs, batch.masks).item() 276 n_frames = x.shape[2] if x.ndim == 5 else 1 277 self.logger.log_train( 278 self._iteration, loss.item(), lr, 279 metric=metric, grad_norm=grad_norm, n_frames=n_frames, 280 x=x if log_imgs else None, 281 y=y if log_imgs else None, 282 batch=batch if log_imgs else None, 283 outputs=outputs if log_imgs else None, 284 ) 285 286 self._iteration += 1 287 n_iter += 1 288 if self._iteration >= self.max_iteration: 289 break 290 progress.update(1) 291 292 return (time.time() - t_per_iter) / n_iter 293 294 def _validate_impl(self, forward_context): 295 self.model.eval() 296 val_loss = 0.0 297 val_dice_loss = 0.0 298 n_iter = 0 299 input_check_done = False 300 log_x = log_y = log_batch = log_outputs = None 301 302 # Pick one validation sample to log via reservoir sampling, seeded per epoch so the 303 # logged image panels show a different sample each epoch (the metric still covers all 304 # samples). This is decoupled from the pinned validation order below, so the metric 305 # stays reproducible while the logged sample varies. 306 log_rng = random.Random(VALIDATION_SEED + self._epoch) 307 308 # Pin the RNGs so the sampled prompts are identical every epoch. Worker-side crop 309 # randomness is pinned via the val loader's deterministic worker_init_fn. 310 with _pinned_validation_rng(self.model): 311 with torch.no_grad(): 312 for i, (x, y) in enumerate(self.val_loader): 313 input_check_done = self._check_input_normalization(x, input_check_done) 314 with forward_context(): 315 loss, batch, outputs = self._interactive_step(x, y) 316 val_loss += loss.item() 317 val_dice_loss += self.metric(outputs, batch.masks).item() 318 n_iter += 1 319 if log_rng.random() < 1.0 / (i + 1): 320 log_x, log_y, log_batch, log_outputs = x, y, batch, outputs 321 322 val_loss /= max(n_iter, 1) 323 val_dice_loss /= max(n_iter, 1) 324 325 # Synchronize across DDP ranks so every rank makes the same early-stopping 326 # decision. Without this, ranks can desync and deadlock. 327 if dist.is_available() and dist.is_initialized(): 328 stats = torch.tensor([val_loss, val_dice_loss], device=self.device) 329 dist.all_reduce(stats, op=dist.ReduceOp.AVG) 330 val_loss, val_dice_loss = stats[0].item(), stats[1].item() 331 332 if self.logger is not None: 333 self.logger.log_validation( 334 self._iteration, val_loss, val_dice_loss, log_x, log_y, log_batch, log_outputs, 335 ) 336 337 # Return the v1-style best-mask Dice loss (lower is better) so checkpoint and 338 # early-stopping selection track segmentation quality rather than the raw loss. 339 return val_dice_loss
torch-em style trainer for interactive segmentation with SAM2Train.
Uses SAM2Train (full model with video memory) and SAM2's native prompting strategy, which handles 2D (T=1) and 3D/video (T>1) batches uniformly:
- T=1: forces point-input mode, one correction round.
- T>1: mixes point/box/mask prompts across frames with iterative correction.
The prompting logic (initial point/box/mask selection, iterative correction from error regions) is fully embedded in SAM2Train.forward(). No manual iterative loop is needed here.
Arguments:
- convert_inputs: Callable that converts (x, y) torch-em batches to BatchedVideoDatapoint. Use ConvertToSam2VideoBatch.
- loss: Loss module compatible with SAM2Train outputs. Defaults to MultiStepMultiMasksAndIous when constructed via train_sam2().
- kwargs: Forwarded to torch_em.trainer.DefaultTrainer (model,
train_loader, val_loader, optimizer, device, lr_scheduler,
logger, save_root, etc.). mixed_precision and mixed_precision_dtype
default to what the device runs natively, see
micro_sam.util.training_autocast_dtype.
163 def __init__( 164 self, 165 convert_inputs: Callable, 166 loss: torch.nn.Module, 167 metric: Optional[torch.nn.Module] = None, 168 clip_grad_norm: Optional[float] = None, 169 **kwargs, 170 ): 171 # The validation metric mirrors v1 SamTrainer: a best-mask Dice score (here on the 172 # initial SAM2 prompt response). Default to CustomSAM2Metric if none is given. 173 if metric is None: 174 metric = CustomSAM2Metric() 175 # The hardware decides the precision. SAM2 trains in bfloat16 only. 176 dtype = training_autocast_dtype(kwargs.get("device")) 177 kwargs.setdefault("mixed_precision", dtype is not None) 178 kwargs.setdefault("mixed_precision_dtype", "bfloat16") 179 super().__init__(loss=loss, metric=metric, **kwargs) 180 self.convert_inputs = convert_inputs 181 self.clip_grad_norm = clip_grad_norm 182 self.interactive_loss = loss 183 self._kwargs = kwargs
342class Sam2Logger(TorchEmLogger): 343 """TensorBoard logger for Sam2Trainer. 344 345 Logs scalars every step; logs four image panels at log_image_interval: 346 raw - input image (first batch item, first frame) 347 gt_all - colorized instance map (all objects in the patch) 348 gt_chosen - overlay of the objects sampled for this training step 349 predictions - model's predicted masks for the chosen objects 350 Only rank 0 writes; all other ranks are no-ops. 351 """ 352 353 def __init__(self, trainer, save_root, **unused_kwargs): 354 super().__init__(trainer, save_root) 355 rank = getattr(trainer, "rank", None) 356 if rank is not None and rank != 0: 357 self.tb = None 358 return 359 self.log_dir = ( 360 f"./logs/{trainer.name}" 361 if save_root is None 362 else os.path.join(save_root, "logs", trainer.name) 363 ) 364 os.makedirs(self.log_dir, exist_ok=True) 365 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 366 self.log_image_interval = trainer.log_image_interval 367 368 def _masks_for_batch_item(self, batch, b=0, t=0): 369 """Return binary masks from batch.masks for a single batch item at frame t. 370 371 batch.masks is (T, O_total, H, W) where O_total spans all batch items. 372 batch.obj_to_frame_idx is (T, O_total, 2): [:, :, 1] gives the batch index 373 for each object slot. Filter to only the objects belonging to batch item b. 374 """ 375 b_indices = batch.obj_to_frame_idx[t, :, 1] # (O_total,) 376 return batch.masks[t][b_indices == b] # (O_b, H, W) 377 378 def _log_images(self, step, x, y, batch, outputs, prefix): 379 is_3d = (x.ndim == 5) 380 381 # Raw: first batch item, first frame, first 3 channels - already [0, 1] 382 raw = x[0, :3, 0].cpu().float() if is_3d else x[0, :3].cpu().float() 383 H, W = raw.shape[-2:] 384 self.tb.add_image(f"{prefix}/raw", raw, step) 385 386 # GT all: colorized instance map for first batch item (all objects in the patch) 387 gt_lbl = y[0, 0, 0].cpu().numpy() if is_3d else y[0, 0].cpu().numpy() 388 self.tb.add_image(f"{prefix}/gt_all", _colorize_instance_map(gt_lbl), step) 389 390 # GT chosen: objects sampled for batch item 0 at frame 0 (subset of gt_all) 391 gt_chosen = self._masks_for_batch_item(batch, b=0, t=0) 392 self.tb.add_image(f"{prefix}/gt_chosen", _overlay_binary_masks(gt_chosen, target_hw=(H, W)), step) 393 394 # Predictions: show step-0 prediction (initial response to the first prompt, before 395 # oracle corrections). Final corrected output is near-identical to GT by design, 396 # since SAM2Train uses GT-derived clicks for iterative correction. 397 # multistep_pred_masks_high_res: (O_total, num_steps, 1024, 1024) 398 b_indices = batch.obj_to_frame_idx[0, :, 1] 399 pred_step0 = outputs[0]["multistep_pred_masks_high_res"][b_indices == 0, 0].detach() 400 self.tb.add_image(f"{prefix}/predictions", _overlay_binary_masks(pred_step0 > 0, target_hw=(H, W)), step) 401 402 def log_train( 403 self, step, loss, lr, metric=None, grad_norm=None, n_frames=None, x=None, y=None, batch=None, outputs=None 404 ): 405 if self.tb is None: 406 return 407 self.tb.add_scalar("train/loss", loss, step) 408 self.tb.add_scalar("train/learning_rate", lr, step) 409 if metric is not None: 410 self.tb.add_scalar("train/metric", metric, step) 411 if grad_norm is not None: 412 self.tb.add_scalar("train/grad_norm", grad_norm, step) 413 if n_frames is not None: 414 self.tb.add_scalar("train/n_frames", n_frames, step) 415 if x is not None: 416 self._log_images(step, x, y, batch, outputs, "train") 417 418 def log_validation(self, step, loss, metric=None, x=None, y=None, batch=None, outputs=None): 419 if self.tb is None: 420 return 421 self.tb.add_scalar("validation/loss", loss, step) 422 if metric is not None: 423 self.tb.add_scalar("validation/metric", metric, step) 424 if x is not None: 425 self._log_images(step, x, y, batch, outputs, "validation")
TensorBoard logger for Sam2Trainer.
Logs scalars every step; logs four image panels at log_image_interval: raw - input image (first batch item, first frame) gt_all - colorized instance map (all objects in the patch) gt_chosen - overlay of the objects sampled for this training step predictions - model's predicted masks for the chosen objects Only rank 0 writes; all other ranks are no-ops.
353 def __init__(self, trainer, save_root, **unused_kwargs): 354 super().__init__(trainer, save_root) 355 rank = getattr(trainer, "rank", None) 356 if rank is not None and rank != 0: 357 self.tb = None 358 return 359 self.log_dir = ( 360 f"./logs/{trainer.name}" 361 if save_root is None 362 else os.path.join(save_root, "logs", trainer.name) 363 ) 364 os.makedirs(self.log_dir, exist_ok=True) 365 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 366 self.log_image_interval = trainer.log_image_interval
402 def log_train( 403 self, step, loss, lr, metric=None, grad_norm=None, n_frames=None, x=None, y=None, batch=None, outputs=None 404 ): 405 if self.tb is None: 406 return 407 self.tb.add_scalar("train/loss", loss, step) 408 self.tb.add_scalar("train/learning_rate", lr, step) 409 if metric is not None: 410 self.tb.add_scalar("train/metric", metric, step) 411 if grad_norm is not None: 412 self.tb.add_scalar("train/grad_norm", grad_norm, step) 413 if n_frames is not None: 414 self.tb.add_scalar("train/n_frames", n_frames, step) 415 if x is not None: 416 self._log_images(step, x, y, batch, outputs, "train")
418 def log_validation(self, step, loss, metric=None, x=None, y=None, batch=None, outputs=None): 419 if self.tb is None: 420 return 421 self.tb.add_scalar("validation/loss", loss, step) 422 if metric is not None: 423 self.tb.add_scalar("validation/metric", metric, step) 424 if x is not None: 425 self._log_images(step, x, y, batch, outputs, "validation")
428class UniSAM2Trainer(CheckpointAdapter, torch_em.trainer.DefaultTrainer): 429 """DefaultTrainer subclass for UniSAM2 automatic segmentation. 430 431 Adds two DDP-compatible behaviours on top of DefaultTrainer: 432 - :class:`CheckpointAdapter` saves and loads checkpoints unwrapped, so they 433 transfer between DDP and non-DDP models. 434 - :meth:`_validate_impl` all_reduces the validation loss across ranks 435 so every rank makes the same early-stopping decision, and passes 436 the last batch to the logger for image visualization. 437 """ 438 439 def _validate_impl(self, forward_context): 440 self.model.eval() 441 metric_val = 0.0 442 n_iter = 0 443 last_x = last_y = last_pred = None 444 445 # Pin synchronous crop sampling without advancing the training RNG state. 446 with _pinned_validation_rng(self.model): 447 with torch.no_grad(): 448 for x, y in self.val_loader: 449 x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) 450 with forward_context(): 451 pred, loss = self._forward_and_loss(x, y) 452 metric_val += loss.item() 453 n_iter += 1 454 last_x, last_y, last_pred = x, y, pred 455 456 metric_val /= max(n_iter, 1) 457 458 if dist.is_available() and dist.is_initialized(): 459 val_tensor = torch.tensor(metric_val, device=self.device) 460 dist.all_reduce(val_tensor, op=dist.ReduceOp.AVG) 461 metric_val = val_tensor.item() 462 463 if self.logger is not None: 464 self.logger.log_validation(self._iteration, metric_val, last_x, last_y, last_pred) 465 466 return metric_val
DefaultTrainer subclass for UniSAM2 automatic segmentation.
Adds two DDP-compatible behaviours on top of DefaultTrainer:
CheckpointAdaptersaves and loads checkpoints unwrapped, so they transfer between DDP and non-DDP models._validate_impl()all_reduces the validation loss across ranks so every rank makes the same early-stopping decision, and passes the last batch to the logger for image visualization.
469class UniSAM2Logger(TorchEmLogger): 470 """TensorBoard logger for UniSAM2Trainer. 471 472 Only rank 0 writes; all other ranks get a no-op logger. 473 Logs scalars every step and per-channel images of input, target, and 474 prediction at the trainer's log_image_interval. 475 """ 476 477 def __init__(self, trainer, save_root, **unused_kwargs): 478 super().__init__(trainer, save_root) 479 rank = getattr(trainer, "rank", None) 480 if rank is not None and rank != 0: 481 self.tb = None 482 return 483 self.log_dir = ( 484 f"./logs/{trainer.name}" 485 if save_root is None 486 else os.path.join(save_root, "logs", trainer.name) 487 ) 488 os.makedirs(self.log_dir, exist_ok=True) 489 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 490 self.log_image_interval = trainer.log_image_interval 491 492 def _log_images(self, step, x, y, pred, prefix, gradients=None): 493 from torch_em.trainer.tensorboard_logger import make_grid_image, normalize_im 494 495 selection = np.s_[0] if x.ndim == 4 else np.s_[0, :, x.shape[2] // 2] 496 image = normalize_im(x[selection].cpu()) 497 self.tb.add_image(f"{prefix}/input", image, step) 498 im, im_name = make_grid_image(image, y, pred, selection, gradients) 499 self.tb.add_image(f"{prefix}/{im_name}", im, step) 500 501 def log_train(self, step, loss, lr, x, y, pred, log_gradients=False): 502 if self.tb is None: 503 return 504 self.tb.add_scalar("train/loss", loss.item() if hasattr(loss, "item") else loss, step) 505 self.tb.add_scalar("train/learning_rate", lr, step) 506 if step % self.log_image_interval == 0: 507 gradients = pred.grad if log_gradients else None 508 self._log_images(step, x, y, pred, "train", gradients=gradients) 509 510 def log_validation(self, step, metric, x, y, pred): 511 if self.tb is None: 512 return 513 self.tb.add_scalar("validation/loss", metric, step) 514 if x is not None: 515 self._log_images(step, x, y, pred, "validation")
TensorBoard logger for UniSAM2Trainer.
Only rank 0 writes; all other ranks get a no-op logger. Logs scalars every step and per-channel images of input, target, and prediction at the trainer's log_image_interval.
477 def __init__(self, trainer, save_root, **unused_kwargs): 478 super().__init__(trainer, save_root) 479 rank = getattr(trainer, "rank", None) 480 if rank is not None and rank != 0: 481 self.tb = None 482 return 483 self.log_dir = ( 484 f"./logs/{trainer.name}" 485 if save_root is None 486 else os.path.join(save_root, "logs", trainer.name) 487 ) 488 os.makedirs(self.log_dir, exist_ok=True) 489 self.tb = torch.utils.tensorboard.SummaryWriter(self.log_dir) 490 self.log_image_interval = trainer.log_image_interval
501 def log_train(self, step, loss, lr, x, y, pred, log_gradients=False): 502 if self.tb is None: 503 return 504 self.tb.add_scalar("train/loss", loss.item() if hasattr(loss, "item") else loss, step) 505 self.tb.add_scalar("train/learning_rate", lr, step) 506 if step % self.log_image_interval == 0: 507 gradients = pred.grad if log_gradients else None 508 self._log_images(step, x, y, pred, "train", gradients=gradients)