synapse_net.training.domain_adaptation
1import os 2import tempfile 3from glob import glob 4from pathlib import Path 5from typing import Optional, Tuple 6 7from sklearn.model_selection import train_test_split 8 9import mrcfile 10import torch 11import torch_em 12import torch_em.self_training as self_training 13from elf.io import open_file 14 15from torch_em.transform.invertible_augmentations import MeanTeacherAugmenters, DEFAULT_WEAK_AUGMENTATIONS 16 17from .dataloaders import get_supervised_loader, get_unsupervised_loader, _determine_ndim 18from .models import get_raw_transform, _check_backbone, _get_model 19from .supervised_training import _derive_key_from_files 20from ..inference.inference import ( 21 get_model_path, compute_scale_from_voxel_size, get_available_models, get_model_training_patch_shape 22) 23from ..inference.util import _restore_legacy_attributes, _Scaler 24 25 26def mean_teacher_adaptation( 27 name: str, 28 unsupervised_train_paths: Tuple[str], 29 unsupervised_val_paths: Tuple[str], 30 patch_shape: Tuple[int, int, int], 31 save_root: Optional[str] = None, 32 source_checkpoint: Optional[str] = None, 33 supervised_train_paths: Optional[Tuple[str]] = None, 34 supervised_val_paths: Optional[Tuple[str]] = None, 35 confidence_threshold: float = 0.9, 36 raw_key: str = "raw", 37 raw_key_supervised: str = "raw", 38 label_key: Optional[str] = None, 39 batch_size: int = 1, 40 lr: float = 1e-4, 41 n_iterations: int = int(1e4), 42 n_samples_train: Optional[int] = None, 43 n_samples_val: Optional[int] = None, 44 train_mask_paths: Optional[Tuple[str]] = None, 45 val_mask_paths: Optional[Tuple[str]] = None, 46 sample_mask_key: Optional[str] = None, 47 unsupervised_sampler: Optional[callable] = None, 48 supervised_sampler: Optional[callable] = None, 49 backbone: Optional[str] = None, 50 model_type: Optional[str] = None, 51 encoder_checkpoint: Optional[str] = None, 52 aug_dict: Optional[dict] = None, 53 separate_backward: bool = False, 54 check: bool = False, 55) -> None: 56 """Run domain adaptation to transfer a network trained on a source domain for a supervised 57 segmentation task to perform this task on a different target domain. 58 59 We support different domain adaptation settings: 60 - unsupervised domain adaptation: the default mode when 'supervised_train_paths' and 61 'supervised_val_paths' are not given. 62 - semi-supervised domain adaptation: domain adaptation on unlabeled and labeled data, 63 when 'supervised_train_paths' and 'supervised_val_paths' are given. 64 65 Args: 66 name: The name for the checkpoint to be trained. 67 unsupervised_train_paths: Filepaths to the hdf5 files or similar file formats 68 for the training data in the target domain. 69 This training data is used for unsupervised learning, so it does not require labels. 70 unsupervised_val_paths: Filepaths to the hdf5 files or similar file formats 71 for the validation data in the target domain. 72 This validation data is used for unsupervised learning, so it does not require labels. 73 patch_shape: The patch shape used for a training example. 74 In order to run 2d training pass a patch shape with a singleton in the z-axis, 75 e.g. 'patch_shape = [1, 512, 512]'. 76 save_root: Folder where the checkpoint will be saved. 77 source_checkpoint: Checkpoint to the initial model trained on the source domain. 78 This is used to initialize the teacher model. 79 If the checkpoint is not given, then both student and teacher model are initialized 80 from scratch. In this case `supervised_train_paths` and `supervised_val_paths` have to 81 be given in order to provide training data from the source domain. 82 supervised_train_paths: Filepaths to the hdf5 files for the training data in the source domain. 83 This training data is optional. If given, it is used for supervised learning and requires labels. 84 supervised_val_paths: Filepaths to the hdf5 files for the validation data in the source domain. 85 This validation data is optional. If given, it is used for supervised learning and requires labels. 86 confidence_threshold: The threshold for filtering data in the unsupervised loss. 87 The label filtering is done based on the uncertainty of network predictions, and only 88 the data with higher certainty than this threshold is used for training. 89 raw_key: The key that holds the raw data inside of the hdf5 or similar files. 90 raw_key_supervised: The key that holds the raw data inside of the hdf5 files for supervised learning. 91 label_key: The key that holds the labels inside of the hdf5 files for supervised learning. 92 This is only required if `supervised_train_paths` and `supervised_val_paths` are given. 93 batch_size: The batch size for training. 94 lr: The initial learning rate. 95 n_iterations: The number of iterations to train for. 96 n_samples_train: The number of train samples per epoch. By default this will be estimated 97 based on the patch_shape and size of the volumes used for training. 98 n_samples_val: The number of val samples per epoch. By default this will be estimated 99 based on the patch_shape and size of the volumes used for validation. 100 train_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for training. 101 val_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for validation. 102 sample_mask_key: The key to the sample mask dataset inside each file. 103 unsupervised_sampler: Sampler to accept or reject patches for the unsupervised data stream. 104 supervised_sampler: Sampler to accept or reject patches for the supervised data stream. 105 Pass `False` to disable. 106 backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR), 107 or "cryosiam" (3D CNN encoder of a CryoZooUNet). 108 The ViT backbones must be set together with `model_type`. 109 model_type: Model type for the selected ViT `backbone` model family, for example "vit_b" or 110 "vit_b_em_organelles" for "sam". 111 encoder_checkpoint: Path to the pretrained encoder weights for `backbone`. 112 By default they are fetched for `backbone` and `model_type`. 113 aug_dict: The augmentations for the teacher and the student, with keys "intensity" and "geometrical". 114 Defaults to Gaussian blur and noise, plus random flips and 90-degree rotations. 115 The noise is scaled with `clip_max` to match the range of `raw_transform`. 116 separate_backward: Whether to backpropagate each loss term separately to reduce peak memory. 117 check: Whether to check the training and validation loaders instead of running training. 118 """ 119 assert (supervised_train_paths is None) == (supervised_val_paths is None) 120 _check_backbone(backbone, model_type, patch_shape) 121 is_2d, _ = _determine_ndim(patch_shape) 122 123 if source_checkpoint is None: 124 # training from scratch only makes sense if we have supervised training data 125 # that's why we have the assertion here. 126 assert supervised_train_paths is not None 127 print("Mean teacher training from scratch (AdaMT).") 128 model = _get_model( 129 patch_shape, out_channels=2, backbone=backbone, 130 model_type=model_type, encoder_checkpoint=encoder_checkpoint, 131 ) 132 reinit_teacher = True 133 else: 134 print("Mean teacher training initialized from source model:", source_checkpoint) 135 if os.path.isdir(source_checkpoint): 136 model = torch_em.util.load_model(source_checkpoint) 137 else: 138 model = _restore_legacy_attributes(torch.load(source_checkpoint, weights_only=False)) 139 reinit_teacher = False 140 141 optimizer = torch.optim.Adam(model.parameters(), lr=lr) 142 scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.5, patience=5) 143 144 # self training functionality 145 pseudo_labeler = self_training.DefaultPseudoLabeler(confidence_threshold=confidence_threshold) 146 loss = self_training.SelfTrainingLossWithInvertibleAugmentations() 147 loss_and_metric = self_training.SelfTrainingLossAndMetricWithInvertibleAugmentations() 148 149 raw_transform, clip_max = get_raw_transform(backbone) 150 151 ndim = 2 if is_2d else 3 152 if aug_dict is None: 153 aug_dict = { 154 "intensity": { 155 "RandomGaussianBlur": {"kernel_size": (19, 19), "sigma": (0.1, 3.0)}, 156 "RandomGaussianNoise": {"mean": 0.0, "std": 0.1 if clip_max is None else 0.015 * clip_max}, 157 }, 158 "geometrical": DEFAULT_WEAK_AUGMENTATIONS["geometrical"], 159 } 160 augmenters = MeanTeacherAugmenters(ndim=ndim, clip_max=clip_max, aug_dict=aug_dict) 161 162 unsupervised_train_loader = get_unsupervised_loader( 163 data_paths=unsupervised_train_paths, 164 raw_key=raw_key, 165 patch_shape=patch_shape, 166 batch_size=batch_size, 167 n_samples=n_samples_train, 168 sample_mask_paths=train_mask_paths, 169 sample_mask_key=sample_mask_key, 170 sampler=unsupervised_sampler, 171 raw_transform=raw_transform, 172 ) 173 unsupervised_val_loader = get_unsupervised_loader( 174 data_paths=unsupervised_val_paths, 175 raw_key=raw_key, 176 patch_shape=patch_shape, 177 batch_size=batch_size, 178 n_samples=n_samples_val, 179 sample_mask_paths=val_mask_paths, 180 sample_mask_key=sample_mask_key, 181 sampler=unsupervised_sampler, 182 raw_transform=raw_transform, 183 ) 184 185 if supervised_train_paths is not None: 186 assert label_key is not None 187 supervised_train_loader = get_supervised_loader( 188 supervised_train_paths, raw_key_supervised, label_key, 189 patch_shape, batch_size, n_samples=n_samples_train, 190 sampler=supervised_sampler, raw_transform=raw_transform, 191 ) 192 supervised_val_loader = get_supervised_loader( 193 supervised_val_paths, raw_key_supervised, label_key, 194 patch_shape, batch_size, n_samples=n_samples_val, 195 sampler=supervised_sampler, raw_transform=raw_transform, 196 ) 197 else: 198 supervised_train_loader = None 199 supervised_val_loader = None 200 201 if check: 202 from torch_em.util.debug import check_loader 203 check_loader(unsupervised_train_loader, n_samples=4) 204 check_loader(unsupervised_val_loader, n_samples=4) 205 if supervised_train_loader is not None: 206 check_loader(supervised_train_loader, n_samples=4) 207 check_loader(supervised_val_loader, n_samples=4) 208 return 209 210 device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 211 trainer = self_training.MeanTeacherTrainerWithInvertibleAugmentations( 212 name=name, 213 model=model, 214 optimizer=optimizer, 215 lr_scheduler=scheduler, 216 pseudo_labeler=pseudo_labeler, 217 unsupervised_loss=loss, 218 unsupervised_loss_and_metric=loss_and_metric, 219 supervised_train_loader=supervised_train_loader, 220 unsupervised_train_loader=unsupervised_train_loader, 221 supervised_val_loader=supervised_val_loader, 222 unsupervised_val_loader=unsupervised_val_loader, 223 supervised_loss=loss, 224 supervised_loss_and_metric=loss_and_metric, 225 logger=self_training.SelfTrainingTensorboardLogger, 226 # On the CPU, mixed precision uses bfloat16. It is very slow without hardware support, 227 # and the kornia augmentations do not accept it. 228 mixed_precision=device.type == "cuda", 229 log_image_interval=100, 230 compile_model=False, 231 device=device, 232 reinit_teacher=reinit_teacher, 233 save_root=save_root, 234 augmenter=augmenters, 235 separate_backward=separate_backward, 236 ) 237 trainer.fit(n_iterations) 238 239 240def _get_paths(input_folder, pattern, resize_training_data, model_name, tmp_dir, val_fraction): 241 files = sorted(glob(os.path.join(input_folder, "**", pattern), recursive=True)) 242 if len(files) == 0: 243 raise ValueError(f"Could not load any files from {input_folder} with pattern {pattern}") 244 245 # Heuristic: if we have less then 4 files then we crop a part of the volumes for validation. 246 # And resave the volumes. 247 resave_val_crops = len(files) < 4 248 249 # We only resave the data if we resave val crops or resize the training data 250 resave_data = resave_val_crops or resize_training_data 251 if not resave_data: 252 train_paths, val_paths = train_test_split(files, test_size=val_fraction) 253 return train_paths, val_paths 254 255 train_paths, val_paths = [], [] 256 for file_path in files: 257 file_name = os.path.basename(file_path) 258 data = open_file(file_path, mode="r")["data"][:] 259 260 if resize_training_data: 261 with mrcfile.open(file_path) as f: 262 voxel_size = f.voxel_size 263 voxel_size = {ax: vox_size / 10.0 for ax, vox_size in zip("xyz", voxel_size.item())} 264 scale = compute_scale_from_voxel_size(voxel_size, model_name) 265 scaler = _Scaler(scale, verbose=False) 266 data = scaler.scale_input(data) 267 268 if resave_val_crops: 269 n_slices = data.shape[0] 270 val_slice = int((1.0 - val_fraction) * n_slices) 271 train_data, val_data = data[:val_slice], data[val_slice:] 272 273 train_path = os.path.join(tmp_dir, Path(file_name).with_suffix(".h5")).replace(".h5", "_train.h5") 274 with open_file(train_path, mode="w") as f: 275 f.create_dataset("data", data=train_data, compression="lzf") 276 train_paths.append(train_path) 277 278 val_path = os.path.join(tmp_dir, Path(file_name).with_suffix(".h5")).replace(".h5", "_val.h5") 279 with open_file(val_path, mode="w") as f: 280 f.create_dataset("data", data=val_data, compression="lzf") 281 val_paths.append(val_path) 282 283 else: 284 output_path = os.path.join(tmp_dir, Path(file_name).with_suffix(".h5")) 285 with open_file(output_path, mode="w") as f: 286 f.create_dataset("data", data=data, compression="lzf") 287 train_paths.append(output_path) 288 289 if not resave_val_crops: 290 train_paths, val_paths = train_test_split(train_paths, test_size=val_fraction) 291 292 return train_paths, val_paths 293 294 295def _parse_patch_shape(patch_shape, model_name): 296 if patch_shape is None: 297 shape = get_model_training_patch_shape(model_name) 298 patch_shape = [shape.get("z", 1), shape["y"], shape["x"]] 299 return patch_shape 300 301 302def _resolve_source_checkpoint(source_model, source_checkpoint): 303 if source_checkpoint is None: 304 return get_model_path(source_model) 305 if not os.path.exists(source_checkpoint): 306 raise ValueError(f"The source checkpoint does not exist: {source_checkpoint}") 307 return source_checkpoint 308 309 310def main(): 311 """@private 312 """ 313 import argparse 314 315 parser = argparse.ArgumentParser( 316 description="Adapt a model to data from a different domain using unsupervised domain adaptation.\n\n" 317 "You can use this function to adapt the SynapseNet model for vesicle segmentation like this:\n" 318 "synapse_net.run_domain_adaptation -n adapted_model -i /path/to/data --file_pattern *.mrc --source_model vesicles_3d\n" # noqa 319 "The trained model will be saved in the folder 'checkpoints/adapted_model' (or whichever name you pass to the '-n' argument)." # noqa 320 "You can then use this model for segmentation with the SynapseNet GUI or CLI. " 321 "Check out the information below for details on the arguments of this function.", 322 formatter_class=argparse.RawTextHelpFormatter 323 ) 324 parser.add_argument("--name", "-n", required=True, help="The name of the model to be trained. ") 325 parser.add_argument("--input_folder", "-i", required=True, help="The folder with the training data.") 326 parser.add_argument("--file_pattern", default="*", 327 help="The pattern for selecting files for training. For example '*.mrc' to select mrc files.") 328 parser.add_argument("--key", help="The internal file path for the training data. Will be derived from the file extension by default.") # noqa 329 available_models = get_available_models() 330 parser.add_argument( 331 "--source_model", 332 default="vesicles_3d", 333 help="The source model sets the default checkpoint and the metadata for patch size and data resizing. " 334 "By default the model 'vesicles_3d' for vesicle segmentation in volumetric data is used.\n" 335 "The --source_checkpoint argument overrides the default checkpoint.\n" 336 f"The following source models are available: {available_models}" 337 ) 338 parser.add_argument( 339 "--source_checkpoint", 340 help="Path to a custom source checkpoint directory or serialized PyTorch model. " 341 "If not given, the command downloads the checkpoint for --source_model." 342 ) 343 parser.add_argument( 344 "--resize_training_data", action="store_true", 345 help="Whether to resize the training data to fit the voxel size of the source model's trainign data." 346 ) 347 parser.add_argument("--n_iterations", type=int, default=int(1e4), help="The number of iterations for training.") 348 parser.add_argument( 349 "--patch_shape", nargs=3, type=int, 350 help="The patch shape for training. By default the patch shape the source model was trained with is used." 351 ) 352 353 # More optional argument: 354 parser.add_argument("--batch_size", type=int, default=1, help="The batch size for training.") 355 parser.add_argument("--n_samples_train", type=int, help="The number of samples per epoch for training. If not given will be derived from the data size.") # noqa 356 parser.add_argument("--n_samples_val", type=int, help="The number of samples per epoch for validation. If not given will be derived from the data size.") # noqa 357 parser.add_argument("--val_fraction", type=float, default=0.15, help="The fraction of the data to use for validation. This has no effect if 'val_folder' and 'val_label_folder' were passed.") # noqa 358 parser.add_argument("--check", action="store_true", help="Visualize samples from the data loaders to ensure correct data instead of running training.") # noqa 359 parser.add_argument("--save_root", help="Root path for saving the checkpoint and log dir.") 360 361 args = parser.parse_args() 362 363 try: 364 source_checkpoint = _resolve_source_checkpoint(args.source_model, args.source_checkpoint) 365 except ValueError as error: 366 parser.error(str(error)) 367 patch_shape = _parse_patch_shape(args.patch_shape, args.source_model) 368 with tempfile.TemporaryDirectory() as tmp_dir: 369 unsupervised_train_paths, unsupervised_val_paths = _get_paths( 370 args.input_folder, args.file_pattern, args.resize_training_data, 371 args.source_model, tmp_dir, args.val_fraction, 372 ) 373 unsupervised_train_paths, raw_key = _derive_key_from_files(unsupervised_train_paths, args.key) 374 375 mean_teacher_adaptation( 376 name=args.name, 377 unsupervised_train_paths=unsupervised_train_paths, 378 unsupervised_val_paths=unsupervised_val_paths, 379 patch_shape=patch_shape, 380 source_checkpoint=source_checkpoint, 381 raw_key=raw_key, 382 n_iterations=args.n_iterations, 383 batch_size=args.batch_size, 384 n_samples_train=args.n_samples_train, 385 n_samples_val=args.n_samples_val, 386 check=args.check, 387 save_root=args.save_root, 388 )
def
mean_teacher_adaptation( name: str, unsupervised_train_paths: Tuple[str], unsupervised_val_paths: Tuple[str], patch_shape: Tuple[int, int, int], save_root: Optional[str] = None, source_checkpoint: Optional[str] = None, supervised_train_paths: Optional[Tuple[str]] = None, supervised_val_paths: Optional[Tuple[str]] = None, confidence_threshold: float = 0.9, raw_key: str = 'raw', raw_key_supervised: str = 'raw', label_key: Optional[str] = None, batch_size: int = 1, lr: float = 0.0001, n_iterations: int = 10000, n_samples_train: Optional[int] = None, n_samples_val: Optional[int] = None, train_mask_paths: Optional[Tuple[str]] = None, val_mask_paths: Optional[Tuple[str]] = None, sample_mask_key: Optional[str] = None, unsupervised_sampler: Optional[<built-in function callable>] = None, supervised_sampler: Optional[<built-in function callable>] = None, backbone: Optional[str] = None, model_type: Optional[str] = None, encoder_checkpoint: Optional[str] = None, aug_dict: Optional[dict] = None, separate_backward: bool = False, check: bool = False) -> None:
27def mean_teacher_adaptation( 28 name: str, 29 unsupervised_train_paths: Tuple[str], 30 unsupervised_val_paths: Tuple[str], 31 patch_shape: Tuple[int, int, int], 32 save_root: Optional[str] = None, 33 source_checkpoint: Optional[str] = None, 34 supervised_train_paths: Optional[Tuple[str]] = None, 35 supervised_val_paths: Optional[Tuple[str]] = None, 36 confidence_threshold: float = 0.9, 37 raw_key: str = "raw", 38 raw_key_supervised: str = "raw", 39 label_key: Optional[str] = None, 40 batch_size: int = 1, 41 lr: float = 1e-4, 42 n_iterations: int = int(1e4), 43 n_samples_train: Optional[int] = None, 44 n_samples_val: Optional[int] = None, 45 train_mask_paths: Optional[Tuple[str]] = None, 46 val_mask_paths: Optional[Tuple[str]] = None, 47 sample_mask_key: Optional[str] = None, 48 unsupervised_sampler: Optional[callable] = None, 49 supervised_sampler: Optional[callable] = None, 50 backbone: Optional[str] = None, 51 model_type: Optional[str] = None, 52 encoder_checkpoint: Optional[str] = None, 53 aug_dict: Optional[dict] = None, 54 separate_backward: bool = False, 55 check: bool = False, 56) -> None: 57 """Run domain adaptation to transfer a network trained on a source domain for a supervised 58 segmentation task to perform this task on a different target domain. 59 60 We support different domain adaptation settings: 61 - unsupervised domain adaptation: the default mode when 'supervised_train_paths' and 62 'supervised_val_paths' are not given. 63 - semi-supervised domain adaptation: domain adaptation on unlabeled and labeled data, 64 when 'supervised_train_paths' and 'supervised_val_paths' are given. 65 66 Args: 67 name: The name for the checkpoint to be trained. 68 unsupervised_train_paths: Filepaths to the hdf5 files or similar file formats 69 for the training data in the target domain. 70 This training data is used for unsupervised learning, so it does not require labels. 71 unsupervised_val_paths: Filepaths to the hdf5 files or similar file formats 72 for the validation data in the target domain. 73 This validation data is used for unsupervised learning, so it does not require labels. 74 patch_shape: The patch shape used for a training example. 75 In order to run 2d training pass a patch shape with a singleton in the z-axis, 76 e.g. 'patch_shape = [1, 512, 512]'. 77 save_root: Folder where the checkpoint will be saved. 78 source_checkpoint: Checkpoint to the initial model trained on the source domain. 79 This is used to initialize the teacher model. 80 If the checkpoint is not given, then both student and teacher model are initialized 81 from scratch. In this case `supervised_train_paths` and `supervised_val_paths` have to 82 be given in order to provide training data from the source domain. 83 supervised_train_paths: Filepaths to the hdf5 files for the training data in the source domain. 84 This training data is optional. If given, it is used for supervised learning and requires labels. 85 supervised_val_paths: Filepaths to the hdf5 files for the validation data in the source domain. 86 This validation data is optional. If given, it is used for supervised learning and requires labels. 87 confidence_threshold: The threshold for filtering data in the unsupervised loss. 88 The label filtering is done based on the uncertainty of network predictions, and only 89 the data with higher certainty than this threshold is used for training. 90 raw_key: The key that holds the raw data inside of the hdf5 or similar files. 91 raw_key_supervised: The key that holds the raw data inside of the hdf5 files for supervised learning. 92 label_key: The key that holds the labels inside of the hdf5 files for supervised learning. 93 This is only required if `supervised_train_paths` and `supervised_val_paths` are given. 94 batch_size: The batch size for training. 95 lr: The initial learning rate. 96 n_iterations: The number of iterations to train for. 97 n_samples_train: The number of train samples per epoch. By default this will be estimated 98 based on the patch_shape and size of the volumes used for training. 99 n_samples_val: The number of val samples per epoch. By default this will be estimated 100 based on the patch_shape and size of the volumes used for validation. 101 train_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for training. 102 val_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for validation. 103 sample_mask_key: The key to the sample mask dataset inside each file. 104 unsupervised_sampler: Sampler to accept or reject patches for the unsupervised data stream. 105 supervised_sampler: Sampler to accept or reject patches for the supervised data stream. 106 Pass `False` to disable. 107 backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR), 108 or "cryosiam" (3D CNN encoder of a CryoZooUNet). 109 The ViT backbones must be set together with `model_type`. 110 model_type: Model type for the selected ViT `backbone` model family, for example "vit_b" or 111 "vit_b_em_organelles" for "sam". 112 encoder_checkpoint: Path to the pretrained encoder weights for `backbone`. 113 By default they are fetched for `backbone` and `model_type`. 114 aug_dict: The augmentations for the teacher and the student, with keys "intensity" and "geometrical". 115 Defaults to Gaussian blur and noise, plus random flips and 90-degree rotations. 116 The noise is scaled with `clip_max` to match the range of `raw_transform`. 117 separate_backward: Whether to backpropagate each loss term separately to reduce peak memory. 118 check: Whether to check the training and validation loaders instead of running training. 119 """ 120 assert (supervised_train_paths is None) == (supervised_val_paths is None) 121 _check_backbone(backbone, model_type, patch_shape) 122 is_2d, _ = _determine_ndim(patch_shape) 123 124 if source_checkpoint is None: 125 # training from scratch only makes sense if we have supervised training data 126 # that's why we have the assertion here. 127 assert supervised_train_paths is not None 128 print("Mean teacher training from scratch (AdaMT).") 129 model = _get_model( 130 patch_shape, out_channels=2, backbone=backbone, 131 model_type=model_type, encoder_checkpoint=encoder_checkpoint, 132 ) 133 reinit_teacher = True 134 else: 135 print("Mean teacher training initialized from source model:", source_checkpoint) 136 if os.path.isdir(source_checkpoint): 137 model = torch_em.util.load_model(source_checkpoint) 138 else: 139 model = _restore_legacy_attributes(torch.load(source_checkpoint, weights_only=False)) 140 reinit_teacher = False 141 142 optimizer = torch.optim.Adam(model.parameters(), lr=lr) 143 scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.5, patience=5) 144 145 # self training functionality 146 pseudo_labeler = self_training.DefaultPseudoLabeler(confidence_threshold=confidence_threshold) 147 loss = self_training.SelfTrainingLossWithInvertibleAugmentations() 148 loss_and_metric = self_training.SelfTrainingLossAndMetricWithInvertibleAugmentations() 149 150 raw_transform, clip_max = get_raw_transform(backbone) 151 152 ndim = 2 if is_2d else 3 153 if aug_dict is None: 154 aug_dict = { 155 "intensity": { 156 "RandomGaussianBlur": {"kernel_size": (19, 19), "sigma": (0.1, 3.0)}, 157 "RandomGaussianNoise": {"mean": 0.0, "std": 0.1 if clip_max is None else 0.015 * clip_max}, 158 }, 159 "geometrical": DEFAULT_WEAK_AUGMENTATIONS["geometrical"], 160 } 161 augmenters = MeanTeacherAugmenters(ndim=ndim, clip_max=clip_max, aug_dict=aug_dict) 162 163 unsupervised_train_loader = get_unsupervised_loader( 164 data_paths=unsupervised_train_paths, 165 raw_key=raw_key, 166 patch_shape=patch_shape, 167 batch_size=batch_size, 168 n_samples=n_samples_train, 169 sample_mask_paths=train_mask_paths, 170 sample_mask_key=sample_mask_key, 171 sampler=unsupervised_sampler, 172 raw_transform=raw_transform, 173 ) 174 unsupervised_val_loader = get_unsupervised_loader( 175 data_paths=unsupervised_val_paths, 176 raw_key=raw_key, 177 patch_shape=patch_shape, 178 batch_size=batch_size, 179 n_samples=n_samples_val, 180 sample_mask_paths=val_mask_paths, 181 sample_mask_key=sample_mask_key, 182 sampler=unsupervised_sampler, 183 raw_transform=raw_transform, 184 ) 185 186 if supervised_train_paths is not None: 187 assert label_key is not None 188 supervised_train_loader = get_supervised_loader( 189 supervised_train_paths, raw_key_supervised, label_key, 190 patch_shape, batch_size, n_samples=n_samples_train, 191 sampler=supervised_sampler, raw_transform=raw_transform, 192 ) 193 supervised_val_loader = get_supervised_loader( 194 supervised_val_paths, raw_key_supervised, label_key, 195 patch_shape, batch_size, n_samples=n_samples_val, 196 sampler=supervised_sampler, raw_transform=raw_transform, 197 ) 198 else: 199 supervised_train_loader = None 200 supervised_val_loader = None 201 202 if check: 203 from torch_em.util.debug import check_loader 204 check_loader(unsupervised_train_loader, n_samples=4) 205 check_loader(unsupervised_val_loader, n_samples=4) 206 if supervised_train_loader is not None: 207 check_loader(supervised_train_loader, n_samples=4) 208 check_loader(supervised_val_loader, n_samples=4) 209 return 210 211 device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 212 trainer = self_training.MeanTeacherTrainerWithInvertibleAugmentations( 213 name=name, 214 model=model, 215 optimizer=optimizer, 216 lr_scheduler=scheduler, 217 pseudo_labeler=pseudo_labeler, 218 unsupervised_loss=loss, 219 unsupervised_loss_and_metric=loss_and_metric, 220 supervised_train_loader=supervised_train_loader, 221 unsupervised_train_loader=unsupervised_train_loader, 222 supervised_val_loader=supervised_val_loader, 223 unsupervised_val_loader=unsupervised_val_loader, 224 supervised_loss=loss, 225 supervised_loss_and_metric=loss_and_metric, 226 logger=self_training.SelfTrainingTensorboardLogger, 227 # On the CPU, mixed precision uses bfloat16. It is very slow without hardware support, 228 # and the kornia augmentations do not accept it. 229 mixed_precision=device.type == "cuda", 230 log_image_interval=100, 231 compile_model=False, 232 device=device, 233 reinit_teacher=reinit_teacher, 234 save_root=save_root, 235 augmenter=augmenters, 236 separate_backward=separate_backward, 237 ) 238 trainer.fit(n_iterations)
Run domain adaptation to transfer a network trained on a source domain for a supervised segmentation task to perform this task on a different target domain.
We support different domain adaptation settings:
- unsupervised domain adaptation: the default mode when 'supervised_train_paths' and 'supervised_val_paths' are not given.
- semi-supervised domain adaptation: domain adaptation on unlabeled and labeled data, when 'supervised_train_paths' and 'supervised_val_paths' are given.
Arguments:
- name: The name for the checkpoint to be trained.
- unsupervised_train_paths: Filepaths to the hdf5 files or similar file formats for the training data in the target domain. This training data is used for unsupervised learning, so it does not require labels.
- unsupervised_val_paths: Filepaths to the hdf5 files or similar file formats for the validation data in the target domain. This validation data is used for unsupervised learning, so it does not require labels.
- patch_shape: The patch shape used for a training example. In order to run 2d training pass a patch shape with a singleton in the z-axis, e.g. 'patch_shape = [1, 512, 512]'.
- save_root: Folder where the checkpoint will be saved.
- source_checkpoint: Checkpoint to the initial model trained on the source domain.
This is used to initialize the teacher model.
If the checkpoint is not given, then both student and teacher model are initialized
from scratch. In this case
supervised_train_pathsandsupervised_val_pathshave to be given in order to provide training data from the source domain. - supervised_train_paths: Filepaths to the hdf5 files for the training data in the source domain. This training data is optional. If given, it is used for supervised learning and requires labels.
- supervised_val_paths: Filepaths to the hdf5 files for the validation data in the source domain. This validation data is optional. If given, it is used for supervised learning and requires labels.
- confidence_threshold: The threshold for filtering data in the unsupervised loss. The label filtering is done based on the uncertainty of network predictions, and only the data with higher certainty than this threshold is used for training.
- raw_key: The key that holds the raw data inside of the hdf5 or similar files.
- raw_key_supervised: The key that holds the raw data inside of the hdf5 files for supervised learning.
- label_key: The key that holds the labels inside of the hdf5 files for supervised learning.
This is only required if
supervised_train_pathsandsupervised_val_pathsare given. - batch_size: The batch size for training.
- lr: The initial learning rate.
- n_iterations: The number of iterations to train for.
- n_samples_train: The number of train samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for training.
- n_samples_val: The number of val samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for validation.
- train_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for training.
- val_mask_paths: Sample masks used by the unsupervised sampler to accept or reject patches for validation.
- sample_mask_key: The key to the sample mask dataset inside each file.
- unsupervised_sampler: Sampler to accept or reject patches for the unsupervised data stream.
- supervised_sampler: Sampler to accept or reject patches for the supervised data stream.
Pass
Falseto disable. - backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR),
or "cryosiam" (3D CNN encoder of a CryoZooUNet).
The ViT backbones must be set together with
model_type. - model_type: Model type for the selected ViT
backbonemodel family, for example "vit_b" or "vit_b_em_organelles" for "sam". - encoder_checkpoint: Path to the pretrained encoder weights for
backbone. By default they are fetched forbackboneandmodel_type. - aug_dict: The augmentations for the teacher and the student, with keys "intensity" and "geometrical".
Defaults to Gaussian blur and noise, plus random flips and 90-degree rotations.
The noise is scaled with
clip_maxto match the range ofraw_transform. - separate_backward: Whether to backpropagate each loss term separately to reduce peak memory.
- check: Whether to check the training and validation loaders instead of running training.