micro_sam.v2.training.training
1import os 2import re 3import sys 4import time 5import traceback 6from datetime import timedelta 7from typing import Any, Dict, List, Optional, Union 8 9import numpy as np 10 11import torch 12import torch._dynamo 13import torch._inductor.config 14import torch.distributed as dist 15from torch.utils.data import DataLoader 16 17from micro_sam.v2.transforms.raw import VideoAugment 18from micro_sam.v2.util import has_registered_decoder 19from micro_sam.v2.loss.custom_sam2_loss import CustomSAM2Loss 20from micro_sam.util import get_device, training_autocast_dtype 21from micro_sam.v2.loss.semantic_loss import CustomCombinedLoss 22from .util import get_sam2_train_model, ConvertToSam2VideoBatch 23from .joint_sam2_trainer import JointSam2Trainer, JointSam2Logger 24from micro_sam.v1.training.semantic_sam_trainer import CustomDiceLoss 25from micro_sam.v2.loss.directed_distance_based import DirectedDistanceLoss 26from .sam2_trainer import Sam2Trainer, Sam2Logger, UniSAM2Trainer, UniSAM2Logger 27 28 29def _no_wd_names(model): 30 """Return the set of parameter names that must have weight_decay=0. 31 32 Matches the MOSE finetune config: bias params and all LayerNorm params. 33 """ 34 names = set() 35 for mn, m in model.named_modules(): 36 if isinstance(m, torch.nn.LayerNorm): 37 for pn, _ in m.named_parameters(recurse=False): 38 names.add(f"{mn}.{pn}" if mn else pn) 39 for pn, _ in model.named_parameters(): 40 if "bias" in pn: 41 names.add(pn) 42 return names 43 44 45def _param_lr_map(model, lr, vision_lr, layer_decay): 46 """Return {param_name: learning_rate} for layer-decayed vision encoder params. 47 48 Per the MOSE finetune YAML: 49 - pos_embed gets vision_lr (no decay, override to scale=1.0 in YAML) 50 - trunk block k gets vision_lr * layer_decay^(n_blocks - k) 51 (block 0 is shallowest, gets the most decay) 52 - other trunk params (patch_embed, stem norm, etc.) get vision_lr * layer_decay^n_blocks 53 - non-trunk encoder params (neck, fpn, etc.) get vision_lr unchanged 54 - non-encoder params get lr 55 """ 56 n_blocks = 0 57 for name, _ in model.named_parameters(): 58 m = re.search(r"image_encoder\.trunk\.blocks\.(\d+)\.", name) 59 if m: 60 n_blocks = max(n_blocks, int(m.group(1)) + 1) 61 62 param_lr = {} 63 for name, _ in model.named_parameters(): 64 if not name.startswith("image_encoder"): 65 param_lr[name] = lr 66 elif "pos_embed" in name: 67 param_lr[name] = vision_lr 68 else: 69 m = re.search(r"image_encoder\.trunk\.blocks\.(\d+)\.", name) 70 if m: 71 k = int(m.group(1)) 72 param_lr[name] = vision_lr * (layer_decay ** (n_blocks - k)) 73 elif name.startswith("image_encoder.trunk"): 74 param_lr[name] = vision_lr * (layer_decay ** n_blocks) 75 else: 76 param_lr[name] = vision_lr 77 return param_lr 78 79 80def _build_optimizer(model, lr, vision_lr=None, layer_decay=1.0): 81 no_wd = _no_wd_names(model) 82 83 if vision_lr is None: 84 decay = [p for n, p in model.named_parameters() if n not in no_wd and p.requires_grad] 85 no_decay = [p for n, p in model.named_parameters() if n in no_wd and p.requires_grad] 86 return torch.optim.AdamW([ 87 {"params": decay, "weight_decay": 0.1}, 88 {"params": no_decay, "weight_decay": 0.0}, 89 ], lr=lr) 90 91 p_lr_map = _param_lr_map(model, lr=lr, vision_lr=vision_lr, layer_decay=layer_decay) 92 groups = {} 93 for name, param in model.named_parameters(): 94 if not param.requires_grad: 95 continue 96 p_lr = p_lr_map[name] 97 p_wd = 0.0 if name in no_wd else 0.1 98 key = (f"{p_lr:.12e}", p_wd) 99 if key not in groups: 100 groups[key] = {"params": [], "lr": p_lr, "weight_decay": p_wd} 101 groups[key]["params"].append(param) 102 return torch.optim.AdamW(list(groups.values())) 103 104 105def _build_scheduler(optimizer, patience=5, factor=0.9, mode="min"): 106 """ReduceLROnPlateau scheduler keyed on the validation metric. 107 108 torch-em's DefaultTrainer calls lr_scheduler.step(current_metric) after each 109 validation, so the LR is multiplied by `factor` after `patience` epochs without 110 improvement in the validation metric (lower is better). 111 """ 112 return torch.optim.lr_scheduler.ReduceLROnPlateau( 113 optimizer, mode=mode, factor=factor, patience=patience, 114 ) 115 116 117def train_sam2( 118 name: str, 119 model_type: str, 120 train_loader: DataLoader, 121 val_loader: DataLoader, 122 n_epochs: int = 100, 123 n_iterations: Optional[int] = None, 124 early_stopping: Optional[int] = 10, 125 max_num_objects: int = 20, 126 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 127 peft_kwargs: Optional[Dict] = None, 128 device: Optional[Union[str, torch.device]] = None, 129 lr: float = 1e-5, 130 vision_lr: Optional[float] = None, 131 save_root: Optional[Union[str, os.PathLike]] = None, 132 save_every_kth_epoch: Optional[int] = None, 133 overwrite_training: bool = True, 134 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 135 prob_to_use_pt_input: float = 0.5, 136 prob_to_use_box_input: float = 0.5, 137 num_frames_to_correct: int = 1, 138 rand_frames_to_correct: bool = True, 139 prob_to_sample_from_gt: float = 0.1, 140 add_all_frames_to_correct_as_cond: bool = True, 141 num_correction_pt_per_frame: int = 7, 142 num_init_cond_frames: int = 2, 143 clip_grad_norm: Optional[float] = None, 144 layer_decay: float = 1.0, 145 scheduler_kwargs: Optional[Dict[str, Any]] = None, 146 largest_first: bool = False, 147 augment: bool = False, 148 bidirectional: bool = False, 149 use_focal_loss: bool = False, 150 focal_weight: float = 20.0, 151 use_object_score_loss: bool = False, 152 average_over_frames: bool = False, 153) -> None: 154 """Train SAM2 for interactive segmentation with SAM2's native prompting strategy. 155 156 Uses SAM2Train (full model with video memory) which handles both 2D (T=1) and 157 3D/video (T>1) batches. All prompting logic - initial point/box/mask selection 158 and iterative correction from error regions - is embedded in the model forward 159 pass. Pass a MixedLoader(loader_2d, loader_3d) as train_loader for joint 2D+3D 160 training. Build the loaders for your own data with 161 `micro_sam.v2.training.loaders.default_sam2_loader` and ``mode="interactive"``. 162 163 Args: 164 name: Checkpoint/log folder name. 165 model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 166 train_loader: DataLoader yielding (x, y) tuples with integer instance labels. 167 x: (B,C,H,W) for 2D or (B,C,Z,H,W) for 3D in [0, 1]. 168 `default_sam2_loader` normalizes the images to this range. 169 y: (B,1,H,W) or (B,1,Z,H,W) with integer instance IDs. 170 val_loader: Same format as train_loader, used for validation. 171 n_epochs: Training epochs. 172 n_iterations: Override n_epochs with a fixed iteration budget. 173 early_stopping: Stop after this many epochs without improvement (None = off). 174 max_num_objects: Max objects sampled per image/volume per step. 175 checkpoint_path: Custom checkpoint path. Downloads default weights if None. 176 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 177 device: Training device. Auto-selects if None. 178 lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+). 179 vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. 180 SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr. 181 save_root: Root directory for checkpoints and logs. 182 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 183 overwrite_training: Overwrite an existing checkpoint at the same path. 184 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 185 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 186 the pretrained SAM2 weights to start from. 187 prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation). 188 prob_to_use_box_input: Conditional probability of using a box instead of a click. 189 num_frames_to_correct: Max frames per volume that receive iterative correction 190 clicks. Set equal to the number of z-slices to correct every frame. 191 rand_frames_to_correct: Randomly sample 1..num_frames_to_correct frames to 192 correct per step rather than always correcting the maximum. 193 prob_to_sample_from_gt: Probability of sampling a correction click from GT 194 instead of the error region - reduces overfitting to error patterns. 195 add_all_frames_to_correct_as_cond: Add frames that receive correction clicks 196 as conditioning frames for memory propagation. 197 num_correction_pt_per_frame: Number of correction clicks per frame per correction 198 round. SAM2 default is 7. 199 num_init_cond_frames: Number of initial conditioning frames (frames that receive 200 the first prompt before any correction round). The MOSE finetune config uses 2. 201 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 202 finetuning uses 0.1. 203 scheduler_kwargs: ReduceLROnPlateau kwargs (mode, factor, patience). Defaults to 204 factor=0.9, patience=5. 205 layer_decay: Multiplicative LR decay applied per trunk block toward shallower 206 layers (block 0 gets vision_lr * layer_decay^n_blocks). The MOSE finetune 207 config uses 0.9. Only active when vision_lr is set. Default 1.0 = no decay. 208 augment: Apply SAM2 MOSE-style data augmentations (RandomHorizontalFlip, 209 RandomAffine, ColorJitter, RandomGrayscale) before each forward pass. 210 Augmentations are applied consistently across frames for 3D volumes. 211 bidirectional: If True, use bidirectional propagation during training: a random 212 z-frame is chosen as the start frame each step, with propagation and correction 213 clicks applied in both directions. No effect for 2D (T=1) batches. 214 use_focal_loss: Add SAM2's sigmoid focal mask loss on top of the Dice loss in 215 CustomSAM2Loss. Off by default for a simpler micro_sam-style loss. 216 focal_weight: Weight of the focal mask loss when enabled. SAM2 uses 20; set to 1 217 to keep it on equal footing with the Dice loss. 218 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss in 219 CustomSAM2Loss. Off by default for a simpler micro_sam-style loss. 220 average_over_frames: Average the interactive loss over frames instead of summing, 221 so 2D and 3D batches share a scale when training on mixed 2D + 3D data. 222 """ 223 t_start = time.time() 224 225 device = get_device(device) 226 model = get_sam2_train_model( 227 model_type=model_type, 228 device=device, 229 checkpoint_path=checkpoint_path, 230 peft_kwargs=peft_kwargs, 231 prob_to_use_pt_input=prob_to_use_pt_input, 232 prob_to_use_box_input=prob_to_use_box_input, 233 num_frames_to_correct=num_frames_to_correct, 234 rand_frames_to_correct=rand_frames_to_correct, 235 prob_to_sample_from_gt=prob_to_sample_from_gt, 236 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 237 num_correction_pt_per_frame=num_correction_pt_per_frame, 238 num_init_cond_frames_for_train=num_init_cond_frames, 239 bidirectional=bidirectional, 240 ) 241 242 interactive_loss = CustomSAM2Loss( 243 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 244 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 245 ) 246 247 augmentor = VideoAugment() if augment else None 248 convert_inputs = ConvertToSam2VideoBatch( 249 max_num_objects=max_num_objects, largest_first=largest_first, augmentor=augmentor, 250 ) 251 252 optimizer = _build_optimizer(model, lr=lr, vision_lr=vision_lr, layer_decay=layer_decay) 253 scheduler = _build_scheduler(optimizer, **(scheduler_kwargs or {})) 254 255 trainer = Sam2Trainer( 256 name=name, 257 model=model, 258 train_loader=train_loader, 259 val_loader=val_loader, 260 optimizer=optimizer, 261 device=device, 262 lr_scheduler=scheduler, 263 logger=Sam2Logger, 264 log_image_interval=100, 265 compile_model=False, 266 early_stopping=early_stopping, 267 save_root=save_root, 268 convert_inputs=convert_inputs, 269 loss=interactive_loss, 270 clip_grad_norm=clip_grad_norm, 271 ) 272 273 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 274 if save_every_kth_epoch is not None: 275 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 276 fit_kwargs["overwrite_training"] = overwrite_training 277 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 278 trainer.fit(**fit_kwargs) 279 280 elapsed = time.time() - t_start 281 h, m, s = int(elapsed // 3600), int(elapsed % 3600 // 60), int(elapsed % 60) 282 print(f"Training took {elapsed:.1f}s (= {h:02}:{m:02}:{s:02})") 283 284 285def _train_sam2_rank( 286 rank: int, 287 local_rank: int, 288 name: str, 289 model_type: str, 290 input_path: str, 291 n_epochs: int, 292 n_iterations: Optional[int], 293 early_stopping: Optional[int], 294 max_num_objects: int, 295 checkpoint_path, 296 peft_kwargs, 297 lr: float, 298 save_root, 299 save_every_kth_epoch: Optional[int], 300 overwrite_training: bool, 301 load_from_checkpoint: Optional[Union[str, os.PathLike]], 302 prob_to_use_pt_input: float, 303 prob_to_use_box_input: float, 304 num_frames_to_correct: int, 305 rand_frames_to_correct: bool, 306 prob_to_sample_from_gt: float, 307 add_all_frames_to_correct_as_cond: bool, 308 num_correction_pt_per_frame: int, 309 num_init_cond_frames: int, 310 clip_grad_norm: Optional[float], 311 layer_decay: float, 312 scheduler_kwargs: Optional[Dict[str, Any]], 313 vision_lr: Optional[float], 314 batch_size: int, 315 batch_size_2d: int, 316 z_slices: List[int], 317 dataset_choice: str, 318 n_workers: int, 319 find_unused_parameters: bool, 320 largest_first: bool, 321 augment: bool, 322 bidirectional: bool = False, 323 use_focal_loss: bool = False, 324 focal_weight: float = 20.0, 325 use_object_score_loss: bool = False, 326 average_over_frames: bool = False, 327): 328 """Single-rank torchrun worker for train_sam2_multi_gpu.""" 329 from torch_em.multi_gpu_training import DDP 330 331 from micro_sam.v2.datasets.generalist_loader import _build_interactive_datasets, seed_worker 332 from micro_sam.v2.datasets.sampler import DistributedUniBatchSampler, _build_group_map 333 334 dist.init_process_group("nccl") 335 world_size = dist.get_world_size() 336 337 device = torch.device(f"cuda:{local_rank}") 338 torch.cuda.set_device(device) 339 340 # Each rank builds its own copy of the datasets. 341 train_ds, val_ds = _build_interactive_datasets(input_path, z_slices, dataset_choice) 342 343 batch_size_per_group = {2: batch_size_2d} if batch_size_2d != batch_size else None 344 345 train_sampler = DistributedUniBatchSampler( 346 group_per_index=_build_group_map(train_ds), 347 batch_size=batch_size, 348 batch_size_per_group=batch_size_per_group, 349 shuffle=True, 350 rank=rank, 351 world_size=world_size, 352 ) 353 val_sampler = DistributedUniBatchSampler( 354 group_per_index=_build_group_map(val_ds), 355 batch_size=batch_size, 356 batch_size_per_group=batch_size_per_group, 357 shuffle=False, 358 rank=rank, 359 world_size=world_size, 360 ) 361 362 train_loader = torch.utils.data.DataLoader( 363 train_ds, batch_sampler=train_sampler, num_workers=n_workers, 364 pin_memory=True, persistent_workers=n_workers > 0, 365 ) 366 train_loader.shuffle = True 367 # Non-persistent workers + a deterministic worker_init_fn re-seed each epoch, so the 368 # validation crops are identical across epochs (see seed_worker / Sam2Trainer._validate_impl). 369 val_loader = torch.utils.data.DataLoader( 370 val_ds, batch_sampler=val_sampler, num_workers=n_workers, 371 pin_memory=True, persistent_workers=False, worker_init_fn=seed_worker, 372 ) 373 val_loader.shuffle = False 374 375 model = get_sam2_train_model( 376 model_type=model_type, 377 device=device, 378 checkpoint_path=checkpoint_path, 379 peft_kwargs=peft_kwargs, 380 prob_to_use_pt_input=prob_to_use_pt_input, 381 prob_to_use_box_input=prob_to_use_box_input, 382 num_frames_to_correct=num_frames_to_correct, 383 rand_frames_to_correct=rand_frames_to_correct, 384 prob_to_sample_from_gt=prob_to_sample_from_gt, 385 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 386 num_correction_pt_per_frame=num_correction_pt_per_frame, 387 num_init_cond_frames_for_train=num_init_cond_frames, 388 bidirectional=bidirectional, 389 ) 390 ddp_model = DDP(model, device_ids=[local_rank], find_unused_parameters=find_unused_parameters) 391 392 interactive_loss = CustomSAM2Loss( 393 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 394 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 395 ) 396 397 augmentor = VideoAugment() if augment else None 398 convert_inputs = ConvertToSam2VideoBatch( 399 max_num_objects=max_num_objects, largest_first=largest_first, augmentor=augmentor, 400 ) 401 402 optimizer = _build_optimizer(model, lr=lr, vision_lr=vision_lr, layer_decay=layer_decay) 403 scheduler = _build_scheduler(optimizer, **(scheduler_kwargs or {})) 404 405 trainer = Sam2Trainer( 406 name=name, 407 model=ddp_model, 408 train_loader=train_loader, 409 val_loader=val_loader, 410 optimizer=optimizer, 411 device=device, 412 lr_scheduler=scheduler, 413 logger=Sam2Logger, 414 log_image_interval=100, 415 compile_model=False, 416 early_stopping=early_stopping, 417 save_root=save_root, 418 convert_inputs=convert_inputs, 419 loss=interactive_loss, 420 clip_grad_norm=clip_grad_norm, 421 rank=rank, 422 ) 423 424 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 425 if save_every_kth_epoch is not None: 426 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 427 fit_kwargs["overwrite_training"] = overwrite_training 428 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 429 _fit_and_shut_down(trainer, fit_kwargs) 430 431 432def _fit_and_shut_down(trainer, fit_kwargs): 433 """Run the training and tear the process group down only after a clean finish. 434 435 A rank that fails mid-collective must not destroy its communicator: the other ranks are still waiting in that 436 collective, the destroy blocks on them, and the traceback never prints before the NCCL timeout an hour later. 437 Instead the traceback is flushed and the process exits at once, so torchrun terminates the other ranks. 438 """ 439 try: 440 trainer.fit(**fit_kwargs) 441 except BaseException: 442 traceback.print_exc() 443 sys.stdout.flush() 444 sys.stderr.flush() 445 os._exit(1) 446 dist.destroy_process_group() 447 448 449def train_sam2_multi_gpu( 450 name: str, 451 model_type: str, 452 input_path: str, 453 batch_size: int = 2, 454 batch_size_2d: Optional[int] = None, 455 z_slices: Optional[List[int]] = None, 456 dataset_choice: str = "all", 457 n_workers: int = 16, 458 n_epochs: int = 100, 459 n_iterations: Optional[int] = None, 460 early_stopping: Optional[int] = 10, 461 max_num_objects: int = 20, 462 checkpoint_path=None, 463 peft_kwargs: Optional[Dict] = None, 464 lr: float = 1e-5, 465 vision_lr: Optional[float] = None, 466 save_root=None, 467 save_every_kth_epoch: Optional[int] = None, 468 overwrite_training: bool = True, 469 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 470 prob_to_use_pt_input: float = 0.5, 471 prob_to_use_box_input: float = 0.5, 472 num_frames_to_correct: int = 1, 473 rand_frames_to_correct: bool = True, 474 prob_to_sample_from_gt: float = 0.1, 475 add_all_frames_to_correct_as_cond: bool = True, 476 num_correction_pt_per_frame: int = 7, 477 num_init_cond_frames: int = 2, 478 clip_grad_norm: Optional[float] = None, 479 layer_decay: float = 1.0, 480 scheduler_kwargs: Optional[Dict[str, Any]] = None, 481 find_unused_parameters: bool = True, 482 largest_first: bool = False, 483 augment: bool = False, 484 bidirectional: bool = False, 485 use_focal_loss: bool = False, 486 focal_weight: float = 20.0, 487 use_object_score_loss: bool = False, 488 average_over_frames: bool = False, 489) -> None: 490 """Train SAM2 for interactive segmentation across multiple GPUs with DDP. 491 492 Must be launched via ``torchrun`` - one process per GPU, on one or more nodes. 493 Example (single node): ``torchrun --nproc_per_node=4 train_sam2.py`` 494 Example (multi-node): ``srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_sam2.py`` 495 496 Each rank reads its identity from the ``RANK``, ``LOCAL_RANK``, and 497 ``WORLD_SIZE`` environment variables set by torchrun and builds its own 498 dataset independently. 499 500 Args: 501 name: Checkpoint/log folder name. 502 model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 503 input_path: Root path to the generalist training data. 504 batch_size: Batch size per GPU for 3D groups. 505 batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size). 506 z_slices: Z-slice counts for 3D data groups (default [8]). 507 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 508 n_workers: DataLoader workers per GPU. 509 n_epochs: Training epochs. 510 n_iterations: Override n_epochs with a fixed iteration budget. 511 early_stopping: Stop after this many epochs without improvement. 512 max_num_objects: Max objects sampled per image/volume per step. 513 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 514 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 515 lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+). 516 vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. 517 SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr. 518 save_root: Root directory for checkpoints and logs. 519 save_every_kth_epoch: Save a checkpoint every k-th epoch. 520 overwrite_training: Overwrite an existing checkpoint at the same path. 521 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 522 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 523 the pretrained SAM2 weights to start from. 524 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 525 prob_to_use_box_input: Conditional P(box) given point/box mode. 526 num_frames_to_correct: Max frames per volume receiving correction clicks. 527 rand_frames_to_correct: Randomly sample how many frames to correct. 528 prob_to_sample_from_gt: P(correction click from GT vs error region). 529 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 530 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 531 finetuning uses 0.1. 532 find_unused_parameters: Passed to DistributedDataParallel. 533 """ 534 if z_slices is None: 535 z_slices = [8] 536 if batch_size_2d is None: 537 batch_size_2d = batch_size 538 539 if "RANK" not in os.environ: 540 raise RuntimeError( 541 "train_sam2_multi_gpu must be launched via torchrun, not called directly. " 542 "Example: torchrun --nproc_per_node=4 train_sam2.py" 543 ) 544 rank = int(os.environ["RANK"]) 545 local_rank = int(os.environ["LOCAL_RANK"]) 546 547 _train_sam2_rank( 548 rank=rank, 549 local_rank=local_rank, 550 name=name, 551 model_type=model_type, 552 input_path=input_path, 553 n_epochs=n_epochs, 554 n_iterations=n_iterations, 555 early_stopping=early_stopping, 556 max_num_objects=max_num_objects, 557 checkpoint_path=checkpoint_path, 558 peft_kwargs=peft_kwargs, 559 lr=lr, 560 save_root=save_root, 561 save_every_kth_epoch=save_every_kth_epoch, 562 overwrite_training=overwrite_training, 563 load_from_checkpoint=load_from_checkpoint, 564 prob_to_use_pt_input=prob_to_use_pt_input, 565 prob_to_use_box_input=prob_to_use_box_input, 566 num_frames_to_correct=num_frames_to_correct, 567 rand_frames_to_correct=rand_frames_to_correct, 568 prob_to_sample_from_gt=prob_to_sample_from_gt, 569 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 570 num_correction_pt_per_frame=num_correction_pt_per_frame, 571 num_init_cond_frames=num_init_cond_frames, 572 clip_grad_norm=clip_grad_norm, 573 layer_decay=layer_decay, 574 scheduler_kwargs=scheduler_kwargs, 575 vision_lr=vision_lr, 576 batch_size=batch_size, 577 batch_size_2d=batch_size_2d, 578 z_slices=z_slices, 579 dataset_choice=dataset_choice, 580 n_workers=n_workers, 581 find_unused_parameters=find_unused_parameters, 582 largest_first=largest_first, 583 augment=augment, 584 bidirectional=bidirectional, 585 use_focal_loss=use_focal_loss, 586 focal_weight=focal_weight, 587 use_object_score_loss=use_object_score_loss, 588 average_over_frames=average_over_frames, 589 ) 590 591 592def _get_start_sam2_model(model_type, device, checkpoint_path=None, peft_kwargs=None): 593 """Build the SAM2 image model to start a training from, with the PEFT layers of the training. 594 595 Args: 596 model_type: The SAM2 model, for example "hvit_t" or "hvit_t_cells". 597 device: The device to build the model on. 598 checkpoint_path: The checkpoint to start from, see `micro_sam.v2.training.util.read_start_weights`. 599 By default the weights of `model_type`. 600 peft_kwargs: The arguments for `PEFT_Sam2`, or None. A checkpoint with PEFT layers keeps its layers. 601 602 Returns: 603 The SAM2 model. Its 'peft_config' holds the PEFT settings, if the model has PEFT layers. 604 """ 605 from micro_sam.v2.util import get_sam2_model 606 from micro_sam.v2.training.util import check_start_peft 607 608 sam2_model = get_sam2_model( 609 model_type=model_type, input_type="images", device=device, checkpoint_path=checkpoint_path, 610 ) 611 start_peft_config = getattr(sam2_model, "peft_config", None) 612 check_start_peft(peft_kwargs, start_peft_config) 613 if peft_kwargs and start_peft_config is None: 614 from micro_sam.v2.models.peft_sam2 import PEFT_Sam2 615 from micro_sam.models.peft import serialize_peft_kwargs 616 617 sam2_model = PEFT_Sam2(sam2_model, **peft_kwargs).sam 618 sam2_model.peft_config = serialize_peft_kwargs(peft_kwargs) 619 return sam2_model 620 621 622def _init_start_decoder(model, model_type, checkpoint_path=None, skip_output_head=False): 623 """Initialize the decoder from the start checkpoint or the registered decoder, if one of them exists.""" 624 if checkpoint_path is not None or has_registered_decoder(model_type): 625 _init_sam2_decoder(model, model_type, skip_output_head=skip_output_head, checkpoint_path=checkpoint_path) 626 627 628def _build_unisam2_model( 629 model_type, device, peft_kwargs=None, output_channels=4, initial_features=32, checkpoint_path=None, 630): 631 """Build a UniSAM2 model and optionally apply PEFT to its encoder. 632 633 Registered models initialize both the encoder and decoder from their pretrained weights. 634 635 Args: 636 model_type: The SAM2 encoder variant, for example, "hvit_t". 637 device: The device to build the model on. 638 peft_kwargs: The arguments for `PEFT_Sam2`, or None. 639 output_channels: The number of UniSAM2 output channels. 640 initial_features: Width of the convolutional decoder. The features per level are 641 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 642 checkpoint_path: The checkpoint to start from. It replaces the weights of `model_type`. Its decoder, 643 or the decoder file next to it, initializes the decoder. Without a decoder, the decoder is random. 644 645 Returns: 646 The UniSAM2 model on the given device. 647 """ 648 from micro_sam.v2.models.util import UniSAM2 649 650 if peft_kwargs or checkpoint_path is not None: 651 sam2_model = _get_start_sam2_model(model_type, device, checkpoint_path, peft_kwargs) 652 model = UniSAM2( 653 encoder=sam2_model.image_encoder, output_channels=output_channels, 654 initial_features=initial_features, device=device, 655 ) 656 peft_config = getattr(sam2_model, "peft_config", None) 657 if peft_config is not None: 658 model.peft_config = peft_config 659 else: 660 model = UniSAM2( 661 encoder=model_type, output_channels=output_channels, initial_features=initial_features, device=device 662 ) 663 _init_start_decoder(model, model_type, checkpoint_path) 664 return model 665 666 667def train_automatic( 668 name: str, 669 model_type: str, 670 train_loader: DataLoader, 671 val_loader: DataLoader, 672 n_epochs: int = 100, 673 n_iterations: Optional[int] = None, 674 early_stopping: Optional[int] = None, 675 device: Optional[Union[str, torch.device]] = None, 676 lr: float = 1e-5, 677 save_root: Optional[Union[str, os.PathLike]] = None, 678 save_every_kth_epoch: Optional[int] = None, 679 overwrite_training: bool = True, 680 peft_kwargs: Optional[Dict] = None, 681 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 682 initial_features: int = 32, 683 with_boundaries: bool = True, 684 boundary_dice_weight: float = 1.0, 685 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 686) -> None: 687 """Train UniSAM2 for automatic instance segmentation with directed distance targets. 688 689 Trains the UNETR3D-based UniSAM2 model using 690 :class:`~micro_sam.v2.loss.directed_distance_based.DirectedDistanceLoss` on 691 combined 2D + 3D data. Pass a loader built by 692 :func:`~micro_sam.v2.datasets.generalist_loader.get_dataloaders` with 693 ``label_trafo=GeodesicHybridDistanceTransform`` (the default). Build the loaders for your own 694 data with `micro_sam.v2.training.loaders.default_sam2_loader` and ``mode="automatic"``. 695 696 Args: 697 name: Checkpoint / log folder name. 698 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 699 "hvit_t_cells". A registered model initializes both the encoder and the decoder. 700 train_loader: DataLoader yielding (x, y) tuples with directed-distance targets. 701 val_loader: Same format, used for validation. 702 n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set. 703 n_iterations: If set, train for this many iterations instead of epochs. 704 early_stopping: Stop after this many epochs without improvement (None = off). 705 device: Training device. Auto-selects if None. 706 lr: Learning rate. 707 save_root: Root directory for checkpoints and logs. 708 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 709 overwrite_training: Overwrite an existing checkpoint at the same path. 710 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder during decoder training. 711 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 712 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 713 the pretrained SAM2 weights to start from. 714 initial_features: Width of the convolutional decoder. The features per level are 715 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 716 with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. 717 By default True, which matches the decoders of the registered models. 718 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 719 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 720 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 721 decoder. Without a decoder, the decoder starts from random weights. 722 """ 723 import torch_em 724 725 device = get_device(device) 726 model = _build_unisam2_model( 727 model_type, device, peft_kwargs=peft_kwargs, output_channels=4 + int(with_boundaries), 728 initial_features=initial_features, checkpoint_path=checkpoint_path, 729 ) 730 731 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 732 loss = DirectedDistanceLoss( 733 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 734 ) 735 736 trainer = torch_em.default_segmentation_trainer( 737 name=name, 738 model=model, 739 train_loader=train_loader, 740 val_loader=val_loader, 741 learning_rate=lr, 742 loss=loss, 743 metric=loss, 744 logger=UniSAM2Logger, 745 log_image_interval=50, 746 save_root=save_root, 747 compile_model=False, 748 scheduler_kwargs=scheduler_kwargs, 749 optimizer_kwargs={"weight_decay": 0.1}, 750 # The hardware decides the precision. SAM2 trains in bfloat16 only. 751 mixed_precision=training_autocast_dtype(device) is not None, 752 mixed_precision_dtype="bfloat16", 753 device=device, 754 early_stopping=early_stopping, 755 trainer_class=UniSAM2Trainer, 756 ) 757 758 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 759 fit_kwargs["overwrite_training"] = overwrite_training 760 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 761 if save_every_kth_epoch is not None: 762 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 763 trainer.fit(**fit_kwargs) 764 765 766def _train_automatic_rank( 767 rank: int, 768 local_rank: int, 769 name: str, 770 model_type: str, 771 input_path: str, 772 n_epochs: int, 773 n_iterations: Optional[int], 774 early_stopping: Optional[int], 775 lr: float, 776 save_root, 777 save_every_kth_epoch: Optional[int], 778 overwrite_training: bool, 779 load_from_checkpoint: Optional[Union[str, os.PathLike]], 780 batch_size: int, 781 batch_size_2d: int, 782 z_slices: List[int], 783 dataset_choice: str, 784 n_workers: int, 785 find_unused_parameters: bool, 786 initial_features: int, 787 with_boundaries: bool, 788 boundary_dice_weight: float, 789 peft_kwargs=None, 790 checkpoint_path=None, 791): 792 """Single-rank torchrun worker for train_automatic_multi_gpu.""" 793 import torch_em 794 from torch_em.multi_gpu_training import DDP 795 796 from micro_sam.v2.datasets.generalist_loader import _build_automatic_datasets, seed_worker 797 from micro_sam.v2.datasets.sampler import DistributedUniBatchSampler, _build_group_map 798 799 dist.init_process_group("nccl") 800 world_size = dist.get_world_size() 801 802 device = torch.device(f"cuda:{local_rank}") 803 torch.cuda.set_device(device) 804 805 train_ds, val_ds = _build_automatic_datasets(input_path, z_slices, dataset_choice, with_boundaries=with_boundaries) 806 807 batch_size_per_group = {2: batch_size_2d} if batch_size_2d != batch_size else None 808 809 train_sampler = DistributedUniBatchSampler( 810 group_per_index=_build_group_map(train_ds), 811 batch_size=batch_size, 812 batch_size_per_group=batch_size_per_group, 813 shuffle=True, 814 rank=rank, 815 world_size=world_size, 816 ) 817 val_sampler = DistributedUniBatchSampler( 818 group_per_index=_build_group_map(val_ds), 819 batch_size=batch_size, 820 batch_size_per_group=batch_size_per_group, 821 shuffle=False, 822 rank=rank, 823 world_size=world_size, 824 ) 825 826 train_loader = torch.utils.data.DataLoader( 827 train_ds, batch_sampler=train_sampler, num_workers=n_workers, 828 pin_memory=True, persistent_workers=n_workers > 0, 829 ) 830 train_loader.shuffle = True 831 # Deterministic validation crops, matching the interactive path: the underlying datasets 832 # draw random crops per __getitem__, so without this the metric changes every epoch. 833 val_loader = torch.utils.data.DataLoader( 834 val_ds, batch_sampler=val_sampler, num_workers=n_workers, 835 pin_memory=True, persistent_workers=False, worker_init_fn=seed_worker, 836 ) 837 val_loader.shuffle = False 838 839 model = _build_unisam2_model( 840 model_type, device, peft_kwargs=peft_kwargs, output_channels=4 + int(with_boundaries), 841 initial_features=initial_features, checkpoint_path=checkpoint_path, 842 ) 843 ddp_model = DDP(model, device_ids=[local_rank], find_unused_parameters=find_unused_parameters) 844 845 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 846 loss = DirectedDistanceLoss( 847 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 848 ) 849 850 trainer = torch_em.default_segmentation_trainer( 851 name=name, 852 model=ddp_model, 853 train_loader=train_loader, 854 val_loader=val_loader, 855 learning_rate=lr, 856 loss=loss, 857 metric=loss, 858 logger=UniSAM2Logger, 859 log_image_interval=50, 860 save_root=save_root, 861 compile_model=False, 862 scheduler_kwargs=scheduler_kwargs, 863 optimizer_kwargs={"weight_decay": 0.1}, 864 # The hardware decides the precision. SAM2 trains in bfloat16 only. 865 mixed_precision=training_autocast_dtype(device) is not None, 866 mixed_precision_dtype="bfloat16", 867 device=device, 868 early_stopping=early_stopping, 869 trainer_class=UniSAM2Trainer, 870 rank=rank, 871 ) 872 873 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 874 fit_kwargs["overwrite_training"] = overwrite_training 875 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 876 if save_every_kth_epoch is not None: 877 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 878 _fit_and_shut_down(trainer, fit_kwargs) 879 880 881def train_automatic_multi_gpu( 882 name: str, 883 model_type: str, 884 input_path: str, 885 batch_size: int = 2, 886 batch_size_2d: Optional[int] = None, 887 z_slices: Optional[List[int]] = None, 888 dataset_choice: str = "all", 889 n_workers: int = 16, 890 n_epochs: int = 100, 891 n_iterations: Optional[int] = None, 892 early_stopping: Optional[int] = None, 893 lr: float = 1e-5, 894 save_root=None, 895 save_every_kth_epoch: Optional[int] = None, 896 overwrite_training: bool = True, 897 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 898 find_unused_parameters: bool = True, 899 peft_kwargs: Optional[Dict] = None, 900 initial_features: int = 32, 901 with_boundaries: bool = True, 902 boundary_dice_weight: float = 1.0, 903 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 904) -> None: 905 """Train UniSAM2 for automatic segmentation across multiple GPUs with DDP. 906 907 Mirrors :func:`train_automatic` but must be launched via ``torchrun`` - one 908 process per GPU. Takes ``input_path`` instead of pre-built dataloaders because 909 each rank must build its own dataset objects. 910 911 Args: 912 name: Checkpoint / log folder name. 913 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 914 "hvit_t_cells". A registered model initializes both the encoder and the decoder. 915 input_path: Root path to the generalist training data. 916 batch_size: Batch size per GPU for 3D groups. 917 batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size). 918 z_slices: Z-slice counts for 3D data groups (default [8]). 919 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 920 n_workers: DataLoader workers per GPU. 921 n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set. 922 n_iterations: If set, train for this many iterations instead of epochs. 923 early_stopping: Stop after this many epochs without improvement. 924 lr: Learning rate. 925 save_root: Root directory for checkpoints and logs. 926 save_every_kth_epoch: Save a checkpoint every k-th epoch. 927 overwrite_training: Overwrite an existing checkpoint at the same path. 928 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 929 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 930 the pretrained SAM2 weights to start from. 931 find_unused_parameters: Passed to DistributedDataParallel. 932 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 933 initial_features: Width of the convolutional decoder. The features per level are 934 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 935 with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. 936 By default True, which matches the decoders of the registered models. 937 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 938 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 939 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 940 decoder. Without a decoder, the decoder starts from random weights. 941 """ 942 if z_slices is None: 943 z_slices = [8] 944 if batch_size_2d is None: 945 batch_size_2d = batch_size 946 947 if "RANK" not in os.environ: 948 raise RuntimeError( 949 "train_automatic_multi_gpu must be launched via torchrun, not called directly. " 950 "Example: torchrun --nproc_per_node=4 train_automatic.py" 951 ) 952 rank = int(os.environ["RANK"]) 953 local_rank = int(os.environ["LOCAL_RANK"]) 954 955 _train_automatic_rank( 956 rank=rank, 957 local_rank=local_rank, 958 name=name, 959 model_type=model_type, 960 input_path=input_path, 961 n_epochs=n_epochs, 962 n_iterations=n_iterations, 963 early_stopping=early_stopping, 964 lr=lr, 965 save_root=save_root, 966 save_every_kth_epoch=save_every_kth_epoch, 967 overwrite_training=overwrite_training, 968 load_from_checkpoint=load_from_checkpoint, 969 batch_size=batch_size, 970 batch_size_2d=batch_size_2d, 971 z_slices=z_slices, 972 dataset_choice=dataset_choice, 973 n_workers=n_workers, 974 find_unused_parameters=find_unused_parameters, 975 initial_features=initial_features, 976 with_boundaries=with_boundaries, 977 boundary_dice_weight=boundary_dice_weight, 978 peft_kwargs=peft_kwargs, 979 checkpoint_path=checkpoint_path, 980 ) 981 982 983# The parts of the joint model that torch.compile can compile. 984COMPILE_COMPONENTS = ("encoder", "decoder", "loss") 985 986# The process-group timeout with torch.compile. Each rank compiles the 2D and the 3D graph at its first 987# iteration with that shape, and the other ranks wait in their collectives until it is done. 988COMPILE_PG_TIMEOUT = timedelta(minutes=60) 989 990 991def _check_compile(compile): 992 if isinstance(compile, str): 993 compile = [compile] 994 compile = [] if compile is None else list(compile) 995 unknown = set(compile) - set(COMPILE_COMPONENTS) 996 if unknown: 997 raise ValueError( 998 f"The compile components {sorted(unknown)} are unknown. Pass a subset of {COMPILE_COMPONENTS}." 999 ) 1000 return compile 1001 1002 1003def _compile_threads_per_rank(): 1004 """Return the number of Inductor compile workers per rank. 1005 1006 The ranks on one node share the CPUs of the job. With the default of one worker per core, the 1007 ranks compete for the CPUs and the first iterations take many minutes. 1008 """ 1009 n_cpus = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() 1010 local_ranks = int(os.environ.get("LOCAL_WORLD_SIZE", "1")) 1011 # The workers keep their memory for the whole run; 16 compile the few shapes of a run within minutes. 1012 return max(1, min(16, n_cpus // local_ranks)) 1013 1014 1015def _configure_joint_speed(sam2_model, unetr, compile): 1016 """Apply the backend speed settings of the joint training functions.""" 1017 # The convolution shapes are fixed per data group. cuDNN autotuning finds a much faster kernel for 1018 # the mask downsampler of the memory encoder than the heuristic choice. 1019 torch.backends.cudnn.benchmark = True 1020 torch.set_float32_matmul_precision("high") 1021 if "encoder" in compile or "decoder" in compile: 1022 # The decoder blocks share one class, so torch.compile stores one specialization per block width 1023 # and per 2D/3D shape. With the default limit of 8, the other blocks run in eager mode. 1024 torch._dynamo.config.cache_size_limit = max(torch._dynamo.config.cache_size_limit, 64) 1025 torch._inductor.config.compile_threads = _compile_threads_per_rank() 1026 if "encoder" in compile: 1027 # The in-place compile keeps the module and its state_dict keys. The SAM2 forward and the UNETR 1028 # encoder adapter both hold this module. 1029 sam2_model.image_encoder.compile(dynamic=False) 1030 if "decoder" in compile: 1031 # Compile the decoder blocks one by one, so the encode and decode methods stay plain Python. 1032 for name, module in unetr.named_children(): 1033 if name != "encoder": 1034 module.compile(dynamic=False) 1035 1036 1037def _configure_semantic_speed(model, compile): 1038 """Apply the backend speed settings of the joint training functions to a SemanticSAM2 model. 1039 1040 Args: 1041 model: The SemanticSAM2 model. 1042 compile: The parts to compile, a subset of "encoder" and "decoder". 1043 """ 1044 torch.backends.cudnn.benchmark = True 1045 torch.set_float32_matmul_precision("high") 1046 if not compile: 1047 return 1048 # See '_configure_joint_speed': one specialization per decoder block width, and one worker per core. 1049 torch._dynamo.config.cache_size_limit = max(torch._dynamo.config.cache_size_limit, 64) 1050 torch._inductor.config.compile_threads = _compile_threads_per_rank() 1051 if "encoder" in compile: 1052 # The in-place compile keeps the module and its state_dict keys. 1053 model.encoder.inner.compile(dynamic=False) 1054 if "decoder" in compile: 1055 for name, module in model.named_children(): 1056 if name != "encoder": 1057 module.compile(dynamic=False) 1058 1059 1060def _init_sam2_decoder(model, model_type, skip_output_head=False, checkpoint_path=None): 1061 """Initialize the decoder from a checkpoint or from the registered UniSAM2 weights. 1062 1063 Args: 1064 model: The UniSAM2 or SemanticSAM2 model. 1065 model_type: A finetuned model with a registered decoder, for example, "hvit_l_cells". 1066 Not used if `checkpoint_path` is given. 1067 skip_output_head: Whether to keep the output head for semantic segmentation. 1068 checkpoint_path: The checkpoint to start from. The function uses its decoder, or the decoder file next to it. 1069 If there is no decoder, the decoder keeps its random weights. 1070 """ 1071 from micro_sam.util import load_checkpoint 1072 from micro_sam.v2.models.util import read_unisam2_state 1073 from micro_sam.v2.instance_segmentation import find_decoder_checkpoint 1074 from micro_sam.v2.util import FINETUNED_MODELS, has_registered_decoder, _download_finetuned_sam2_model 1075 1076 if checkpoint_path is not None: 1077 source = checkpoint_path 1078 state = read_unisam2_state(load_checkpoint(checkpoint_path)) 1079 decoder_path = find_decoder_checkpoint(checkpoint_path) if state is None else None 1080 if decoder_path is not None: 1081 source = decoder_path 1082 state = read_unisam2_state(load_checkpoint(decoder_path)) 1083 if state is None: 1084 print(f"'{checkpoint_path}' has no decoder, so the decoder starts from random weights.") 1085 return 1086 else: 1087 if model_type not in FINETUNED_MODELS or not has_registered_decoder(model_type): 1088 raise ValueError(f"'{model_type}' has no registered decoder to initialize the decoder from.") 1089 _, _, decoder_path = _download_finetuned_sam2_model(model_type) 1090 source = model_type 1091 state = read_unisam2_state(load_checkpoint(decoder_path)) 1092 if state is None: 1093 raise ValueError(f"The registered decoder of '{model_type}' holds no decoder weights.") 1094 1095 head_prefixes = ("encoder.", "out_conv.") if skip_output_head else ("encoder.",) 1096 decoder_state = {k: v for k, v in state.items() if not k.startswith(head_prefixes)} 1097 1098 model_state = model.state_dict() 1099 mismatched = [k for k, v in decoder_state.items() if k in model_state and model_state[k].shape != v.shape] 1100 if mismatched: 1101 settings = "'initial_features'" if skip_output_head else "'initial_features' and 'with_boundaries'" 1102 raise ValueError( 1103 f"The decoder of '{source}' does not match the model, for example at '{mismatched[0]}'. " 1104 f"Match {settings} to this decoder." 1105 ) 1106 1107 missing, unexpected = model.load_state_dict(decoder_state, strict=False) 1108 missing = [k for k in missing if not k.startswith(head_prefixes)] 1109 if missing or unexpected: 1110 raise RuntimeError(f"Could not initialize the decoder. Missing keys: {missing}, unexpected keys: {unexpected}.") 1111 1112 1113def _build_semantic_sam2_model( 1114 model_type, device, num_classes, peft_kwargs=None, initial_features=32, checkpoint_path=None, 1115): 1116 """Build a SemanticSAM2 model and optionally apply PEFT to its encoder. 1117 1118 The encoder starts from the weights of `model_type`. For a model with a registered decoder, for example 1119 "hvit_t_cells", the decoder starts from it too, and only the output head for the classes is new. 1120 1121 Args: 1122 model_type: The SAM2 encoder variant, for example, "hvit_t". 1123 device: The device to build the model on. 1124 num_classes: The number of semantic classes, the background class included. 1125 peft_kwargs: The arguments for `PEFT_Sam2`, or None. 1126 initial_features: Width of the convolutional decoder. The features per level are 1127 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1128 checkpoint_path: The checkpoint to start from. It replaces the weights of `model_type`. Its decoder, 1129 or the decoder file next to it, initializes the decoder, but not the output head. 1130 1131 Returns: 1132 The SemanticSAM2 model on the given device. 1133 """ 1134 from micro_sam.v2.models.util import SemanticSAM2 1135 1136 if peft_kwargs or checkpoint_path is not None: 1137 sam2_model = _get_start_sam2_model(model_type, device, checkpoint_path, peft_kwargs) 1138 model = SemanticSAM2( 1139 encoder=sam2_model.image_encoder, num_classes=num_classes, 1140 initial_features=initial_features, device=device, 1141 ) 1142 peft_config = getattr(sam2_model, "peft_config", None) 1143 if peft_config is not None: 1144 model.peft_config = peft_config 1145 else: 1146 model = SemanticSAM2( 1147 encoder=model_type, num_classes=num_classes, initial_features=initial_features, device=device 1148 ) 1149 1150 _init_start_decoder(model, model_type, checkpoint_path, skip_output_head=True) 1151 return model 1152 1153 1154def train_semantic( 1155 name: str, 1156 model_type: str, 1157 train_loader: DataLoader, 1158 val_loader: DataLoader, 1159 num_classes: int = 3, 1160 n_epochs: int = 100, 1161 n_iterations: Optional[int] = None, 1162 early_stopping: Optional[int] = None, 1163 device: Optional[Union[str, torch.device]] = None, 1164 lr: float = 1e-5, 1165 save_root: Optional[Union[str, os.PathLike]] = None, 1166 save_every_kth_epoch: Optional[int] = None, 1167 overwrite_training: bool = True, 1168 peft_kwargs: Optional[Dict] = None, 1169 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1170 initial_features: int = 32, 1171 dice_weight: float = 0.5, 1172 mixed_precision: Optional[bool] = None, 1173 compile: Optional[List[str]] = None, 1174 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 1175) -> None: 1176 """Train SemanticSAM2 for semantic segmentation on 2d and 3d data. 1177 1178 Trains the UNETR3D-based SemanticSAM2 model with 1179 :class:`~micro_sam.v2.loss.semantic_loss.CustomCombinedLoss`, a weighted sum of a 1180 multi-class dice loss and a cross entropy loss. The targets are class ids, one per voxel; 1181 :func:`~micro_sam.v2.transforms.labels.semantic_labels` derives the three class layout of 1182 background, object boundary and object interior from an instance segmentation. 1183 1184 With 'num_classes=1' the model predicts a single foreground channel instead, trained with a 1185 weighted sum of a dice loss and a binary cross entropy loss on the sigmoid of the logits. 1186 The targets are then binary foreground masks. 1187 1188 Build the loaders for your own data with `micro_sam.v2.training.loaders.default_sam2_loader` 1189 and ``mode="semantic"``. 1190 1191 The encoder starts from the weights of `model_type`. For a model with a registered decoder, for example 1192 "hvit_t_cells", the decoder starts from it too, and only the output head for the classes is new. 1193 1194 Args: 1195 name: Checkpoint / log folder name. 1196 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 1197 "hvit_t_cells". 1198 train_loader: DataLoader yielding (x, y) tuples, with x of shape (B, 3, Z, Y, X) and the 1199 class ids in y of shape (B, 1, Z, Y, X). 2d data carries a singleton z axis. 1200 val_loader: Same format, used for validation. 1201 num_classes: The number of semantic classes, the background class included. 1202 One selects binary foreground segmentation with the dice and binary cross entropy loss. 1203 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1204 n_iterations: If set, train for this many iterations instead of epochs. 1205 early_stopping: Stop after this many epochs without improvement (None = off). 1206 device: Training device. Auto-selects if None. 1207 lr: Learning rate. 1208 save_root: Root directory for checkpoints and logs. 1209 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 1210 overwrite_training: Overwrite an existing checkpoint at the same path. 1211 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder during decoder training. 1212 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1213 scheduler, epoch and iteration. 1214 initial_features: Width of the convolutional decoder. The features per level are 1215 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1216 dice_weight: The weight of the dice loss in the combined loss. One selects dice only. 1217 Zero selects cross entropy only. 1218 mixed_precision: Whether to train with bfloat16 mixed precision. The weights and the optimizer state 1219 stay in float32. The hardware decides if None. 1220 compile: The parts to compile with ``torch.compile``, a subset of "encoder" and "decoder". 1221 Set 'TORCHINDUCTOR_CACHE_DIR' to a node-local folder: a cache on a shared filesystem blocks on its locks. 1222 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 1223 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 1224 decoder, but not the output head. 1225 """ 1226 import torch_em 1227 1228 device = get_device(device) 1229 model = _build_semantic_sam2_model( 1230 model_type, device, num_classes=num_classes, peft_kwargs=peft_kwargs, 1231 initial_features=initial_features, checkpoint_path=checkpoint_path, 1232 ) 1233 compile = _check_compile(compile) 1234 if "loss" in compile: 1235 raise ValueError("The semantic training compiles the 'encoder' and the 'decoder' only.") 1236 _configure_semantic_speed(model, compile) 1237 1238 if num_classes == 1: 1239 from torch_em.loss.dice import BCEDiceLossWithLogits, DiceLossWithLogits 1240 1241 if not 0.0 <= dice_weight <= 1.0: 1242 raise ValueError(f"The dice weight is '{dice_weight}'. It must lie between zero and one.") 1243 loss = BCEDiceLossWithLogits(alpha=dice_weight, beta=1.0 - dice_weight) 1244 metric = DiceLossWithLogits() 1245 else: 1246 loss = CustomCombinedLoss(num_classes=num_classes, dice_weight=dice_weight) 1247 metric = CustomDiceLoss(num_classes=num_classes) 1248 1249 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 1250 1251 trainer = torch_em.default_segmentation_trainer( 1252 name=name, 1253 model=model, 1254 train_loader=train_loader, 1255 val_loader=val_loader, 1256 learning_rate=lr, 1257 loss=loss, 1258 metric=metric, 1259 logger=UniSAM2Logger, 1260 log_image_interval=50, 1261 save_root=save_root, 1262 compile_model=False, 1263 scheduler_kwargs=scheduler_kwargs, 1264 optimizer_kwargs={"weight_decay": 0.1}, 1265 # The hardware decides the precision by default. SAM2 trains in bfloat16 only. 1266 mixed_precision=(training_autocast_dtype(device) is not None) if mixed_precision is None else mixed_precision, 1267 mixed_precision_dtype="bfloat16", 1268 device=device, 1269 early_stopping=early_stopping, 1270 trainer_class=UniSAM2Trainer, 1271 ) 1272 1273 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 1274 fit_kwargs["overwrite_training"] = overwrite_training 1275 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 1276 if save_every_kth_epoch is not None: 1277 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 1278 trainer.fit(**fit_kwargs) 1279 1280 1281def train_joint_sam2( 1282 name: str, 1283 model_type: str, 1284 input_path: Optional[str] = None, 1285 train_loader: Optional[DataLoader] = None, 1286 val_loader: Optional[DataLoader] = None, 1287 batch_size: int = 2, 1288 batch_size_2d: Optional[int] = None, 1289 z_slices: Optional[List[int]] = None, 1290 dataset_choice: str = "all", 1291 n_workers: int = 16, 1292 n_epochs: int = 100, 1293 n_iterations: Optional[int] = None, 1294 early_stopping: Optional[int] = None, 1295 max_num_objects: int = 20, 1296 checkpoint_path=None, 1297 freeze: Optional[List[str]] = None, 1298 peft_kwargs: Optional[Dict] = None, 1299 device: Optional[Union[str, torch.device]] = None, 1300 lr: float = 1e-5, 1301 save_root: Optional[Union[str, os.PathLike]] = None, 1302 scheduler_kwargs: Optional[Dict[str, Any]] = None, 1303 save_every_kth_epoch: Optional[int] = None, 1304 overwrite_training: bool = True, 1305 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1306 prob_to_use_pt_input: float = 0.5, 1307 prob_to_use_box_input: float = 0.5, 1308 num_frames_to_correct: int = 1, 1309 rand_frames_to_correct: bool = True, 1310 prob_to_sample_from_gt: float = 0.1, 1311 add_all_frames_to_correct_as_cond: bool = True, 1312 num_correction_pt_per_frame: int = 7, 1313 num_init_cond_frames: int = 2, 1314 clip_grad_norm: Optional[float] = None, 1315 largest_first: bool = False, 1316 bidirectional: bool = False, 1317 use_focal_loss: bool = False, 1318 focal_weight: float = 20.0, 1319 use_object_score_loss: bool = False, 1320 average_over_frames: bool = False, 1321 automatic_metric_weight: float = 0.25, 1322 initial_features: int = 32, 1323 distance_type: str = "geodesic", 1324 with_boundaries: bool = True, 1325 boundary_dice_weight: float = 1.0, 1326 label_trafo_threads: int = 1, 1327 compile: Optional[List[str]] = None, 1328) -> None: 1329 """Train SAM2Train and UniSAM2 jointly with a shared image encoder (single GPU). 1330 1331 Builds both the interactive (SAM2Train) and automatic (UniSAM2) models from 1332 ``model_type``, wires the shared image encoder, then interleaves the two 1333 losses in each training step. Both branches train on the same patches: the labels 1334 hold the instance ids for the interactive branch, followed by the targets of the 1335 automatic branch. 1336 1337 Train either on the generalist training data, with `input_path`, or on your own data, 1338 with `train_loader` and `val_loader` from 1339 `micro_sam.v2.training.loaders.default_sam2_loader` with ``mode="joint"``. 1340 1341 Args: 1342 name: Checkpoint / log folder name. 1343 model_type: SAM2 model to start from: a base backbone ("hvit_t", "hvit_s", "hvit_b", "hvit_l") 1344 or a finetuned model, e.g. "hvit_t_cells", whose decoder initializes the automatic branch. 1345 input_path: Root path to the generalist training data. Pass either this or the loaders. 1346 train_loader: The training loader for your own data. Pass it together with `val_loader`. 1347 val_loader: The validation loader for your own data. 1348 batch_size: Batch size for 3D groups (both branches). Only used with `input_path`. 1349 batch_size_2d: Batch size for 2D groups (both branches). Defaults to ``batch_size``. Only used with 1350 `input_path`. 1351 z_slices: Z-slice counts for 3D groups (default [8]). Only used with `input_path`. 1352 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. Only used with `input_path`. 1353 n_workers: DataLoader workers. Only used with `input_path`. 1354 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1355 n_iterations: If set, train for this many iterations instead of epochs. 1356 early_stopping: Stop after this many epochs without improvement (None = off). 1357 max_num_objects: Max objects per interactive step. 1358 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 1359 freeze: Component name prefixes to freeze (e.g. ["image_encoder"]). 1360 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 1361 device: Training device. Auto-selects if None. 1362 lr: Learning rate. 1363 save_root: Root directory for checkpoints and logs. 1364 scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10. 1365 save_every_kth_epoch: Save a checkpoint every k-th epoch. 1366 overwrite_training: Overwrite an existing checkpoint at the same path. 1367 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1368 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 1369 the pretrained SAM2 weights to start from. 1370 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 1371 prob_to_use_box_input: Conditional P(box) given point/box mode. 1372 num_frames_to_correct: Max frames per volume receiving correction clicks. 1373 rand_frames_to_correct: Randomly sample how many frames to correct. 1374 prob_to_sample_from_gt: P(correction click from GT vs error region). 1375 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 1376 num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7). 1377 num_init_cond_frames: Initial conditioning frames before the first correction round. 1378 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 1379 finetuning uses 0.1. 1380 bidirectional: Bidirectional propagation during training for 3D z-stacks. 1381 use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss. 1382 focal_weight: Weight of the focal mask loss when enabled. 1383 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss. 1384 average_over_frames: Average the interactive loss over frames instead of summing. 1385 automatic_metric_weight: Weight of the automatic metric in the combined validation 1386 metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, 1387 which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive 1388 Dice metric. Set to 0 to select purely on the interactive task. 1389 initial_features: Width of the convolutional decoder. The features per level are 1390 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1391 distance_type: Directed distance target for the automatic branch. "geodesic" uses the 1392 geodesic hybrid field around each object's center, "directed" the euclidean vector 1393 to the nearest boundary. Only used with `input_path`: `default_sam2_loader` uses "geodesic". 1394 with_boundaries: The flag to add a fifth automatic output for the full object-boundary target. 1395 By default True, which matches the decoders of the registered models. 1396 It must match the targets of the loaders, and the decoder of a finetuned `model_type`. 1397 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 1398 label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel 1399 in the distance transform. Only pays off when the node has more cores than loader workers. 1400 Only used with `input_path`. 1401 compile: The parts to compile with ``torch.compile``. "encoder" is the shared image encoder, 1402 "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels 1403 of the interactive loss. The default compiles nothing. 1404 """ 1405 from micro_sam.v2.datasets.generalist_loader import _build_joint_datasets, _prepare_data_loader 1406 from micro_sam.v2.models.util import UniSAM2 1407 1408 have_loaders = train_loader is not None or val_loader is not None 1409 if (input_path is not None) == have_loaders: 1410 raise ValueError("Pass either 'input_path' or both 'train_loader' and 'val_loader'.") 1411 if have_loaders and (train_loader is None or val_loader is None): 1412 raise ValueError("Pass both 'train_loader' and 'val_loader'.") 1413 1414 device = get_device(device) 1415 1416 if input_path is not None: 1417 if z_slices is None: 1418 z_slices = [8] 1419 if batch_size_2d is None: 1420 batch_size_2d = batch_size 1421 train_ds, val_ds = _build_joint_datasets( 1422 input_path, z_slices, dataset_choice, distance_type, 1423 with_boundaries=with_boundaries, label_trafo_threads=label_trafo_threads, 1424 ) 1425 bpg = {2: batch_size_2d} if batch_size_2d != batch_size else None 1426 train_loader = _prepare_data_loader( 1427 train_ds, batch_size=batch_size, shuffle=True, 1428 batch_size_per_group=bpg, num_workers=n_workers, 1429 ) 1430 val_loader = _prepare_data_loader( 1431 val_ds, batch_size=batch_size, shuffle=False, 1432 batch_size_per_group=bpg, num_workers=n_workers, deterministic=True, 1433 ) 1434 1435 sam2_model = get_sam2_train_model( 1436 model_type=model_type, device=device, 1437 checkpoint_path=checkpoint_path, freeze=freeze, peft_kwargs=peft_kwargs, 1438 prob_to_use_pt_input=prob_to_use_pt_input, 1439 prob_to_use_box_input=prob_to_use_box_input, 1440 num_frames_to_correct=num_frames_to_correct, 1441 rand_frames_to_correct=rand_frames_to_correct, 1442 prob_to_sample_from_gt=prob_to_sample_from_gt, 1443 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 1444 num_correction_pt_per_frame=num_correction_pt_per_frame, 1445 num_init_cond_frames_for_train=num_init_cond_frames, 1446 bidirectional=bidirectional, 1447 ) 1448 unetr = UniSAM2( 1449 encoder=sam2_model.image_encoder, output_channels=4 + int(with_boundaries), 1450 initial_features=initial_features, device=device, 1451 perform_range_checks=False, # The trainer checks the input range once. 1452 ) 1453 _init_start_decoder(unetr, model_type, checkpoint_path) 1454 compile = _check_compile(compile) 1455 _configure_joint_speed(sam2_model, unetr, compile) 1456 1457 interactive_loss = CustomSAM2Loss( 1458 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 1459 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 1460 compile_kernels="loss" in compile, 1461 ) 1462 automatic_loss = DirectedDistanceLoss( 1463 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 1464 ) 1465 convert_inputs = ConvertToSam2VideoBatch(max_num_objects=max_num_objects, largest_first=largest_first) 1466 1467 if scheduler_kwargs is None: 1468 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 1469 sam2_params = list(sam2_model.parameters()) 1470 unetr_decoder_params = [p for n, p in unetr.named_parameters() if not n.startswith("encoder")] 1471 # The fused AdamW kernel exists for CUDA only. 1472 optimizer = torch.optim.AdamW( 1473 sam2_params + unetr_decoder_params, lr=lr, fused=torch.device(device).type == "cuda" 1474 ) 1475 scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, **scheduler_kwargs) 1476 1477 trainer = JointSam2Trainer( 1478 name=name, 1479 model=sam2_model, 1480 train_loader=train_loader, 1481 val_loader=val_loader, 1482 optimizer=optimizer, 1483 device=device, 1484 lr_scheduler=scheduler, 1485 logger=JointSam2Logger, 1486 log_image_interval=100, 1487 compile_model=False, 1488 early_stopping=early_stopping, 1489 save_root=save_root, 1490 unetr=unetr, 1491 convert_inputs=convert_inputs, 1492 interactive_loss=interactive_loss, 1493 automatic_loss=automatic_loss, 1494 automatic_metric_weight=automatic_metric_weight, 1495 clip_grad_norm=clip_grad_norm, 1496 ) 1497 1498 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 1499 fit_kwargs["overwrite_training"] = overwrite_training 1500 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 1501 if save_every_kth_epoch is not None: 1502 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 1503 trainer.fit(**fit_kwargs) 1504 1505 1506def _train_joint_rank( 1507 rank: int, 1508 local_rank: int, 1509 name: str, 1510 model_type: str, 1511 input_path: str, 1512 n_epochs: int, 1513 n_iterations: Optional[int], 1514 early_stopping: Optional[int], 1515 max_num_objects: int, 1516 checkpoint_path, 1517 freeze, 1518 peft_kwargs, 1519 lr: float, 1520 save_root, 1521 scheduler_kwargs: Optional[Dict], 1522 save_every_kth_epoch: Optional[int], 1523 overwrite_training: bool, 1524 load_from_checkpoint: Optional[Union[str, os.PathLike]], 1525 prob_to_use_pt_input: float, 1526 prob_to_use_box_input: float, 1527 num_frames_to_correct: int, 1528 rand_frames_to_correct: bool, 1529 prob_to_sample_from_gt: float, 1530 add_all_frames_to_correct_as_cond: bool, 1531 num_correction_pt_per_frame: int, 1532 num_init_cond_frames: int, 1533 clip_grad_norm: Optional[float], 1534 batch_size: int, 1535 batch_size_2d: int, 1536 z_slices: List[int], 1537 dataset_choice: str, 1538 n_workers: int, 1539 find_unused_parameters: bool, 1540 largest_first: bool, 1541 bidirectional: bool = False, 1542 use_focal_loss: bool = False, 1543 focal_weight: float = 20.0, 1544 use_object_score_loss: bool = False, 1545 average_over_frames: bool = False, 1546 automatic_metric_weight: float = 0.25, 1547 initial_features: int = 32, 1548 distance_type: str = "geodesic", 1549 with_boundaries: bool = True, 1550 boundary_dice_weight: float = 1.0, 1551 label_trafo_threads: int = 1, 1552 compile: Optional[List[str]] = None, 1553): 1554 """Single-rank torchrun worker for train_joint_sam2_multi_gpu.""" 1555 from torch_em.multi_gpu_training import DDP 1556 1557 from micro_sam.v2.datasets.generalist_loader import _build_joint_datasets, seed_worker 1558 from micro_sam.v2.datasets.sampler import DistributedUniBatchSampler, _build_group_map 1559 from micro_sam.v2.models.util import UniSAM2 1560 1561 pg_kwargs = {"timeout": COMPILE_PG_TIMEOUT} if compile else {} 1562 dist.init_process_group("nccl", **pg_kwargs) 1563 world_size = dist.get_world_size() 1564 1565 device = torch.device(f"cuda:{local_rank}") 1566 torch.cuda.set_device(device) 1567 1568 batch_size_per_group = {2: batch_size_2d} if batch_size_2d != batch_size else None 1569 1570 train_ds, val_ds = _build_joint_datasets( 1571 input_path, z_slices, dataset_choice, distance_type, 1572 with_boundaries=with_boundaries, label_trafo_threads=label_trafo_threads, 1573 ) 1574 1575 # The trailing partial batch would have its own shape and recompile the encoder on one rank. 1576 train_sampler = DistributedUniBatchSampler( 1577 group_per_index=_build_group_map(train_ds), 1578 batch_size=batch_size, 1579 batch_size_per_group=batch_size_per_group, 1580 shuffle=True, drop_last=True, rank=rank, world_size=world_size, 1581 ) 1582 val_sampler = DistributedUniBatchSampler( 1583 group_per_index=_build_group_map(val_ds), 1584 batch_size=batch_size, 1585 batch_size_per_group=batch_size_per_group, 1586 shuffle=False, rank=rank, world_size=world_size, 1587 ) 1588 train_loader = torch.utils.data.DataLoader( 1589 train_ds, batch_sampler=train_sampler, num_workers=n_workers, 1590 pin_memory=True, persistent_workers=n_workers > 0, 1591 ) 1592 train_loader.shuffle = True 1593 # Deterministic validation crops, matching the interactive path. 1594 val_loader = torch.utils.data.DataLoader( 1595 val_ds, batch_sampler=val_sampler, num_workers=n_workers, 1596 pin_memory=True, persistent_workers=False, worker_init_fn=seed_worker, 1597 ) 1598 val_loader.shuffle = False 1599 1600 sam2_model = get_sam2_train_model( 1601 model_type=model_type, device=device, 1602 checkpoint_path=checkpoint_path, freeze=freeze, peft_kwargs=peft_kwargs, 1603 prob_to_use_pt_input=prob_to_use_pt_input, 1604 prob_to_use_box_input=prob_to_use_box_input, 1605 num_frames_to_correct=num_frames_to_correct, 1606 rand_frames_to_correct=rand_frames_to_correct, 1607 prob_to_sample_from_gt=prob_to_sample_from_gt, 1608 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 1609 num_correction_pt_per_frame=num_correction_pt_per_frame, 1610 num_init_cond_frames_for_train=num_init_cond_frames, 1611 bidirectional=bidirectional, 1612 ) 1613 # SAM2Train seeds its prompt sampling with 42 on every rank; give each rank its own stream. 1614 sam2_model.rng = np.random.default_rng(42 + rank) 1615 unetr = UniSAM2( 1616 encoder=sam2_model.image_encoder, output_channels=4 + int(with_boundaries), 1617 initial_features=initial_features, device=device, 1618 perform_range_checks=False, # The trainer checks the input range once. 1619 ) 1620 _init_start_decoder(unetr, model_type, checkpoint_path) 1621 compile = _check_compile(compile) 1622 _configure_joint_speed(sam2_model, unetr, compile) 1623 1624 sam2_params = list(sam2_model.parameters()) 1625 unetr_decoder_params = [p for n, p in unetr.named_parameters() if not n.startswith("encoder")] 1626 # DDP does not broadcast the decoder, so every rank starts from the parameters of rank 0. 1627 for param in unetr_decoder_params: 1628 dist.broadcast(param.data, src=0) 1629 1630 # Only DDP-wrap sam2_model. We sync the unetr decoder grads manually. 1631 ddp_model = DDP(sam2_model, device_ids=[local_rank], find_unused_parameters=find_unused_parameters) 1632 1633 interactive_loss = CustomSAM2Loss( 1634 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 1635 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 1636 compile_kernels="loss" in compile, 1637 ) 1638 automatic_loss = DirectedDistanceLoss( 1639 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 1640 ) 1641 convert_inputs = ConvertToSam2VideoBatch(max_num_objects=max_num_objects, largest_first=largest_first) 1642 1643 if scheduler_kwargs is None: 1644 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 1645 # The fused AdamW kernel exists for CUDA only. 1646 optimizer = torch.optim.AdamW( 1647 sam2_params + unetr_decoder_params, lr=lr, fused=torch.device(device).type == "cuda" 1648 ) 1649 scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, **scheduler_kwargs) 1650 1651 trainer = JointSam2Trainer( 1652 name=name, 1653 model=ddp_model, 1654 train_loader=train_loader, 1655 val_loader=val_loader, 1656 optimizer=optimizer, 1657 device=device, 1658 lr_scheduler=scheduler, 1659 logger=JointSam2Logger, 1660 log_image_interval=100, 1661 compile_model=False, 1662 early_stopping=early_stopping, 1663 save_root=save_root, 1664 rank=rank, 1665 unetr=unetr, 1666 convert_inputs=convert_inputs, 1667 interactive_loss=interactive_loss, 1668 automatic_loss=automatic_loss, 1669 automatic_metric_weight=automatic_metric_weight, 1670 clip_grad_norm=clip_grad_norm, 1671 ) 1672 1673 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 1674 fit_kwargs["overwrite_training"] = overwrite_training 1675 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 1676 if save_every_kth_epoch is not None: 1677 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 1678 _fit_and_shut_down(trainer, fit_kwargs) 1679 1680 1681def train_joint_sam2_multi_gpu( 1682 name: str, 1683 model_type: str, 1684 input_path: str, 1685 batch_size: int = 2, 1686 batch_size_2d: Optional[int] = None, 1687 z_slices: Optional[List[int]] = None, 1688 dataset_choice: str = "all", 1689 n_workers: int = 16, 1690 n_epochs: int = 100, 1691 n_iterations: Optional[int] = None, 1692 early_stopping: Optional[int] = None, 1693 max_num_objects: int = 20, 1694 checkpoint_path=None, 1695 freeze: Optional[List[str]] = None, 1696 peft_kwargs: Optional[Dict] = None, 1697 lr: float = 1e-5, 1698 save_root=None, 1699 scheduler_kwargs: Optional[Dict[str, Any]] = None, 1700 save_every_kth_epoch: Optional[int] = None, 1701 overwrite_training: bool = True, 1702 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1703 prob_to_use_pt_input: float = 0.5, 1704 prob_to_use_box_input: float = 0.5, 1705 num_frames_to_correct: int = 1, 1706 rand_frames_to_correct: bool = True, 1707 prob_to_sample_from_gt: float = 0.1, 1708 add_all_frames_to_correct_as_cond: bool = True, 1709 num_correction_pt_per_frame: int = 7, 1710 num_init_cond_frames: int = 2, 1711 clip_grad_norm: Optional[float] = None, 1712 find_unused_parameters: bool = True, 1713 largest_first: bool = False, 1714 bidirectional: bool = False, 1715 use_focal_loss: bool = False, 1716 focal_weight: float = 20.0, 1717 use_object_score_loss: bool = False, 1718 average_over_frames: bool = False, 1719 automatic_metric_weight: float = 0.25, 1720 initial_features: int = 32, 1721 distance_type: str = "geodesic", 1722 with_boundaries: bool = True, 1723 boundary_dice_weight: float = 1.0, 1724 label_trafo_threads: int = 1, 1725 compile: Optional[List[str]] = None, 1726) -> None: 1727 """Train SAM2Train and UniSAM2 jointly across multiple GPUs with DDP. 1728 1729 Must be launched via ``torchrun`` - one process per GPU, on one or more nodes. 1730 Example (single node): ``torchrun --nproc_per_node=4 train_joint.py`` 1731 Example (multi-node): ``srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_joint.py`` 1732 1733 Both the interactive and automatic datasets are constructed independently in 1734 each rank. Only the SAM2 model is DDP-wrapped; UniSAM2 decoder gradients are 1735 manually all_reduced after each backward so the shared encoder is not double-reduced. 1736 1737 Args: 1738 name: Checkpoint / log folder name. 1739 model_type: SAM2 encoder variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 1740 input_path: Root path to the generalist training data. 1741 batch_size: Batch size per GPU for 3D groups (both branches). 1742 batch_size_2d: Batch size per GPU for 2D groups. Defaults to ``batch_size``. 1743 z_slices: Z-slice counts for 3D groups (default [8]). 1744 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 1745 n_workers: DataLoader workers per GPU. 1746 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1747 n_iterations: If set, train for this many iterations instead of epochs. 1748 early_stopping: Stop after this many epochs without improvement. 1749 max_num_objects: Max objects per interactive step. 1750 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 1751 freeze: Component name prefixes to freeze (e.g. ["image_encoder"]). 1752 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 1753 lr: Learning rate. 1754 save_root: Root directory for checkpoints and logs. 1755 scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10. 1756 save_every_kth_epoch: Save a checkpoint every k-th epoch. 1757 overwrite_training: Overwrite an existing checkpoint at the same path. 1758 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1759 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 1760 the pretrained SAM2 weights to start from. 1761 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 1762 prob_to_use_box_input: Conditional P(box) given point/box mode. 1763 num_frames_to_correct: Max frames per volume receiving correction clicks. 1764 rand_frames_to_correct: Randomly sample how many frames to correct. 1765 prob_to_sample_from_gt: P(correction click from GT vs error region). 1766 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 1767 num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7). 1768 num_init_cond_frames: Initial conditioning frames before the first correction round. 1769 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 1770 finetuning uses 0.1. 1771 find_unused_parameters: Passed to DistributedDataParallel. 1772 bidirectional: Bidirectional propagation during training for 3D z-stacks. 1773 use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss. 1774 focal_weight: Weight of the focal mask loss when enabled. 1775 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss. 1776 average_over_frames: Average the interactive loss over frames instead of summing. 1777 automatic_metric_weight: Weight of the automatic metric in the combined validation 1778 metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, 1779 which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive 1780 Dice metric. Set to 0 to select purely on the interactive task. 1781 initial_features: Width of the convolutional decoder. The features per level are 1782 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1783 distance_type: Directed distance target for the automatic branch. "geodesic" uses the 1784 geodesic hybrid field around each object's center, "directed" the euclidean vector 1785 to the nearest boundary. 1786 with_boundaries: The flag to add a fifth automatic output for the full object-boundary target. 1787 By default True, which matches the decoders of the registered models. 1788 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 1789 label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel 1790 in the distance transform. Only pays off when the node has more cores than loader workers. 1791 compile: The parts to compile with ``torch.compile``. "encoder" is the shared image encoder, 1792 "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels 1793 of the interactive loss. The default compiles nothing. 1794 """ 1795 if z_slices is None: 1796 z_slices = [8] 1797 if batch_size_2d is None: 1798 batch_size_2d = batch_size 1799 1800 if "RANK" not in os.environ: 1801 raise RuntimeError( 1802 "train_joint_sam2_multi_gpu must be launched via torchrun, not called directly. " 1803 "Example: torchrun --nproc_per_node=4 train_joint.py" 1804 ) 1805 rank = int(os.environ["RANK"]) 1806 local_rank = int(os.environ["LOCAL_RANK"]) 1807 1808 _train_joint_rank( 1809 rank=rank, 1810 local_rank=local_rank, 1811 name=name, 1812 model_type=model_type, 1813 input_path=input_path, 1814 n_epochs=n_epochs, 1815 n_iterations=n_iterations, 1816 early_stopping=early_stopping, 1817 max_num_objects=max_num_objects, 1818 checkpoint_path=checkpoint_path, 1819 freeze=freeze, 1820 peft_kwargs=peft_kwargs, 1821 lr=lr, 1822 save_root=save_root, 1823 scheduler_kwargs=scheduler_kwargs, 1824 save_every_kth_epoch=save_every_kth_epoch, 1825 overwrite_training=overwrite_training, 1826 load_from_checkpoint=load_from_checkpoint, 1827 prob_to_use_pt_input=prob_to_use_pt_input, 1828 prob_to_use_box_input=prob_to_use_box_input, 1829 num_frames_to_correct=num_frames_to_correct, 1830 rand_frames_to_correct=rand_frames_to_correct, 1831 prob_to_sample_from_gt=prob_to_sample_from_gt, 1832 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 1833 num_correction_pt_per_frame=num_correction_pt_per_frame, 1834 num_init_cond_frames=num_init_cond_frames, 1835 clip_grad_norm=clip_grad_norm, 1836 batch_size=batch_size, 1837 batch_size_2d=batch_size_2d, 1838 z_slices=z_slices, 1839 dataset_choice=dataset_choice, 1840 n_workers=n_workers, 1841 find_unused_parameters=find_unused_parameters, 1842 largest_first=largest_first, 1843 bidirectional=bidirectional, 1844 use_focal_loss=use_focal_loss, 1845 focal_weight=focal_weight, 1846 use_object_score_loss=use_object_score_loss, 1847 average_over_frames=average_over_frames, 1848 automatic_metric_weight=automatic_metric_weight, 1849 initial_features=initial_features, 1850 distance_type=distance_type, 1851 with_boundaries=with_boundaries, 1852 boundary_dice_weight=boundary_dice_weight, 1853 label_trafo_threads=label_trafo_threads, 1854 compile=compile, 1855 )
118def train_sam2( 119 name: str, 120 model_type: str, 121 train_loader: DataLoader, 122 val_loader: DataLoader, 123 n_epochs: int = 100, 124 n_iterations: Optional[int] = None, 125 early_stopping: Optional[int] = 10, 126 max_num_objects: int = 20, 127 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 128 peft_kwargs: Optional[Dict] = None, 129 device: Optional[Union[str, torch.device]] = None, 130 lr: float = 1e-5, 131 vision_lr: Optional[float] = None, 132 save_root: Optional[Union[str, os.PathLike]] = None, 133 save_every_kth_epoch: Optional[int] = None, 134 overwrite_training: bool = True, 135 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 136 prob_to_use_pt_input: float = 0.5, 137 prob_to_use_box_input: float = 0.5, 138 num_frames_to_correct: int = 1, 139 rand_frames_to_correct: bool = True, 140 prob_to_sample_from_gt: float = 0.1, 141 add_all_frames_to_correct_as_cond: bool = True, 142 num_correction_pt_per_frame: int = 7, 143 num_init_cond_frames: int = 2, 144 clip_grad_norm: Optional[float] = None, 145 layer_decay: float = 1.0, 146 scheduler_kwargs: Optional[Dict[str, Any]] = None, 147 largest_first: bool = False, 148 augment: bool = False, 149 bidirectional: bool = False, 150 use_focal_loss: bool = False, 151 focal_weight: float = 20.0, 152 use_object_score_loss: bool = False, 153 average_over_frames: bool = False, 154) -> None: 155 """Train SAM2 for interactive segmentation with SAM2's native prompting strategy. 156 157 Uses SAM2Train (full model with video memory) which handles both 2D (T=1) and 158 3D/video (T>1) batches. All prompting logic - initial point/box/mask selection 159 and iterative correction from error regions - is embedded in the model forward 160 pass. Pass a MixedLoader(loader_2d, loader_3d) as train_loader for joint 2D+3D 161 training. Build the loaders for your own data with 162 `micro_sam.v2.training.loaders.default_sam2_loader` and ``mode="interactive"``. 163 164 Args: 165 name: Checkpoint/log folder name. 166 model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 167 train_loader: DataLoader yielding (x, y) tuples with integer instance labels. 168 x: (B,C,H,W) for 2D or (B,C,Z,H,W) for 3D in [0, 1]. 169 `default_sam2_loader` normalizes the images to this range. 170 y: (B,1,H,W) or (B,1,Z,H,W) with integer instance IDs. 171 val_loader: Same format as train_loader, used for validation. 172 n_epochs: Training epochs. 173 n_iterations: Override n_epochs with a fixed iteration budget. 174 early_stopping: Stop after this many epochs without improvement (None = off). 175 max_num_objects: Max objects sampled per image/volume per step. 176 checkpoint_path: Custom checkpoint path. Downloads default weights if None. 177 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 178 device: Training device. Auto-selects if None. 179 lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+). 180 vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. 181 SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr. 182 save_root: Root directory for checkpoints and logs. 183 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 184 overwrite_training: Overwrite an existing checkpoint at the same path. 185 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 186 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 187 the pretrained SAM2 weights to start from. 188 prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation). 189 prob_to_use_box_input: Conditional probability of using a box instead of a click. 190 num_frames_to_correct: Max frames per volume that receive iterative correction 191 clicks. Set equal to the number of z-slices to correct every frame. 192 rand_frames_to_correct: Randomly sample 1..num_frames_to_correct frames to 193 correct per step rather than always correcting the maximum. 194 prob_to_sample_from_gt: Probability of sampling a correction click from GT 195 instead of the error region - reduces overfitting to error patterns. 196 add_all_frames_to_correct_as_cond: Add frames that receive correction clicks 197 as conditioning frames for memory propagation. 198 num_correction_pt_per_frame: Number of correction clicks per frame per correction 199 round. SAM2 default is 7. 200 num_init_cond_frames: Number of initial conditioning frames (frames that receive 201 the first prompt before any correction round). The MOSE finetune config uses 2. 202 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 203 finetuning uses 0.1. 204 scheduler_kwargs: ReduceLROnPlateau kwargs (mode, factor, patience). Defaults to 205 factor=0.9, patience=5. 206 layer_decay: Multiplicative LR decay applied per trunk block toward shallower 207 layers (block 0 gets vision_lr * layer_decay^n_blocks). The MOSE finetune 208 config uses 0.9. Only active when vision_lr is set. Default 1.0 = no decay. 209 augment: Apply SAM2 MOSE-style data augmentations (RandomHorizontalFlip, 210 RandomAffine, ColorJitter, RandomGrayscale) before each forward pass. 211 Augmentations are applied consistently across frames for 3D volumes. 212 bidirectional: If True, use bidirectional propagation during training: a random 213 z-frame is chosen as the start frame each step, with propagation and correction 214 clicks applied in both directions. No effect for 2D (T=1) batches. 215 use_focal_loss: Add SAM2's sigmoid focal mask loss on top of the Dice loss in 216 CustomSAM2Loss. Off by default for a simpler micro_sam-style loss. 217 focal_weight: Weight of the focal mask loss when enabled. SAM2 uses 20; set to 1 218 to keep it on equal footing with the Dice loss. 219 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss in 220 CustomSAM2Loss. Off by default for a simpler micro_sam-style loss. 221 average_over_frames: Average the interactive loss over frames instead of summing, 222 so 2D and 3D batches share a scale when training on mixed 2D + 3D data. 223 """ 224 t_start = time.time() 225 226 device = get_device(device) 227 model = get_sam2_train_model( 228 model_type=model_type, 229 device=device, 230 checkpoint_path=checkpoint_path, 231 peft_kwargs=peft_kwargs, 232 prob_to_use_pt_input=prob_to_use_pt_input, 233 prob_to_use_box_input=prob_to_use_box_input, 234 num_frames_to_correct=num_frames_to_correct, 235 rand_frames_to_correct=rand_frames_to_correct, 236 prob_to_sample_from_gt=prob_to_sample_from_gt, 237 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 238 num_correction_pt_per_frame=num_correction_pt_per_frame, 239 num_init_cond_frames_for_train=num_init_cond_frames, 240 bidirectional=bidirectional, 241 ) 242 243 interactive_loss = CustomSAM2Loss( 244 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 245 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 246 ) 247 248 augmentor = VideoAugment() if augment else None 249 convert_inputs = ConvertToSam2VideoBatch( 250 max_num_objects=max_num_objects, largest_first=largest_first, augmentor=augmentor, 251 ) 252 253 optimizer = _build_optimizer(model, lr=lr, vision_lr=vision_lr, layer_decay=layer_decay) 254 scheduler = _build_scheduler(optimizer, **(scheduler_kwargs or {})) 255 256 trainer = Sam2Trainer( 257 name=name, 258 model=model, 259 train_loader=train_loader, 260 val_loader=val_loader, 261 optimizer=optimizer, 262 device=device, 263 lr_scheduler=scheduler, 264 logger=Sam2Logger, 265 log_image_interval=100, 266 compile_model=False, 267 early_stopping=early_stopping, 268 save_root=save_root, 269 convert_inputs=convert_inputs, 270 loss=interactive_loss, 271 clip_grad_norm=clip_grad_norm, 272 ) 273 274 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 275 if save_every_kth_epoch is not None: 276 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 277 fit_kwargs["overwrite_training"] = overwrite_training 278 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 279 trainer.fit(**fit_kwargs) 280 281 elapsed = time.time() - t_start 282 h, m, s = int(elapsed // 3600), int(elapsed % 3600 // 60), int(elapsed % 60) 283 print(f"Training took {elapsed:.1f}s (= {h:02}:{m:02}:{s:02})")
Train SAM2 for interactive segmentation with SAM2's native prompting strategy.
Uses SAM2Train (full model with video memory) which handles both 2D (T=1) and
3D/video (T>1) batches. All prompting logic - initial point/box/mask selection
and iterative correction from error regions - is embedded in the model forward
pass. Pass a MixedLoader(loader_2d, loader_3d) as train_loader for joint 2D+3D
training. Build the loaders for your own data with
micro_sam.v2.training.loaders.default_sam2_loader and mode="interactive".
Arguments:
- name: Checkpoint/log folder name.
- model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
- train_loader: DataLoader yielding (x, y) tuples with integer instance labels.
x: (B,C,H,W) for 2D or (B,C,Z,H,W) for 3D in [0, 1].
default_sam2_loadernormalizes the images to this range. y: (B,1,H,W) or (B,1,Z,H,W) with integer instance IDs. - val_loader: Same format as train_loader, used for validation.
- n_epochs: Training epochs.
- n_iterations: Override n_epochs with a fixed iteration budget.
- early_stopping: Stop after this many epochs without improvement (None = off).
- max_num_objects: Max objects sampled per image/volume per step.
- checkpoint_path: Custom checkpoint path. Downloads default weights if None.
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method. - device: Training device. Auto-selects if None.
- lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+).
- vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr.
- save_root: Root directory for checkpoints and logs.
- save_every_kth_epoch: Save a separate checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- prob_to_use_pt_input: Probability of using point/box prompts (vs mask propagation).
- prob_to_use_box_input: Conditional probability of using a box instead of a click.
- num_frames_to_correct: Max frames per volume that receive iterative correction clicks. Set equal to the number of z-slices to correct every frame.
- rand_frames_to_correct: Randomly sample 1..num_frames_to_correct frames to correct per step rather than always correcting the maximum.
- prob_to_sample_from_gt: Probability of sampling a correction click from GT instead of the error region - reduces overfitting to error patterns.
- add_all_frames_to_correct_as_cond: Add frames that receive correction clicks as conditioning frames for memory propagation.
- num_correction_pt_per_frame: Number of correction clicks per frame per correction round. SAM2 default is 7.
- num_init_cond_frames: Number of initial conditioning frames (frames that receive the first prompt before any correction round). The MOSE finetune config uses 2.
- clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own finetuning uses 0.1.
- scheduler_kwargs: ReduceLROnPlateau kwargs (mode, factor, patience). Defaults to factor=0.9, patience=5.
- layer_decay: Multiplicative LR decay applied per trunk block toward shallower layers (block 0 gets vision_lr * layer_decay^n_blocks). The MOSE finetune config uses 0.9. Only active when vision_lr is set. Default 1.0 = no decay.
- augment: Apply SAM2 MOSE-style data augmentations (RandomHorizontalFlip, RandomAffine, ColorJitter, RandomGrayscale) before each forward pass. Augmentations are applied consistently across frames for 3D volumes.
- bidirectional: If True, use bidirectional propagation during training: a random z-frame is chosen as the start frame each step, with propagation and correction clicks applied in both directions. No effect for 2D (T=1) batches.
- use_focal_loss: Add SAM2's sigmoid focal mask loss on top of the Dice loss in CustomSAM2Loss. Off by default for a simpler micro_sam-style loss.
- focal_weight: Weight of the focal mask loss when enabled. SAM2 uses 20; set to 1 to keep it on equal footing with the Dice loss.
- use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss in CustomSAM2Loss. Off by default for a simpler micro_sam-style loss.
- average_over_frames: Average the interactive loss over frames instead of summing, so 2D and 3D batches share a scale when training on mixed 2D + 3D data.
450def train_sam2_multi_gpu( 451 name: str, 452 model_type: str, 453 input_path: str, 454 batch_size: int = 2, 455 batch_size_2d: Optional[int] = None, 456 z_slices: Optional[List[int]] = None, 457 dataset_choice: str = "all", 458 n_workers: int = 16, 459 n_epochs: int = 100, 460 n_iterations: Optional[int] = None, 461 early_stopping: Optional[int] = 10, 462 max_num_objects: int = 20, 463 checkpoint_path=None, 464 peft_kwargs: Optional[Dict] = None, 465 lr: float = 1e-5, 466 vision_lr: Optional[float] = None, 467 save_root=None, 468 save_every_kth_epoch: Optional[int] = None, 469 overwrite_training: bool = True, 470 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 471 prob_to_use_pt_input: float = 0.5, 472 prob_to_use_box_input: float = 0.5, 473 num_frames_to_correct: int = 1, 474 rand_frames_to_correct: bool = True, 475 prob_to_sample_from_gt: float = 0.1, 476 add_all_frames_to_correct_as_cond: bool = True, 477 num_correction_pt_per_frame: int = 7, 478 num_init_cond_frames: int = 2, 479 clip_grad_norm: Optional[float] = None, 480 layer_decay: float = 1.0, 481 scheduler_kwargs: Optional[Dict[str, Any]] = None, 482 find_unused_parameters: bool = True, 483 largest_first: bool = False, 484 augment: bool = False, 485 bidirectional: bool = False, 486 use_focal_loss: bool = False, 487 focal_weight: float = 20.0, 488 use_object_score_loss: bool = False, 489 average_over_frames: bool = False, 490) -> None: 491 """Train SAM2 for interactive segmentation across multiple GPUs with DDP. 492 493 Must be launched via ``torchrun`` - one process per GPU, on one or more nodes. 494 Example (single node): ``torchrun --nproc_per_node=4 train_sam2.py`` 495 Example (multi-node): ``srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_sam2.py`` 496 497 Each rank reads its identity from the ``RANK``, ``LOCAL_RANK``, and 498 ``WORLD_SIZE`` environment variables set by torchrun and builds its own 499 dataset independently. 500 501 Args: 502 name: Checkpoint/log folder name. 503 model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 504 input_path: Root path to the generalist training data. 505 batch_size: Batch size per GPU for 3D groups. 506 batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size). 507 z_slices: Z-slice counts for 3D data groups (default [8]). 508 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 509 n_workers: DataLoader workers per GPU. 510 n_epochs: Training epochs. 511 n_iterations: Override n_epochs with a fixed iteration budget. 512 early_stopping: Stop after this many epochs without improvement. 513 max_num_objects: Max objects sampled per image/volume per step. 514 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 515 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 516 lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+). 517 vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. 518 SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr. 519 save_root: Root directory for checkpoints and logs. 520 save_every_kth_epoch: Save a checkpoint every k-th epoch. 521 overwrite_training: Overwrite an existing checkpoint at the same path. 522 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 523 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 524 the pretrained SAM2 weights to start from. 525 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 526 prob_to_use_box_input: Conditional P(box) given point/box mode. 527 num_frames_to_correct: Max frames per volume receiving correction clicks. 528 rand_frames_to_correct: Randomly sample how many frames to correct. 529 prob_to_sample_from_gt: P(correction click from GT vs error region). 530 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 531 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 532 finetuning uses 0.1. 533 find_unused_parameters: Passed to DistributedDataParallel. 534 """ 535 if z_slices is None: 536 z_slices = [8] 537 if batch_size_2d is None: 538 batch_size_2d = batch_size 539 540 if "RANK" not in os.environ: 541 raise RuntimeError( 542 "train_sam2_multi_gpu must be launched via torchrun, not called directly. " 543 "Example: torchrun --nproc_per_node=4 train_sam2.py" 544 ) 545 rank = int(os.environ["RANK"]) 546 local_rank = int(os.environ["LOCAL_RANK"]) 547 548 _train_sam2_rank( 549 rank=rank, 550 local_rank=local_rank, 551 name=name, 552 model_type=model_type, 553 input_path=input_path, 554 n_epochs=n_epochs, 555 n_iterations=n_iterations, 556 early_stopping=early_stopping, 557 max_num_objects=max_num_objects, 558 checkpoint_path=checkpoint_path, 559 peft_kwargs=peft_kwargs, 560 lr=lr, 561 save_root=save_root, 562 save_every_kth_epoch=save_every_kth_epoch, 563 overwrite_training=overwrite_training, 564 load_from_checkpoint=load_from_checkpoint, 565 prob_to_use_pt_input=prob_to_use_pt_input, 566 prob_to_use_box_input=prob_to_use_box_input, 567 num_frames_to_correct=num_frames_to_correct, 568 rand_frames_to_correct=rand_frames_to_correct, 569 prob_to_sample_from_gt=prob_to_sample_from_gt, 570 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 571 num_correction_pt_per_frame=num_correction_pt_per_frame, 572 num_init_cond_frames=num_init_cond_frames, 573 clip_grad_norm=clip_grad_norm, 574 layer_decay=layer_decay, 575 scheduler_kwargs=scheduler_kwargs, 576 vision_lr=vision_lr, 577 batch_size=batch_size, 578 batch_size_2d=batch_size_2d, 579 z_slices=z_slices, 580 dataset_choice=dataset_choice, 581 n_workers=n_workers, 582 find_unused_parameters=find_unused_parameters, 583 largest_first=largest_first, 584 augment=augment, 585 bidirectional=bidirectional, 586 use_focal_loss=use_focal_loss, 587 focal_weight=focal_weight, 588 use_object_score_loss=use_object_score_loss, 589 average_over_frames=average_over_frames, 590 )
Train SAM2 for interactive segmentation across multiple GPUs with DDP.
Must be launched via torchrun - one process per GPU, on one or more nodes.
Example (single node): torchrun --nproc_per_node=4 train_sam2.py
Example (multi-node): srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_sam2.py
Each rank reads its identity from the RANK, LOCAL_RANK, and
WORLD_SIZE environment variables set by torchrun and builds its own
dataset independently.
Arguments:
- name: Checkpoint/log folder name.
- model_type: SAM2 variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
- input_path: Root path to the generalist training data.
- batch_size: Batch size per GPU for 3D groups.
- batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size).
- z_slices: Z-slice counts for 3D data groups (default [8]).
- dataset_choice:
"lm","em","hp", or"all". - n_workers: DataLoader workers per GPU.
- n_epochs: Training epochs.
- n_iterations: Override n_epochs with a fixed iteration budget.
- early_stopping: Stop after this many epochs without improvement.
- max_num_objects: Max objects sampled per image/volume per step.
- checkpoint_path: SAM2 checkpoint path. Downloads default if None.
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method. - lr: Learning rate. SAM2 OG fine-tuning uses 1e-5 (tiny) or 5e-6 (b+).
- vision_lr: Separate LR for the image encoder. If None, uses lr for all parameters. SAM2 OG fine-tuning uses 6e-6 (tiny) or 3e-6 (b+), i.e. ~0.6x the base lr.
- save_root: Root directory for checkpoints and logs.
- save_every_kth_epoch: Save a checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation).
- prob_to_use_box_input: Conditional P(box) given point/box mode.
- num_frames_to_correct: Max frames per volume receiving correction clicks.
- rand_frames_to_correct: Randomly sample how many frames to correct.
- prob_to_sample_from_gt: P(correction click from GT vs error region).
- add_all_frames_to_correct_as_cond: Add corrected frames as cond frames.
- clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own finetuning uses 0.1.
- find_unused_parameters: Passed to DistributedDataParallel.
668def train_automatic( 669 name: str, 670 model_type: str, 671 train_loader: DataLoader, 672 val_loader: DataLoader, 673 n_epochs: int = 100, 674 n_iterations: Optional[int] = None, 675 early_stopping: Optional[int] = None, 676 device: Optional[Union[str, torch.device]] = None, 677 lr: float = 1e-5, 678 save_root: Optional[Union[str, os.PathLike]] = None, 679 save_every_kth_epoch: Optional[int] = None, 680 overwrite_training: bool = True, 681 peft_kwargs: Optional[Dict] = None, 682 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 683 initial_features: int = 32, 684 with_boundaries: bool = True, 685 boundary_dice_weight: float = 1.0, 686 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 687) -> None: 688 """Train UniSAM2 for automatic instance segmentation with directed distance targets. 689 690 Trains the UNETR3D-based UniSAM2 model using 691 :class:`~micro_sam.v2.loss.directed_distance_based.DirectedDistanceLoss` on 692 combined 2D + 3D data. Pass a loader built by 693 :func:`~micro_sam.v2.datasets.generalist_loader.get_dataloaders` with 694 ``label_trafo=GeodesicHybridDistanceTransform`` (the default). Build the loaders for your own 695 data with `micro_sam.v2.training.loaders.default_sam2_loader` and ``mode="automatic"``. 696 697 Args: 698 name: Checkpoint / log folder name. 699 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 700 "hvit_t_cells". A registered model initializes both the encoder and the decoder. 701 train_loader: DataLoader yielding (x, y) tuples with directed-distance targets. 702 val_loader: Same format, used for validation. 703 n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set. 704 n_iterations: If set, train for this many iterations instead of epochs. 705 early_stopping: Stop after this many epochs without improvement (None = off). 706 device: Training device. Auto-selects if None. 707 lr: Learning rate. 708 save_root: Root directory for checkpoints and logs. 709 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 710 overwrite_training: Overwrite an existing checkpoint at the same path. 711 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder during decoder training. 712 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 713 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 714 the pretrained SAM2 weights to start from. 715 initial_features: Width of the convolutional decoder. The features per level are 716 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 717 with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. 718 By default True, which matches the decoders of the registered models. 719 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 720 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 721 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 722 decoder. Without a decoder, the decoder starts from random weights. 723 """ 724 import torch_em 725 726 device = get_device(device) 727 model = _build_unisam2_model( 728 model_type, device, peft_kwargs=peft_kwargs, output_channels=4 + int(with_boundaries), 729 initial_features=initial_features, checkpoint_path=checkpoint_path, 730 ) 731 732 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 733 loss = DirectedDistanceLoss( 734 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 735 ) 736 737 trainer = torch_em.default_segmentation_trainer( 738 name=name, 739 model=model, 740 train_loader=train_loader, 741 val_loader=val_loader, 742 learning_rate=lr, 743 loss=loss, 744 metric=loss, 745 logger=UniSAM2Logger, 746 log_image_interval=50, 747 save_root=save_root, 748 compile_model=False, 749 scheduler_kwargs=scheduler_kwargs, 750 optimizer_kwargs={"weight_decay": 0.1}, 751 # The hardware decides the precision. SAM2 trains in bfloat16 only. 752 mixed_precision=training_autocast_dtype(device) is not None, 753 mixed_precision_dtype="bfloat16", 754 device=device, 755 early_stopping=early_stopping, 756 trainer_class=UniSAM2Trainer, 757 ) 758 759 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 760 fit_kwargs["overwrite_training"] = overwrite_training 761 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 762 if save_every_kth_epoch is not None: 763 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 764 trainer.fit(**fit_kwargs)
Train UniSAM2 for automatic instance segmentation with directed distance targets.
Trains the UNETR3D-based UniSAM2 model using
~micro_sam.v2.loss.directed_distance_based.DirectedDistanceLoss on
combined 2D + 3D data. Pass a loader built by
~micro_sam.v2.datasets.generalist_loader.get_dataloaders() with
label_trafo=GeodesicHybridDistanceTransform (the default). Build the loaders for your own
data with micro_sam.v2.training.loaders.default_sam2_loader and mode="automatic".
Arguments:
- name: Checkpoint / log folder name.
- model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like "hvit_t_cells". A registered model initializes both the encoder and the decoder.
- train_loader: DataLoader yielding (x, y) tuples with directed-distance targets.
- val_loader: Same format, used for validation.
- n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set.
- n_iterations: If set, train for this many iterations instead of epochs.
- early_stopping: Stop after this many epochs without improvement (None = off).
- device: Training device. Auto-selects if None.
- lr: Learning rate.
- save_root: Root directory for checkpoints and logs.
- save_every_kth_epoch: Save a separate checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder during decoder training. - load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- initial_features: Width of the convolutional decoder. The features per level are 'initial_features * 2 ** i', so this scales the decoder parameters quadratically.
- with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. By default True, which matches the decoders of the registered models.
- boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only.
- checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It
replaces the weights of
model_type. Its decoder, or the decoder file next to it, initializes the decoder. Without a decoder, the decoder starts from random weights.
882def train_automatic_multi_gpu( 883 name: str, 884 model_type: str, 885 input_path: str, 886 batch_size: int = 2, 887 batch_size_2d: Optional[int] = None, 888 z_slices: Optional[List[int]] = None, 889 dataset_choice: str = "all", 890 n_workers: int = 16, 891 n_epochs: int = 100, 892 n_iterations: Optional[int] = None, 893 early_stopping: Optional[int] = None, 894 lr: float = 1e-5, 895 save_root=None, 896 save_every_kth_epoch: Optional[int] = None, 897 overwrite_training: bool = True, 898 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 899 find_unused_parameters: bool = True, 900 peft_kwargs: Optional[Dict] = None, 901 initial_features: int = 32, 902 with_boundaries: bool = True, 903 boundary_dice_weight: float = 1.0, 904 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 905) -> None: 906 """Train UniSAM2 for automatic segmentation across multiple GPUs with DDP. 907 908 Mirrors :func:`train_automatic` but must be launched via ``torchrun`` - one 909 process per GPU. Takes ``input_path`` instead of pre-built dataloaders because 910 each rank must build its own dataset objects. 911 912 Args: 913 name: Checkpoint / log folder name. 914 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 915 "hvit_t_cells". A registered model initializes both the encoder and the decoder. 916 input_path: Root path to the generalist training data. 917 batch_size: Batch size per GPU for 3D groups. 918 batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size). 919 z_slices: Z-slice counts for 3D data groups (default [8]). 920 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 921 n_workers: DataLoader workers per GPU. 922 n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set. 923 n_iterations: If set, train for this many iterations instead of epochs. 924 early_stopping: Stop after this many epochs without improvement. 925 lr: Learning rate. 926 save_root: Root directory for checkpoints and logs. 927 save_every_kth_epoch: Save a checkpoint every k-th epoch. 928 overwrite_training: Overwrite an existing checkpoint at the same path. 929 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 930 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 931 the pretrained SAM2 weights to start from. 932 find_unused_parameters: Passed to DistributedDataParallel. 933 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 934 initial_features: Width of the convolutional decoder. The features per level are 935 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 936 with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. 937 By default True, which matches the decoders of the registered models. 938 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 939 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 940 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 941 decoder. Without a decoder, the decoder starts from random weights. 942 """ 943 if z_slices is None: 944 z_slices = [8] 945 if batch_size_2d is None: 946 batch_size_2d = batch_size 947 948 if "RANK" not in os.environ: 949 raise RuntimeError( 950 "train_automatic_multi_gpu must be launched via torchrun, not called directly. " 951 "Example: torchrun --nproc_per_node=4 train_automatic.py" 952 ) 953 rank = int(os.environ["RANK"]) 954 local_rank = int(os.environ["LOCAL_RANK"]) 955 956 _train_automatic_rank( 957 rank=rank, 958 local_rank=local_rank, 959 name=name, 960 model_type=model_type, 961 input_path=input_path, 962 n_epochs=n_epochs, 963 n_iterations=n_iterations, 964 early_stopping=early_stopping, 965 lr=lr, 966 save_root=save_root, 967 save_every_kth_epoch=save_every_kth_epoch, 968 overwrite_training=overwrite_training, 969 load_from_checkpoint=load_from_checkpoint, 970 batch_size=batch_size, 971 batch_size_2d=batch_size_2d, 972 z_slices=z_slices, 973 dataset_choice=dataset_choice, 974 n_workers=n_workers, 975 find_unused_parameters=find_unused_parameters, 976 initial_features=initial_features, 977 with_boundaries=with_boundaries, 978 boundary_dice_weight=boundary_dice_weight, 979 peft_kwargs=peft_kwargs, 980 checkpoint_path=checkpoint_path, 981 )
Train UniSAM2 for automatic segmentation across multiple GPUs with DDP.
Mirrors train_automatic() but must be launched via torchrun - one
process per GPU. Takes input_path instead of pre-built dataloaders because
each rank must build its own dataset objects.
Arguments:
- name: Checkpoint / log folder name.
- model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like "hvit_t_cells". A registered model initializes both the encoder and the decoder.
- input_path: Root path to the generalist training data.
- batch_size: Batch size per GPU for 3D groups.
- batch_size_2d: Batch size per GPU for 2D groups (falls back to batch_size).
- z_slices: Z-slice counts for 3D data groups (default [8]).
- dataset_choice:
"lm","em","hp", or"all". - n_workers: DataLoader workers per GPU.
- n_epochs: Number of training epochs (default 100). Ignored if n_iterations is set.
- n_iterations: If set, train for this many iterations instead of epochs.
- early_stopping: Stop after this many epochs without improvement.
- lr: Learning rate.
- save_root: Root directory for checkpoints and logs.
- save_every_kth_epoch: Save a checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- find_unused_parameters: Passed to DistributedDataParallel.
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method. - initial_features: Width of the convolutional decoder. The features per level are 'initial_features * 2 ** i', so this scales the decoder parameters quadratically.
- with_boundaries: The flag to add a fifth decoder output for the full object-boundary target. By default True, which matches the decoders of the registered models.
- boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only.
- checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It
replaces the weights of
model_type. Its decoder, or the decoder file next to it, initializes the decoder. Without a decoder, the decoder starts from random weights.
1155def train_semantic( 1156 name: str, 1157 model_type: str, 1158 train_loader: DataLoader, 1159 val_loader: DataLoader, 1160 num_classes: int = 3, 1161 n_epochs: int = 100, 1162 n_iterations: Optional[int] = None, 1163 early_stopping: Optional[int] = None, 1164 device: Optional[Union[str, torch.device]] = None, 1165 lr: float = 1e-5, 1166 save_root: Optional[Union[str, os.PathLike]] = None, 1167 save_every_kth_epoch: Optional[int] = None, 1168 overwrite_training: bool = True, 1169 peft_kwargs: Optional[Dict] = None, 1170 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1171 initial_features: int = 32, 1172 dice_weight: float = 0.5, 1173 mixed_precision: Optional[bool] = None, 1174 compile: Optional[List[str]] = None, 1175 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 1176) -> None: 1177 """Train SemanticSAM2 for semantic segmentation on 2d and 3d data. 1178 1179 Trains the UNETR3D-based SemanticSAM2 model with 1180 :class:`~micro_sam.v2.loss.semantic_loss.CustomCombinedLoss`, a weighted sum of a 1181 multi-class dice loss and a cross entropy loss. The targets are class ids, one per voxel; 1182 :func:`~micro_sam.v2.transforms.labels.semantic_labels` derives the three class layout of 1183 background, object boundary and object interior from an instance segmentation. 1184 1185 With 'num_classes=1' the model predicts a single foreground channel instead, trained with a 1186 weighted sum of a dice loss and a binary cross entropy loss on the sigmoid of the logits. 1187 The targets are then binary foreground masks. 1188 1189 Build the loaders for your own data with `micro_sam.v2.training.loaders.default_sam2_loader` 1190 and ``mode="semantic"``. 1191 1192 The encoder starts from the weights of `model_type`. For a model with a registered decoder, for example 1193 "hvit_t_cells", the decoder starts from it too, and only the output head for the classes is new. 1194 1195 Args: 1196 name: Checkpoint / log folder name. 1197 model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like 1198 "hvit_t_cells". 1199 train_loader: DataLoader yielding (x, y) tuples, with x of shape (B, 3, Z, Y, X) and the 1200 class ids in y of shape (B, 1, Z, Y, X). 2d data carries a singleton z axis. 1201 val_loader: Same format, used for validation. 1202 num_classes: The number of semantic classes, the background class included. 1203 One selects binary foreground segmentation with the dice and binary cross entropy loss. 1204 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1205 n_iterations: If set, train for this many iterations instead of epochs. 1206 early_stopping: Stop after this many epochs without improvement (None = off). 1207 device: Training device. Auto-selects if None. 1208 lr: Learning rate. 1209 save_root: Root directory for checkpoints and logs. 1210 save_every_kth_epoch: Save a separate checkpoint every k-th epoch. 1211 overwrite_training: Overwrite an existing checkpoint at the same path. 1212 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder during decoder training. 1213 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1214 scheduler, epoch and iteration. 1215 initial_features: Width of the convolutional decoder. The features per level are 1216 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1217 dice_weight: The weight of the dice loss in the combined loss. One selects dice only. 1218 Zero selects cross entropy only. 1219 mixed_precision: Whether to train with bfloat16 mixed precision. The weights and the optimizer state 1220 stay in float32. The hardware decides if None. 1221 compile: The parts to compile with ``torch.compile``, a subset of "encoder" and "decoder". 1222 Set 'TORCHINDUCTOR_CACHE_DIR' to a node-local folder: a cache on a shared filesystem blocks on its locks. 1223 checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It 1224 replaces the weights of `model_type`. Its decoder, or the decoder file next to it, initializes the 1225 decoder, but not the output head. 1226 """ 1227 import torch_em 1228 1229 device = get_device(device) 1230 model = _build_semantic_sam2_model( 1231 model_type, device, num_classes=num_classes, peft_kwargs=peft_kwargs, 1232 initial_features=initial_features, checkpoint_path=checkpoint_path, 1233 ) 1234 compile = _check_compile(compile) 1235 if "loss" in compile: 1236 raise ValueError("The semantic training compiles the 'encoder' and the 'decoder' only.") 1237 _configure_semantic_speed(model, compile) 1238 1239 if num_classes == 1: 1240 from torch_em.loss.dice import BCEDiceLossWithLogits, DiceLossWithLogits 1241 1242 if not 0.0 <= dice_weight <= 1.0: 1243 raise ValueError(f"The dice weight is '{dice_weight}'. It must lie between zero and one.") 1244 loss = BCEDiceLossWithLogits(alpha=dice_weight, beta=1.0 - dice_weight) 1245 metric = DiceLossWithLogits() 1246 else: 1247 loss = CustomCombinedLoss(num_classes=num_classes, dice_weight=dice_weight) 1248 metric = CustomDiceLoss(num_classes=num_classes) 1249 1250 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 1251 1252 trainer = torch_em.default_segmentation_trainer( 1253 name=name, 1254 model=model, 1255 train_loader=train_loader, 1256 val_loader=val_loader, 1257 learning_rate=lr, 1258 loss=loss, 1259 metric=metric, 1260 logger=UniSAM2Logger, 1261 log_image_interval=50, 1262 save_root=save_root, 1263 compile_model=False, 1264 scheduler_kwargs=scheduler_kwargs, 1265 optimizer_kwargs={"weight_decay": 0.1}, 1266 # The hardware decides the precision by default. SAM2 trains in bfloat16 only. 1267 mixed_precision=(training_autocast_dtype(device) is not None) if mixed_precision is None else mixed_precision, 1268 mixed_precision_dtype="bfloat16", 1269 device=device, 1270 early_stopping=early_stopping, 1271 trainer_class=UniSAM2Trainer, 1272 ) 1273 1274 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 1275 fit_kwargs["overwrite_training"] = overwrite_training 1276 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 1277 if save_every_kth_epoch is not None: 1278 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 1279 trainer.fit(**fit_kwargs)
Train SemanticSAM2 for semantic segmentation on 2d and 3d data.
Trains the UNETR3D-based SemanticSAM2 model with
~micro_sam.v2.loss.semantic_loss.CustomCombinedLoss, a weighted sum of a
multi-class dice loss and a cross entropy loss. The targets are class ids, one per voxel;
~micro_sam.v2.transforms.labels.semantic_labels() derives the three class layout of
background, object boundary and object interior from an instance segmentation.
With 'num_classes=1' the model predicts a single foreground channel instead, trained with a weighted sum of a dice loss and a binary cross entropy loss on the sigmoid of the logits. The targets are then binary foreground masks.
Build the loaders for your own data with micro_sam.v2.training.loaders.default_sam2_loader
and mode="semantic".
The encoder starts from the weights of model_type. For a model with a registered decoder, for example
"hvit_t_cells", the decoder starts from it too, and only the output head for the classes is new.
Arguments:
- name: Checkpoint / log folder name.
- model_type: The SAM2 model to start from, a backbone like "hvit_t" or a registered model like "hvit_t_cells".
- train_loader: DataLoader yielding (x, y) tuples, with x of shape (B, 3, Z, Y, X) and the class ids in y of shape (B, 1, Z, Y, X). 2d data carries a singleton z axis.
- val_loader: Same format, used for validation.
- num_classes: The number of semantic classes, the background class included. One selects binary foreground segmentation with the dice and binary cross entropy loss.
- n_epochs: Number of training epochs. Ignored if n_iterations is set.
- n_iterations: If set, train for this many iterations instead of epochs.
- early_stopping: Stop after this many epochs without improvement (None = off).
- device: Training device. Auto-selects if None.
- lr: Learning rate.
- save_root: Root directory for checkpoints and logs.
- save_every_kth_epoch: Save a separate checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder during decoder training. - load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration.
- initial_features: Width of the convolutional decoder. The features per level are 'initial_features * 2 ** i', so this scales the decoder parameters quadratically.
- dice_weight: The weight of the dice loss in the combined loss. One selects dice only. Zero selects cross entropy only.
- mixed_precision: Whether to train with bfloat16 mixed precision. The weights and the optimizer state stay in float32. The hardware decides if None.
- compile: The parts to compile with
torch.compile, a subset of "encoder" and "decoder". Set 'TORCHINDUCTOR_CACHE_DIR' to a node-local folder: a cache on a shared filesystem blocks on its locks. - checkpoint_path: The checkpoint to start from, for example the 'best.pt' of an earlier training. It
replaces the weights of
model_type. Its decoder, or the decoder file next to it, initializes the decoder, but not the output head.
1282def train_joint_sam2( 1283 name: str, 1284 model_type: str, 1285 input_path: Optional[str] = None, 1286 train_loader: Optional[DataLoader] = None, 1287 val_loader: Optional[DataLoader] = None, 1288 batch_size: int = 2, 1289 batch_size_2d: Optional[int] = None, 1290 z_slices: Optional[List[int]] = None, 1291 dataset_choice: str = "all", 1292 n_workers: int = 16, 1293 n_epochs: int = 100, 1294 n_iterations: Optional[int] = None, 1295 early_stopping: Optional[int] = None, 1296 max_num_objects: int = 20, 1297 checkpoint_path=None, 1298 freeze: Optional[List[str]] = None, 1299 peft_kwargs: Optional[Dict] = None, 1300 device: Optional[Union[str, torch.device]] = None, 1301 lr: float = 1e-5, 1302 save_root: Optional[Union[str, os.PathLike]] = None, 1303 scheduler_kwargs: Optional[Dict[str, Any]] = None, 1304 save_every_kth_epoch: Optional[int] = None, 1305 overwrite_training: bool = True, 1306 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1307 prob_to_use_pt_input: float = 0.5, 1308 prob_to_use_box_input: float = 0.5, 1309 num_frames_to_correct: int = 1, 1310 rand_frames_to_correct: bool = True, 1311 prob_to_sample_from_gt: float = 0.1, 1312 add_all_frames_to_correct_as_cond: bool = True, 1313 num_correction_pt_per_frame: int = 7, 1314 num_init_cond_frames: int = 2, 1315 clip_grad_norm: Optional[float] = None, 1316 largest_first: bool = False, 1317 bidirectional: bool = False, 1318 use_focal_loss: bool = False, 1319 focal_weight: float = 20.0, 1320 use_object_score_loss: bool = False, 1321 average_over_frames: bool = False, 1322 automatic_metric_weight: float = 0.25, 1323 initial_features: int = 32, 1324 distance_type: str = "geodesic", 1325 with_boundaries: bool = True, 1326 boundary_dice_weight: float = 1.0, 1327 label_trafo_threads: int = 1, 1328 compile: Optional[List[str]] = None, 1329) -> None: 1330 """Train SAM2Train and UniSAM2 jointly with a shared image encoder (single GPU). 1331 1332 Builds both the interactive (SAM2Train) and automatic (UniSAM2) models from 1333 ``model_type``, wires the shared image encoder, then interleaves the two 1334 losses in each training step. Both branches train on the same patches: the labels 1335 hold the instance ids for the interactive branch, followed by the targets of the 1336 automatic branch. 1337 1338 Train either on the generalist training data, with `input_path`, or on your own data, 1339 with `train_loader` and `val_loader` from 1340 `micro_sam.v2.training.loaders.default_sam2_loader` with ``mode="joint"``. 1341 1342 Args: 1343 name: Checkpoint / log folder name. 1344 model_type: SAM2 model to start from: a base backbone ("hvit_t", "hvit_s", "hvit_b", "hvit_l") 1345 or a finetuned model, e.g. "hvit_t_cells", whose decoder initializes the automatic branch. 1346 input_path: Root path to the generalist training data. Pass either this or the loaders. 1347 train_loader: The training loader for your own data. Pass it together with `val_loader`. 1348 val_loader: The validation loader for your own data. 1349 batch_size: Batch size for 3D groups (both branches). Only used with `input_path`. 1350 batch_size_2d: Batch size for 2D groups (both branches). Defaults to ``batch_size``. Only used with 1351 `input_path`. 1352 z_slices: Z-slice counts for 3D groups (default [8]). Only used with `input_path`. 1353 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. Only used with `input_path`. 1354 n_workers: DataLoader workers. Only used with `input_path`. 1355 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1356 n_iterations: If set, train for this many iterations instead of epochs. 1357 early_stopping: Stop after this many epochs without improvement (None = off). 1358 max_num_objects: Max objects per interactive step. 1359 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 1360 freeze: Component name prefixes to freeze (e.g. ["image_encoder"]). 1361 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 1362 device: Training device. Auto-selects if None. 1363 lr: Learning rate. 1364 save_root: Root directory for checkpoints and logs. 1365 scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10. 1366 save_every_kth_epoch: Save a checkpoint every k-th epoch. 1367 overwrite_training: Overwrite an existing checkpoint at the same path. 1368 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1369 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 1370 the pretrained SAM2 weights to start from. 1371 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 1372 prob_to_use_box_input: Conditional P(box) given point/box mode. 1373 num_frames_to_correct: Max frames per volume receiving correction clicks. 1374 rand_frames_to_correct: Randomly sample how many frames to correct. 1375 prob_to_sample_from_gt: P(correction click from GT vs error region). 1376 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 1377 num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7). 1378 num_init_cond_frames: Initial conditioning frames before the first correction round. 1379 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 1380 finetuning uses 0.1. 1381 bidirectional: Bidirectional propagation during training for 3D z-stacks. 1382 use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss. 1383 focal_weight: Weight of the focal mask loss when enabled. 1384 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss. 1385 average_over_frames: Average the interactive loss over frames instead of summing. 1386 automatic_metric_weight: Weight of the automatic metric in the combined validation 1387 metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, 1388 which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive 1389 Dice metric. Set to 0 to select purely on the interactive task. 1390 initial_features: Width of the convolutional decoder. The features per level are 1391 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1392 distance_type: Directed distance target for the automatic branch. "geodesic" uses the 1393 geodesic hybrid field around each object's center, "directed" the euclidean vector 1394 to the nearest boundary. Only used with `input_path`: `default_sam2_loader` uses "geodesic". 1395 with_boundaries: The flag to add a fifth automatic output for the full object-boundary target. 1396 By default True, which matches the decoders of the registered models. 1397 It must match the targets of the loaders, and the decoder of a finetuned `model_type`. 1398 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 1399 label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel 1400 in the distance transform. Only pays off when the node has more cores than loader workers. 1401 Only used with `input_path`. 1402 compile: The parts to compile with ``torch.compile``. "encoder" is the shared image encoder, 1403 "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels 1404 of the interactive loss. The default compiles nothing. 1405 """ 1406 from micro_sam.v2.datasets.generalist_loader import _build_joint_datasets, _prepare_data_loader 1407 from micro_sam.v2.models.util import UniSAM2 1408 1409 have_loaders = train_loader is not None or val_loader is not None 1410 if (input_path is not None) == have_loaders: 1411 raise ValueError("Pass either 'input_path' or both 'train_loader' and 'val_loader'.") 1412 if have_loaders and (train_loader is None or val_loader is None): 1413 raise ValueError("Pass both 'train_loader' and 'val_loader'.") 1414 1415 device = get_device(device) 1416 1417 if input_path is not None: 1418 if z_slices is None: 1419 z_slices = [8] 1420 if batch_size_2d is None: 1421 batch_size_2d = batch_size 1422 train_ds, val_ds = _build_joint_datasets( 1423 input_path, z_slices, dataset_choice, distance_type, 1424 with_boundaries=with_boundaries, label_trafo_threads=label_trafo_threads, 1425 ) 1426 bpg = {2: batch_size_2d} if batch_size_2d != batch_size else None 1427 train_loader = _prepare_data_loader( 1428 train_ds, batch_size=batch_size, shuffle=True, 1429 batch_size_per_group=bpg, num_workers=n_workers, 1430 ) 1431 val_loader = _prepare_data_loader( 1432 val_ds, batch_size=batch_size, shuffle=False, 1433 batch_size_per_group=bpg, num_workers=n_workers, deterministic=True, 1434 ) 1435 1436 sam2_model = get_sam2_train_model( 1437 model_type=model_type, device=device, 1438 checkpoint_path=checkpoint_path, freeze=freeze, peft_kwargs=peft_kwargs, 1439 prob_to_use_pt_input=prob_to_use_pt_input, 1440 prob_to_use_box_input=prob_to_use_box_input, 1441 num_frames_to_correct=num_frames_to_correct, 1442 rand_frames_to_correct=rand_frames_to_correct, 1443 prob_to_sample_from_gt=prob_to_sample_from_gt, 1444 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 1445 num_correction_pt_per_frame=num_correction_pt_per_frame, 1446 num_init_cond_frames_for_train=num_init_cond_frames, 1447 bidirectional=bidirectional, 1448 ) 1449 unetr = UniSAM2( 1450 encoder=sam2_model.image_encoder, output_channels=4 + int(with_boundaries), 1451 initial_features=initial_features, device=device, 1452 perform_range_checks=False, # The trainer checks the input range once. 1453 ) 1454 _init_start_decoder(unetr, model_type, checkpoint_path) 1455 compile = _check_compile(compile) 1456 _configure_joint_speed(sam2_model, unetr, compile) 1457 1458 interactive_loss = CustomSAM2Loss( 1459 use_focal_loss=use_focal_loss, focal_weight=focal_weight, 1460 use_object_score_loss=use_object_score_loss, average_over_frames=average_over_frames, 1461 compile_kernels="loss" in compile, 1462 ) 1463 automatic_loss = DirectedDistanceLoss( 1464 mask_distances_in_bg=True, with_boundaries=with_boundaries, boundary_dice_weight=boundary_dice_weight, 1465 ) 1466 convert_inputs = ConvertToSam2VideoBatch(max_num_objects=max_num_objects, largest_first=largest_first) 1467 1468 if scheduler_kwargs is None: 1469 scheduler_kwargs = {"mode": "min", "factor": 0.9, "patience": 10} 1470 sam2_params = list(sam2_model.parameters()) 1471 unetr_decoder_params = [p for n, p in unetr.named_parameters() if not n.startswith("encoder")] 1472 # The fused AdamW kernel exists for CUDA only. 1473 optimizer = torch.optim.AdamW( 1474 sam2_params + unetr_decoder_params, lr=lr, fused=torch.device(device).type == "cuda" 1475 ) 1476 scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, **scheduler_kwargs) 1477 1478 trainer = JointSam2Trainer( 1479 name=name, 1480 model=sam2_model, 1481 train_loader=train_loader, 1482 val_loader=val_loader, 1483 optimizer=optimizer, 1484 device=device, 1485 lr_scheduler=scheduler, 1486 logger=JointSam2Logger, 1487 log_image_interval=100, 1488 compile_model=False, 1489 early_stopping=early_stopping, 1490 save_root=save_root, 1491 unetr=unetr, 1492 convert_inputs=convert_inputs, 1493 interactive_loss=interactive_loss, 1494 automatic_loss=automatic_loss, 1495 automatic_metric_weight=automatic_metric_weight, 1496 clip_grad_norm=clip_grad_norm, 1497 ) 1498 1499 fit_kwargs = {"epochs": n_epochs} if n_iterations is None else {"iterations": n_iterations} 1500 fit_kwargs["overwrite_training"] = overwrite_training 1501 fit_kwargs["load_from_checkpoint"] = load_from_checkpoint 1502 if save_every_kth_epoch is not None: 1503 fit_kwargs["save_every_kth_epoch"] = save_every_kth_epoch 1504 trainer.fit(**fit_kwargs)
Train SAM2Train and UniSAM2 jointly with a shared image encoder (single GPU).
Builds both the interactive (SAM2Train) and automatic (UniSAM2) models from
model_type, wires the shared image encoder, then interleaves the two
losses in each training step. Both branches train on the same patches: the labels
hold the instance ids for the interactive branch, followed by the targets of the
automatic branch.
Train either on the generalist training data, with input_path, or on your own data,
with train_loader and val_loader from
micro_sam.v2.training.loaders.default_sam2_loader with mode="joint".
Arguments:
- name: Checkpoint / log folder name.
- model_type: SAM2 model to start from: a base backbone ("hvit_t", "hvit_s", "hvit_b", "hvit_l") or a finetuned model, e.g. "hvit_t_cells", whose decoder initializes the automatic branch.
- input_path: Root path to the generalist training data. Pass either this or the loaders.
- train_loader: The training loader for your own data. Pass it together with
val_loader. - val_loader: The validation loader for your own data.
- batch_size: Batch size for 3D groups (both branches). Only used with
input_path. - batch_size_2d: Batch size for 2D groups (both branches). Defaults to
batch_size. Only used withinput_path. - z_slices: Z-slice counts for 3D groups (default [8]). Only used with
input_path. - dataset_choice:
"lm","em","hp", or"all". Only used withinput_path. - n_workers: DataLoader workers. Only used with
input_path. - n_epochs: Number of training epochs. Ignored if n_iterations is set.
- n_iterations: If set, train for this many iterations instead of epochs.
- early_stopping: Stop after this many epochs without improvement (None = off).
- max_num_objects: Max objects per interactive step.
- checkpoint_path: SAM2 checkpoint path. Downloads default if None.
- freeze: Component name prefixes to freeze (e.g. ["image_encoder"]).
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method. - device: Training device. Auto-selects if None.
- lr: Learning rate.
- save_root: Root directory for checkpoints and logs.
- scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10.
- save_every_kth_epoch: Save a checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation).
- prob_to_use_box_input: Conditional P(box) given point/box mode.
- num_frames_to_correct: Max frames per volume receiving correction clicks.
- rand_frames_to_correct: Randomly sample how many frames to correct.
- prob_to_sample_from_gt: P(correction click from GT vs error region).
- add_all_frames_to_correct_as_cond: Add corrected frames as cond frames.
- num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7).
- num_init_cond_frames: Initial conditioning frames before the first correction round.
- clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own finetuning uses 0.1.
- bidirectional: Bidirectional propagation during training for 3D z-stacks.
- use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss.
- focal_weight: Weight of the focal mask loss when enabled.
- use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss.
- average_over_frames: Average the interactive loss over frames instead of summing.
- automatic_metric_weight: Weight of the automatic metric in the combined validation metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive Dice metric. Set to 0 to select purely on the interactive task.
- initial_features: Width of the convolutional decoder. The features per level are 'initial_features * 2 ** i', so this scales the decoder parameters quadratically.
- distance_type: Directed distance target for the automatic branch. "geodesic" uses the
geodesic hybrid field around each object's center, "directed" the euclidean vector
to the nearest boundary. Only used with
input_path:default_sam2_loaderuses "geodesic". - with_boundaries: The flag to add a fifth automatic output for the full object-boundary target.
By default True, which matches the decoders of the registered models.
It must match the targets of the loaders, and the decoder of a finetuned
model_type. - boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only.
- label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel
in the distance transform. Only pays off when the node has more cores than loader workers.
Only used with
input_path. - compile: The parts to compile with
torch.compile. "encoder" is the shared image encoder, "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels of the interactive loss. The default compiles nothing.
1682def train_joint_sam2_multi_gpu( 1683 name: str, 1684 model_type: str, 1685 input_path: str, 1686 batch_size: int = 2, 1687 batch_size_2d: Optional[int] = None, 1688 z_slices: Optional[List[int]] = None, 1689 dataset_choice: str = "all", 1690 n_workers: int = 16, 1691 n_epochs: int = 100, 1692 n_iterations: Optional[int] = None, 1693 early_stopping: Optional[int] = None, 1694 max_num_objects: int = 20, 1695 checkpoint_path=None, 1696 freeze: Optional[List[str]] = None, 1697 peft_kwargs: Optional[Dict] = None, 1698 lr: float = 1e-5, 1699 save_root=None, 1700 scheduler_kwargs: Optional[Dict[str, Any]] = None, 1701 save_every_kth_epoch: Optional[int] = None, 1702 overwrite_training: bool = True, 1703 load_from_checkpoint: Optional[Union[str, os.PathLike]] = None, 1704 prob_to_use_pt_input: float = 0.5, 1705 prob_to_use_box_input: float = 0.5, 1706 num_frames_to_correct: int = 1, 1707 rand_frames_to_correct: bool = True, 1708 prob_to_sample_from_gt: float = 0.1, 1709 add_all_frames_to_correct_as_cond: bool = True, 1710 num_correction_pt_per_frame: int = 7, 1711 num_init_cond_frames: int = 2, 1712 clip_grad_norm: Optional[float] = None, 1713 find_unused_parameters: bool = True, 1714 largest_first: bool = False, 1715 bidirectional: bool = False, 1716 use_focal_loss: bool = False, 1717 focal_weight: float = 20.0, 1718 use_object_score_loss: bool = False, 1719 average_over_frames: bool = False, 1720 automatic_metric_weight: float = 0.25, 1721 initial_features: int = 32, 1722 distance_type: str = "geodesic", 1723 with_boundaries: bool = True, 1724 boundary_dice_weight: float = 1.0, 1725 label_trafo_threads: int = 1, 1726 compile: Optional[List[str]] = None, 1727) -> None: 1728 """Train SAM2Train and UniSAM2 jointly across multiple GPUs with DDP. 1729 1730 Must be launched via ``torchrun`` - one process per GPU, on one or more nodes. 1731 Example (single node): ``torchrun --nproc_per_node=4 train_joint.py`` 1732 Example (multi-node): ``srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_joint.py`` 1733 1734 Both the interactive and automatic datasets are constructed independently in 1735 each rank. Only the SAM2 model is DDP-wrapped; UniSAM2 decoder gradients are 1736 manually all_reduced after each backward so the shared encoder is not double-reduced. 1737 1738 Args: 1739 name: Checkpoint / log folder name. 1740 model_type: SAM2 encoder variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l". 1741 input_path: Root path to the generalist training data. 1742 batch_size: Batch size per GPU for 3D groups (both branches). 1743 batch_size_2d: Batch size per GPU for 2D groups. Defaults to ``batch_size``. 1744 z_slices: Z-slice counts for 3D groups (default [8]). 1745 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, or ``"all"``. 1746 n_workers: DataLoader workers per GPU. 1747 n_epochs: Number of training epochs. Ignored if n_iterations is set. 1748 n_iterations: If set, train for this many iterations instead of epochs. 1749 early_stopping: Stop after this many epochs without improvement. 1750 max_num_objects: Max objects per interactive step. 1751 checkpoint_path: SAM2 checkpoint path. Downloads default if None. 1752 freeze: Component name prefixes to freeze (e.g. ["image_encoder"]). 1753 peft_kwargs: The arguments for `PEFT_Sam2`. These arguments freeze the encoder and apply the PEFT method. 1754 lr: Learning rate. 1755 save_root: Root directory for checkpoints and logs. 1756 scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10. 1757 save_every_kth_epoch: Save a checkpoint every k-th epoch. 1758 overwrite_training: Overwrite an existing checkpoint at the same path. 1759 load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, 1760 scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies 1761 the pretrained SAM2 weights to start from. 1762 prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation). 1763 prob_to_use_box_input: Conditional P(box) given point/box mode. 1764 num_frames_to_correct: Max frames per volume receiving correction clicks. 1765 rand_frames_to_correct: Randomly sample how many frames to correct. 1766 prob_to_sample_from_gt: P(correction click from GT vs error region). 1767 add_all_frames_to_correct_as_cond: Add corrected frames as cond frames. 1768 num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7). 1769 num_init_cond_frames: Initial conditioning frames before the first correction round. 1770 clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own 1771 finetuning uses 0.1. 1772 find_unused_parameters: Passed to DistributedDataParallel. 1773 bidirectional: Bidirectional propagation during training for 3D z-stacks. 1774 use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss. 1775 focal_weight: Weight of the focal mask loss when enabled. 1776 use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss. 1777 average_over_frames: Average the interactive loss over frames instead of summing. 1778 automatic_metric_weight: Weight of the automatic metric in the combined validation 1779 metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, 1780 which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive 1781 Dice metric. Set to 0 to select purely on the interactive task. 1782 initial_features: Width of the convolutional decoder. The features per level are 1783 'initial_features * 2 ** i', so this scales the decoder parameters quadratically. 1784 distance_type: Directed distance target for the automatic branch. "geodesic" uses the 1785 geodesic hybrid field around each object's center, "directed" the euclidean vector 1786 to the nearest boundary. 1787 with_boundaries: The flag to add a fifth automatic output for the full object-boundary target. 1788 By default True, which matches the decoders of the registered models. 1789 boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only. 1790 label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel 1791 in the distance transform. Only pays off when the node has more cores than loader workers. 1792 compile: The parts to compile with ``torch.compile``. "encoder" is the shared image encoder, 1793 "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels 1794 of the interactive loss. The default compiles nothing. 1795 """ 1796 if z_slices is None: 1797 z_slices = [8] 1798 if batch_size_2d is None: 1799 batch_size_2d = batch_size 1800 1801 if "RANK" not in os.environ: 1802 raise RuntimeError( 1803 "train_joint_sam2_multi_gpu must be launched via torchrun, not called directly. " 1804 "Example: torchrun --nproc_per_node=4 train_joint.py" 1805 ) 1806 rank = int(os.environ["RANK"]) 1807 local_rank = int(os.environ["LOCAL_RANK"]) 1808 1809 _train_joint_rank( 1810 rank=rank, 1811 local_rank=local_rank, 1812 name=name, 1813 model_type=model_type, 1814 input_path=input_path, 1815 n_epochs=n_epochs, 1816 n_iterations=n_iterations, 1817 early_stopping=early_stopping, 1818 max_num_objects=max_num_objects, 1819 checkpoint_path=checkpoint_path, 1820 freeze=freeze, 1821 peft_kwargs=peft_kwargs, 1822 lr=lr, 1823 save_root=save_root, 1824 scheduler_kwargs=scheduler_kwargs, 1825 save_every_kth_epoch=save_every_kth_epoch, 1826 overwrite_training=overwrite_training, 1827 load_from_checkpoint=load_from_checkpoint, 1828 prob_to_use_pt_input=prob_to_use_pt_input, 1829 prob_to_use_box_input=prob_to_use_box_input, 1830 num_frames_to_correct=num_frames_to_correct, 1831 rand_frames_to_correct=rand_frames_to_correct, 1832 prob_to_sample_from_gt=prob_to_sample_from_gt, 1833 add_all_frames_to_correct_as_cond=add_all_frames_to_correct_as_cond, 1834 num_correction_pt_per_frame=num_correction_pt_per_frame, 1835 num_init_cond_frames=num_init_cond_frames, 1836 clip_grad_norm=clip_grad_norm, 1837 batch_size=batch_size, 1838 batch_size_2d=batch_size_2d, 1839 z_slices=z_slices, 1840 dataset_choice=dataset_choice, 1841 n_workers=n_workers, 1842 find_unused_parameters=find_unused_parameters, 1843 largest_first=largest_first, 1844 bidirectional=bidirectional, 1845 use_focal_loss=use_focal_loss, 1846 focal_weight=focal_weight, 1847 use_object_score_loss=use_object_score_loss, 1848 average_over_frames=average_over_frames, 1849 automatic_metric_weight=automatic_metric_weight, 1850 initial_features=initial_features, 1851 distance_type=distance_type, 1852 with_boundaries=with_boundaries, 1853 boundary_dice_weight=boundary_dice_weight, 1854 label_trafo_threads=label_trafo_threads, 1855 compile=compile, 1856 )
Train SAM2Train and UniSAM2 jointly across multiple GPUs with DDP.
Must be launched via torchrun - one process per GPU, on one or more nodes.
Example (single node): torchrun --nproc_per_node=4 train_joint.py
Example (multi-node): srun torchrun --nnodes=$SLURM_NNODES --nproc_per_node=4 train_joint.py
Both the interactive and automatic datasets are constructed independently in each rank. Only the SAM2 model is DDP-wrapped; UniSAM2 decoder gradients are manually all_reduced after each backward so the shared encoder is not double-reduced.
Arguments:
- name: Checkpoint / log folder name.
- model_type: SAM2 encoder variant - one of "hvit_t", "hvit_s", "hvit_b", "hvit_l".
- input_path: Root path to the generalist training data.
- batch_size: Batch size per GPU for 3D groups (both branches).
- batch_size_2d: Batch size per GPU for 2D groups. Defaults to
batch_size. - z_slices: Z-slice counts for 3D groups (default [8]).
- dataset_choice:
"lm","em","hp", or"all". - n_workers: DataLoader workers per GPU.
- n_epochs: Number of training epochs. Ignored if n_iterations is set.
- n_iterations: If set, train for this many iterations instead of epochs.
- early_stopping: Stop after this many epochs without improvement.
- max_num_objects: Max objects per interactive step.
- checkpoint_path: SAM2 checkpoint path. Downloads default if None.
- freeze: Component name prefixes to freeze (e.g. ["image_encoder"]).
- peft_kwargs: The arguments for
PEFT_Sam2. These arguments freeze the encoder and apply the PEFT method. - lr: Learning rate.
- save_root: Root directory for checkpoints and logs.
- scheduler_kwargs: ReduceLROnPlateau kwargs. Defaults to patience=10.
- save_every_kth_epoch: Save a checkpoint every k-th epoch.
- overwrite_training: Overwrite an existing checkpoint at the same path.
- load_from_checkpoint: Trainer checkpoint to resume from, restoring the model, optimizer, scheduler, epoch and iteration. This is distinct from checkpoint_path, which supplies the pretrained SAM2 weights to start from.
- prob_to_use_pt_input: P(point/box prompt) vs P(mask propagation).
- prob_to_use_box_input: Conditional P(box) given point/box mode.
- num_frames_to_correct: Max frames per volume receiving correction clicks.
- rand_frames_to_correct: Randomly sample how many frames to correct.
- prob_to_sample_from_gt: P(correction click from GT vs error region).
- add_all_frames_to_correct_as_cond: Add corrected frames as cond frames.
- num_correction_pt_per_frame: Correction clicks per frame per round (SAM2 default 7).
- num_init_cond_frames: Initial conditioning frames before the first correction round.
- clip_grad_norm: Max gradient norm for clipping. Disabled by default; SAM2's own finetuning uses 0.1.
- find_unused_parameters: Passed to DistributedDataParallel.
- bidirectional: Bidirectional propagation during training for 3D z-stacks.
- use_focal_loss: Add SAM2's focal mask loss on top of Dice in CustomSAM2Loss.
- focal_weight: Weight of the focal mask loss when enabled.
- use_object_score_loss: Supervise SAM2's object-presence score with a BCE loss.
- average_over_frames: Average the interactive loss over frames instead of summing.
- automatic_metric_weight: Weight of the automatic metric in the combined validation metric used for checkpointing, LR scheduling and early stopping. Defaults to 1/4, which puts DirectedDistanceLoss's 4 summed terms on the scale of the interactive Dice metric. Set to 0 to select purely on the interactive task.
- initial_features: Width of the convolutional decoder. The features per level are 'initial_features * 2 ** i', so this scales the decoder parameters quadratically.
- distance_type: Directed distance target for the automatic branch. "geodesic" uses the geodesic hybrid field around each object's center, "directed" the euclidean vector to the nearest boundary.
- with_boundaries: The flag to add a fifth automatic output for the full object-boundary target. By default True, which matches the decoders of the registered models.
- boundary_dice_weight: The Dice weight for the boundary channel. One selects Dice only. Zero selects BCE only.
- label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel in the distance transform. Only pays off when the node has more cores than loader workers.
- compile: The parts to compile with
torch.compile. "encoder" is the shared image encoder, "decoder" are the blocks of the UNETR decoder and "loss" are the Dice and focal kernels of the interactive loss. The default compiles nothing.