class nnUNetTrainerV2_3ConvPerStage(nnUNetTrainerV2): def initialize_network(self): self.base_num_features = 24 # otherwise we run out of VRAM if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), 3, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ # self.print_to_log_file(self.net_num_pool_op_kernel_sizes) # self.print_to_log_file(self.net_conv_kernel_sizes) net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.network.inference_apply_nonlin = softmax_helper if torch.cuda.is_available(): self.network.cuda()
class nnUNetTrainerV2BraTSRegions_BN(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.BatchNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.BatchNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = torch.nn.Softmax(1)
def initialize_network(self): """ changed deep supervision to False :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = FRN3D else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d raise NotImplementedError norm_op = nn.BatchNorm2d norm_op_kwargs = {'eps': 1e-6} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = Identity net_nonlin_kwargs = {} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
class nnUNetTrainerV2_Mish(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = Mish net_nonlin_kwargs = {} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(0), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network(self): """ changed deep supervision to False :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network_optimizer_and_scheduler(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ #self.print_to_log_file(self.net_num_pool_op_kernel_sizes) #self.print_to_log_file(self.net_conv_kernel_sizes) net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, 2, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, amsgrad=True) self.lr_scheduler = lr_scheduler.ReduceLROnPlateau(self.optimizer, mode='min', factor=0.2, patience=self.lr_scheduler_patience, verbose=True, threshold=self.lr_scheduler_eps, threshold_mode="abs") #if torch.cuda.is_available(): #edit PW # self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
class nnUNetTrainerV2_NoNormalization(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = Identity else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = Identity norm_op_kwargs = {} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network_optimizer_and_scheduler(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ # self.print_to_log_file(self.net_num_pool_op_kernel_sizes) # self.print_to_log_file(self.net_conv_kernel_sizes) net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, 2, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, amsgrad=True) self.lr_scheduler = lr_scheduler.ReduceLROnPlateau( self.optimizer, mode='min', factor=0.2, patience=self.lr_scheduler_patience, verbose=True, threshold=self.lr_scheduler_eps, threshold_mode="abs") self.network.cuda() if torch.cuda.device_count() > 1: torch.distributed.init_process_group( backend='nccl', init_method='tcp://localhost:23456', rank=0, world_size=1) self.network = torch.nn.parallel.DistributedDataParallel( self.network) # self.network, self.optimizer = amp.initialize(self.network, self.optimizer, opt_level="O1") # self.network = DistributedDataParallel(self.network) print("Let's use", torch.cuda.device_count(), "GPUs!") self.network.inference_apply_nonlin = softmax_helper
class nnUNetTrainerV2_MMS(nnUNetTrainerV2_insaneDA): def setup_DA_params(self): super().setup_DA_params() self.data_aug_params["p_rot"] = 0.7 self.data_aug_params["p_eldef"] = 0.1 self.data_aug_params["p_scale"] = 0.3 self.data_aug_params["independent_scale_factor_for_each_axis"] = True self.data_aug_params["p_independent_scale_per_axis"] = 0.3 self.data_aug_params["do_additive_brightness"] = True self.data_aug_params["additive_brightness_mu"] = 0 self.data_aug_params["additive_brightness_sigma"] = 0.2 self.data_aug_params["additive_brightness_p_per_sample"] = 0.3 self.data_aug_params["additive_brightness_p_per_channel"] = 1 self.data_aug_params["elastic_deform_alpha"] = (0., 300.) self.data_aug_params["elastic_deform_sigma"] = (9., 15.) self.data_aug_params['gamma_range'] = (0.5, 1.6) def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.BatchNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.BatchNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper """def run_training(self):
def initialize_network_optimizer_and_scheduler(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ #self.print_to_log_file(self.net_num_pool_op_kernel_sizes) #self.print_to_log_file(self.net_conv_kernel_sizes) print('Has entered into the initialize_network_optimizer_and_scheduler!') net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} torch.cuda.set_device(0) self.do_supervision=False self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, 2, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, self.do_supervision, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) # print('self.network is:',self.network) # Here!!! Modify it to be parallel model # self.network=nn.DataParallel(self.network,device_ids=[0,1,2,3]) g=tw.draw_model(self.network,[8,1,128,128,128]) g.save('/cache/WenshuaiZhao/ProjectFiles/NNUnet/nnunet/model_structure.png') print('draw model has been done!') self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, amsgrad=True) # Here!!! optimizer is also need to be parallel # self.optimizer=nn.DataParallel(self.optimizer,device_ids=[0,1,2,3]) self.lr_scheduler = lr_scheduler.ReduceLROnPlateau(self.optimizer, mode='min', factor=0.2, patience=self.lr_scheduler_patience, verbose=True, threshold=self.lr_scheduler_eps, threshold_mode="abs") self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
class nnUNetTrainerV2_Mish(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = Mish net_nonlin_kwargs = {} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(0), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper def _maybe_init_amp(self): """ In O1 mish will result in super super high memory usage. I believe that may be because amp decides to be save and use fp32 for all activation functions. By using O2 we reduce memory comsumption by a lot :return: """ # we use fp16 for training only, not inference if self.fp16: if not self.amp_initialized: if amp is not None: self.network, self.optimizer = amp.initialize( self.network, self.optimizer, opt_level="O2") self.amp_initialized = True else: self.print_to_log_file( "WARNING: FP16 training was requested but nvidia apex is not installed. " "Install it from https://github.com/NVIDIA/apex")
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape, dtype=np.int64) * num_cases input_patch_size = new_median_shape[1:] network_numpool, net_pool_kernel_sizes, net_conv_kernel_sizes, input_patch_size, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing[1:], input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool) # we pretend to use 30 feature maps. This will yield the same configuration as in V1. The larger memory # footpring of 32 vs 30 is mor ethan offset by the fp16 training. We make fp16 training default # Reason for 32 vs 30 feature maps is that 32 is faster in fp16 training (because multiple of 8) estimated_gpu_ram_consumption = Generic_UNet.compute_approx_vram_consumption( input_patch_size, network_numpool, 30, self.unet_max_num_filters, num_modalities, num_classes, net_pool_kernel_sizes, conv_per_stage=self.conv_per_stage) batch_size = int( np.floor(Generic_UNet.use_this_for_batch_size_computation_2D / estimated_gpu_ram_consumption * Generic_UNet.DEFAULT_BATCH_SIZE_2D)) if batch_size < self.unet_min_batch_size: raise RuntimeError( "This framework is not made to process patches this large. We will add patch-based " "2D networks later. Sorry for the inconvenience") # check if batch size is too large (more than 5 % of dataset) max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) batch_size = min(batch_size, max_batch_size) plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_numpool, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'pool_op_kernel_sizes': net_pool_kernel_sizes, 'conv_kernel_sizes': net_conv_kernel_sizes, 'do_dummy_2D_data_aug': False } return plan
class nnUNetTrainerV2_lReLU_biasInSegOutput(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(0), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True, seg_output_use_bias=True) self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.ReLU net_nonlin_kwargs = {'inplace': True} self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(0), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True, basic_block=ConvDropoutNonlinNorm) self.network.cuda() self.network.inference_apply_nonlin = softmax_helper
def get_properties_for_stage(current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes, transpose_forward): spacing_transposed = current_spacing[transpose_forward] new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) new_median_shape_transposed = new_median_shape[transpose_forward] dataset_num_voxels = np.prod(new_median_shape) * num_cases input_patch_size = new_median_shape_transposed[1:] network_numpool, net_pool_kernel_sizes, net_conv_kernel_sizes, input_patch_size, \ shape_must_be_divisible_by = get_pool_and_conv_props(spacing_transposed[1:], input_patch_size, FEATUREMAP_MIN_EDGE_LENGTH_BOTTLENECK, Generic_UNet.MAX_NUMPOOL_2D) estimated_gpu_ram_consumption = Generic_UNet.compute_approx_vram_consumption( input_patch_size, network_numpool, Generic_UNet.BASE_NUM_FEATURES_2D, Generic_UNet.MAX_FILTERS_2D, num_modalities, num_classes, net_pool_kernel_sizes) batch_size = int( np.floor(Generic_UNet.use_this_for_batch_size_computation_2D / estimated_gpu_ram_consumption * Generic_UNet.DEFAULT_BATCH_SIZE_2D)) if batch_size < dataset_min_batch_size_cap: raise RuntimeError( "This framework is not made to process patches this large. We will add patch-based " "2D networks later. Sorry for the inconvenience") # check if batch size is too large (more than 5 % of dataset) max_batch_size = np.round( batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size)).astype(int) batch_size = min(batch_size, max_batch_size) plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_numpool, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'pool_op_kernel_sizes': net_pool_kernel_sizes, 'conv_kernel_sizes': net_conv_kernel_sizes, 'do_dummy_2D_data_aug': False } return plan
class nnUNetTrainer(NetworkTrainer): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): """ :param deterministic: :param fold: can be either [0 ... 5) for cross-validation, 'all' to train on all available training data or None if you wish to load some checkpoint and do inference only :param plans_file: the pkl file generated by preprocessing. This file will determine all design choices :param subfolder_with_preprocessed_data: must be a subfolder of dataset_directory (just the name of the folder, not the entire path). This is where the preprocessed data lies that will be used for network training. We made this explicitly available so that differently preprocessed data can coexist and the user can choose what to use. Can be None if you are doing inference only. :param output_folder: where to store parameters, plot progress and to the validation :param dataset_directory: the parent directory in which the preprocessed Task data is stored. This is required because the split information is stored in this directory. For running prediction only this input is not required and may be set to None :param batch_dice: compute dice loss for each sample and average over all samples in the batch or pretend the batch is a pseudo volume? :param stage: The plans file may contain several stages (used for lowres / highres / pyramid). Stage must be specified for training: if stage 1 exists then stage 1 is the high resolution stage, otherwise it's 0 :param unpack_data: if False, npz preprocessed data will not be unpacked to npy. This consumes less space but is considerably slower! Running unpack_data=False with 2d should never be done! IMPORTANT: If you inherit from nnUNetTrainer and the init args change then you need to redefine self.init_args in your init accordingly. Otherwise checkpoints won't load properly! """ super(nnUNetTrainer, self).__init__(deterministic, fp16) self.unpack_data = unpack_data self.init_args = (plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) # set through arguments from init self.stage = stage self.experiment_name = self.__class__.__name__ self.plans_file = plans_file self.output_folder = output_folder self.dataset_directory = dataset_directory self.output_folder_base = self.output_folder self.fold = fold self.plans = None # if we are running inference only then the self.dataset_directory is set (due to checkpoint loading) but it # irrelevant if self.dataset_directory is not None and isdir(self.dataset_directory): self.gt_niftis_folder = join(self.dataset_directory, "gt_segmentations") else: self.gt_niftis_folder = None self.folder_with_preprocessed_data = None # set in self.initialize() self.dl_tr = self.dl_val = None self.num_input_channels = self.num_classes = self.net_pool_per_axis = self.patch_size = self.batch_size = \ self.threeD = self.base_num_features = self.intensity_properties = self.normalization_schemes = \ self.net_num_pool_op_kernel_sizes = self.net_conv_kernel_sizes = None # loaded automatically from plans_file self.basic_generator_patch_size = self.data_aug_params = self.transpose_forward = self.transpose_backward = None self.batch_dice = batch_dice self.loss = DC_and_CE_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {}) self.online_eval_foreground_dc = [] self.online_eval_tp = [] self.online_eval_fp = [] self.online_eval_fn = [] self.classes = self.do_dummy_2D_aug = self.use_mask_for_norm = self.only_keep_largest_connected_component = \ self.min_region_size_per_class = self.min_size_per_class = None self.inference_pad_border_mode = "constant" self.inference_pad_kwargs = {'constant_values': 0} self.update_fold(fold) self.pad_all_sides = None self.lr_scheduler_eps = 1e-3 self.lr_scheduler_patience = 30 self.initial_lr = 3e-4 self.weight_decay = 3e-5 self.oversample_foreground_percent = 0.33 self.conv_per_stage = None self.regions_class_order = None def update_fold(self, fold): """ used to swap between folds for inference (ensemble of models from cross-validation) DO NOT USE DURING TRAINING AS THIS WILL NOT UPDATE THE DATASET SPLIT AND THE DATA AUGMENTATION GENERATORS :param fold: :return: """ if fold is not None: if isinstance(fold, str): assert fold == "all", "if self.fold is a string then it must be \'all\'" if self.output_folder.endswith("%s" % str(self.fold)): self.output_folder = self.output_folder_base self.output_folder = join(self.output_folder, "%s" % str(fold)) else: if self.output_folder.endswith("fold_%s" % str(self.fold)): self.output_folder = self.output_folder_base self.output_folder = join(self.output_folder, "fold_%s" % str(fold)) self.fold = fold def setup_DA_params(self): if self.threeD: self.data_aug_params = default_3D_augmentation_params if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params["rotation_x"] = default_2D_augmentation_params["rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params["mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size(self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array([self.patch_size[0]] + list(self.basic_generator_patch_size)) patch_size_for_spatialtransform = self.patch_size[1:] else: self.basic_generator_patch_size = get_patch_size(self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) patch_size_for_spatialtransform = self.patch_size self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params['patch_size_for_spatialtransform'] = patch_size_for_spatialtransform def initialize(self, training=True, force_load_plans=False): """ For prediction of test cases just set training=False, this will prevent loading of training data and training batchgenerator initialization :param training: :return: """ maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() if training: self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: self.print_to_log_file("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) self.print_to_log_file("done") else: self.print_to_log_file( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") self.tr_gen, self.val_gen = get_default_augmentation(self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() # assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) self.was_initialized = True def initialize_network(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ # self.print_to_log_file(self.net_num_pool_op_kernel_sizes) # self.print_to_log_file(self.net_conv_kernel_sizes) net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.network.inference_apply_nonlin = softmax_helper if torch.cuda.is_available(): self.network.cuda() def initialize_optimizer_and_scheduler(self): assert self.network is not None, "self.initialize_network must be called first" self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, amsgrad=True) self.lr_scheduler = lr_scheduler.ReduceLROnPlateau(self.optimizer, mode='min', factor=0.2, patience=self.lr_scheduler_patience, verbose=True, threshold=self.lr_scheduler_eps, threshold_mode="abs") def plot_network_architecture(self): try: from batchgenerators.utilities.file_and_folder_operations import join import hiddenlayer as hl if torch.cuda.is_available(): g = hl.build_graph(self.network, torch.rand((1, self.num_input_channels, *self.patch_size)).cuda(), transforms=None) else: g = hl.build_graph(self.network, torch.rand((1, self.num_input_channels, *self.patch_size)), transforms=None) g.save(join(self.output_folder, "network_architecture.pdf")) del g except Exception as e: self.print_to_log_file("Unable to plot network architecture:") self.print_to_log_file(e) self.print_to_log_file("\nprinting the network instead:\n") self.print_to_log_file(self.network) self.print_to_log_file("\n") finally: if torch.cuda.is_available(): torch.cuda.empty_cache() def run_training(self): dct = OrderedDict() for k in self.__dir__(): if not k.startswith("__"): if not callable(getattr(self, k)): dct[k] = str(getattr(self, k)) del dct['plans'] del dct['intensity_properties'] del dct['dataset'] del dct['dataset_tr'] del dct['dataset_val'] save_json(dct, join(self.output_folder, "debug.json")) import shutil shutil.copy(self.plans_file, join(self.output_folder_base, "plans.pkl")) super(nnUNetTrainer, self).run_training() def load_plans_file(self): """ This is what actually configures the entire experiment. The plans file is generated by experiment planning :return: """ self.plans = load_pickle(self.plans_file) def process_plans(self, plans): if self.stage is None: assert len(list(plans['plans_per_stage'].keys())) == 1, \ "If self.stage is None then there can be only one stage in the plans file. That seems to not be the " \ "case. Please specify which stage of the cascade must be trained" self.stage = list(plans['plans_per_stage'].keys())[0] self.plans = plans stage_plans = self.plans['plans_per_stage'][self.stage] self.batch_size = stage_plans['batch_size'] self.net_pool_per_axis = stage_plans['num_pool_per_axis'] self.patch_size = np.array(stage_plans['patch_size']).astype(int) self.do_dummy_2D_aug = stage_plans['do_dummy_2D_data_aug'] if 'pool_op_kernel_sizes' not in stage_plans.keys(): assert 'num_pool_per_axis' in stage_plans.keys() self.print_to_log_file("WARNING! old plans file with missing pool_op_kernel_sizes. Attempting to fix it...") self.net_num_pool_op_kernel_sizes = [] for i in range(max(self.net_pool_per_axis)): curr = [] for j in self.net_pool_per_axis: if (max(self.net_pool_per_axis) - j) <= i: curr.append(2) else: curr.append(1) self.net_num_pool_op_kernel_sizes.append(curr) else: self.net_num_pool_op_kernel_sizes = stage_plans['pool_op_kernel_sizes'] if 'conv_kernel_sizes' not in stage_plans.keys(): self.print_to_log_file("WARNING! old plans file with missing conv_kernel_sizes. Attempting to fix it...") self.net_conv_kernel_sizes = [[3] * len(self.net_pool_per_axis)] * (max(self.net_pool_per_axis) + 1) else: self.net_conv_kernel_sizes = stage_plans['conv_kernel_sizes'] self.pad_all_sides = None # self.patch_size self.intensity_properties = plans['dataset_properties']['intensityproperties'] self.normalization_schemes = plans['normalization_schemes'] self.base_num_features = plans['base_num_features'] self.num_input_channels = plans['num_modalities'] self.num_classes = plans['num_classes'] + 1 # background is no longer in num_classes self.classes = plans['all_classes'] self.use_mask_for_norm = plans['use_mask_for_norm'] self.only_keep_largest_connected_component = plans['keep_only_largest_region'] self.min_region_size_per_class = plans['min_region_size_per_class'] self.min_size_per_class = None # DONT USE THIS. plans['min_size_per_class'] if plans.get('transpose_forward') is None or plans.get('transpose_backward') is None: print("WARNING! You seem to have data that was preprocessed with a previous version of nnU-Net. " "You should rerun preprocessing. We will proceed and assume that both transpose_foward " "and transpose_backward are [0, 1, 2]. If that is not correct then weird things will happen!") plans['transpose_forward'] = [0, 1, 2] plans['transpose_backward'] = [0, 1, 2] self.transpose_forward = plans['transpose_forward'] self.transpose_backward = plans['transpose_backward'] if len(self.patch_size) == 2: self.threeD = False elif len(self.patch_size) == 3: self.threeD = True else: raise RuntimeError("invalid patch size in plans file: %s" % str(self.patch_size)) if "conv_per_stage" in plans.keys(): # this ha sbeen added to the plans only recently self.conv_per_stage = plans['conv_per_stage'] else: self.conv_per_stage = 2 def load_dataset(self): self.dataset = load_dataset(self.folder_with_preprocessed_data) def get_basic_generators(self): self.load_dataset() self.do_split() if self.threeD: print("3d!") dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, False, oversample_foreground_percent=self.oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides, memmap_mode='r') dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, False, oversample_foreground_percent=self.oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides, memmap_mode='r') else: print("2d!") dl_tr = DataLoader2D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, oversample_foreground_percent=self.oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides, memmap_mode='r') dl_val = DataLoader2D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, oversample_foreground_percent=self.oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides, memmap_mode='r') return dl_tr, dl_val def preprocess_patient(self, input_files): """ Used to predict new unseen data. Not used for the preprocessing of the training/test data :param input_files: :return: """ from nnunet.training.model_restore import recursive_find_python_class preprocessor_name = self.plans.get('preprocessor_name') if preprocessor_name is None: if self.threeD: preprocessor_name = "GenericPreprocessor" else: preprocessor_name = "PreprocessorFor2D" print("using preprocessor", preprocessor_name) preprocessor_class = recursive_find_python_class([join(nnunet.__path__[0], "preprocessing")], preprocessor_name, current_module="nnunet.preprocessing") assert preprocessor_class is not None, "Could not find preprocessor %s in nnunet.preprocessing" % \ preprocessor_name preprocessor = preprocessor_class(self.normalization_schemes, self.use_mask_for_norm, self.transpose_forward, self.intensity_properties) d, s, properties = preprocessor.preprocess_test_case(input_files, self.plans['plans_per_stage'][self.stage][ 'current_spacing']) return d, s, properties def preprocess_predict_nifti(self, input_files: List[str], output_file: str = None, softmax_ouput_file: str = None, mixed_precision: bool = True) -> None: """ Use this to predict new data :param input_files: :param output_file: :param softmax_ouput_file: :param mixed_precision: :return: """ print("preprocessing...") d, s, properties = self.preprocess_patient(input_files) print("predicting...") pred = self.predict_preprocessed_data_return_seg_and_softmax(d, do_mirroring=self.data_aug_params["do_mirror"], mirror_axes=self.data_aug_params['mirror_axes'], use_sliding_window=True, step_size=0.5, use_gaussian=True, pad_border_mode='constant', pad_kwargs={'constant_values': 0}, verbose=True, all_in_gpu=False, mixed_precision=mixed_precision)[1] pred = pred.transpose([0] + [i + 1 for i in self.transpose_backward]) if 'segmentation_export_params' in self.plans.keys(): force_separate_z = self.plans['segmentation_export_params']['force_separate_z'] interpolation_order = self.plans['segmentation_export_params']['interpolation_order'] interpolation_order_z = self.plans['segmentation_export_params']['interpolation_order_z'] else: force_separate_z = None interpolation_order = 1 interpolation_order_z = 0 print("resampling to original spacing and nifti export...") save_segmentation_nifti_from_softmax(pred, output_file, properties, interpolation_order, self.regions_class_order, None, None, softmax_ouput_file, None, force_separate_z=force_separate_z, interpolation_order_z=interpolation_order_z) print("done") def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True, mirror_axes: Tuple[int] = None, use_sliding_window: bool = True, step_size: float = 0.5, use_gaussian: bool = True, pad_border_mode: str = 'constant', pad_kwargs: dict = None, all_in_gpu: bool = False, verbose: bool = True, mixed_precision: bool = True) -> Tuple[np.ndarray, np.ndarray]: """ :param data: :param do_mirroring: :param mirror_axes: :param use_sliding_window: :param step_size: :param use_gaussian: :param pad_border_mode: :param pad_kwargs: :param all_in_gpu: :param verbose: :return: """ if pad_border_mode == 'constant' and pad_kwargs is None: pad_kwargs = {'constant_values': 0} if do_mirroring and mirror_axes is None: mirror_axes = self.data_aug_params['mirror_axes'] if do_mirroring: assert self.data_aug_params["do_mirror"], "Cannot do mirroring as test time augmentation when training " \ "was done without mirroring" valid = list((SegmentationNetwork, nn.DataParallel)) assert isinstance(self.network, tuple(valid)) current_mode = self.network.training self.network.eval() ret = self.network.predict_3D(data, do_mirroring=do_mirroring, mirror_axes=mirror_axes, use_sliding_window=use_sliding_window, step_size=step_size, patch_size=self.patch_size, regions_class_order=self.regions_class_order, use_gaussian=use_gaussian, pad_border_mode=pad_border_mode, pad_kwargs=pad_kwargs, all_in_gpu=all_in_gpu, verbose=verbose, mixed_precision=mixed_precision) self.network.train(current_mode) return ret def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True): """ if debug=True then the temporary files generated for postprocessing determination will be kept """ current_mode = self.network.training self.network.eval() assert self.was_initialized, "must initialize, ideally with checkpoint (or train first)" if self.dataset_val is None: self.load_dataset() self.do_split() if segmentation_export_kwargs is None: if 'segmentation_export_params' in self.plans.keys(): force_separate_z = self.plans['segmentation_export_params']['force_separate_z'] interpolation_order = self.plans['segmentation_export_params']['interpolation_order'] interpolation_order_z = self.plans['segmentation_export_params']['interpolation_order_z'] else: force_separate_z = None interpolation_order = 1 interpolation_order_z = 0 else: force_separate_z = segmentation_export_kwargs['force_separate_z'] interpolation_order = segmentation_export_kwargs['interpolation_order'] interpolation_order_z = segmentation_export_kwargs['interpolation_order_z'] # predictions as they come from the network go here output_folder = join(self.output_folder, validation_folder_name) maybe_mkdir_p(output_folder) # this is for debug purposes my_input_args = {'do_mirroring': do_mirroring, 'use_sliding_window': use_sliding_window, 'step_size': step_size, 'save_softmax': save_softmax, 'use_gaussian': use_gaussian, 'overwrite': overwrite, 'validation_folder_name': validation_folder_name, 'debug': debug, 'all_in_gpu': all_in_gpu, 'segmentation_export_kwargs': segmentation_export_kwargs, } save_json(my_input_args, join(output_folder, "validation_args.json")) if do_mirroring: if not self.data_aug_params['do_mirror']: raise RuntimeError("We did not train with mirroring so you cannot do inference with mirroring enabled") mirror_axes = self.data_aug_params['mirror_axes'] else: mirror_axes = () pred_gt_tuples = [] export_pool = Pool(default_num_threads) results = [] for k in self.dataset_val.keys(): properties = load_pickle(self.dataset[k]['properties_file']) fname = properties['list_of_data_files'][0].split("/")[-1][:-12] if overwrite or (not isfile(join(output_folder, fname + ".nii.gz"))) or \ (save_softmax and not isfile(join(output_folder, fname + ".npz"))): data = np.load(self.dataset[k]['data_file'])['data'] print(k, data.shape) data[-1][data[-1] == -1] = 0 softmax_pred = self.predict_preprocessed_data_return_seg_and_softmax(data[:-1], do_mirroring=do_mirroring, mirror_axes=mirror_axes, use_sliding_window=use_sliding_window, step_size=step_size, use_gaussian=use_gaussian, all_in_gpu=all_in_gpu, mixed_precision=self.fp16)[1] softmax_pred = softmax_pred.transpose([0] + [i + 1 for i in self.transpose_backward]) if save_softmax: softmax_fname = join(output_folder, fname + ".npz") else: softmax_fname = None """There is a problem with python process communication that prevents us from communicating obejcts larger than 2 GB between processes (basically when the length of the pickle string that will be sent is communicated by the multiprocessing.Pipe object then the placeholder (\%i I think) does not allow for long enough strings (lol). This could be fixed by changing i to l (for long) but that would require manually patching system python code. We circumvent that problem here by saving softmax_pred to a npy file that will then be read (and finally deleted) by the Process. save_segmentation_nifti_from_softmax can take either filename or np.ndarray and will handle this automatically""" if np.prod(softmax_pred.shape) > (2e9 / 4 * 0.85): # *0.85 just to be save np.save(join(output_folder, fname + ".npy"), softmax_pred) softmax_pred = join(output_folder, fname + ".npy") results.append(export_pool.starmap_async(save_segmentation_nifti_from_softmax, ((softmax_pred, join(output_folder, fname + ".nii.gz"), properties, interpolation_order, self.regions_class_order, None, None, softmax_fname, None, force_separate_z, interpolation_order_z), ) ) ) pred_gt_tuples.append([join(output_folder, fname + ".nii.gz"), join(self.gt_niftis_folder, fname + ".nii.gz")]) _ = [i.get() for i in results] self.print_to_log_file("finished prediction") # evaluate raw predictions self.print_to_log_file("evaluation of raw predictions") task = self.dataset_directory.split("/")[-1] job_name = self.experiment_name _ = aggregate_scores(pred_gt_tuples, labels=list(range(self.num_classes)), json_output_file=join(output_folder, "summary.json"), json_name=job_name + " val tiled %s" % (str(use_sliding_window)), json_author="Fabian", json_task=task, num_threads=default_num_threads) if run_postprocessing_on_folds: # in the old nnunet we would stop here. Now we add a postprocessing. This postprocessing can remove everything # except the largest connected component for each class. To see if this improves results, we do this for all # classes and then rerun the evaluation. Those classes for which this resulted in an improved dice score will # have this applied during inference as well self.print_to_log_file("determining postprocessing") determine_postprocessing(self.output_folder, self.gt_niftis_folder, validation_folder_name, final_subf_name=validation_folder_name + "_postprocessed", debug=debug) # after this the final predictions for the vlaidation set can be found in validation_folder_name_base + "_postprocessed" # They are always in that folder, even if no postprocessing as applied! # detemining postprocesing on a per-fold basis may be OK for this fold but what if another fold finds another # postprocesing to be better? In this case we need to consolidate. At the time the consolidation is going to be # done we won't know what self.gt_niftis_folder was, so now we copy all the niftis into a separate folder to # be used later gt_nifti_folder = join(self.output_folder_base, "gt_niftis") maybe_mkdir_p(gt_nifti_folder) for f in subfiles(self.gt_niftis_folder, suffix=".nii.gz"): success = False attempts = 0 e = None while not success and attempts < 10: try: shutil.copy(f, gt_nifti_folder) success = True except OSError as e: attempts += 1 sleep(1) if not success: print("Could not copy gt nifti file %s into folder %s" % (f, gt_nifti_folder)) if e is not None: raise e self.network.train(current_mode) def run_online_evaluation(self, output, target): with torch.no_grad(): num_classes = output.shape[1] output_softmax = softmax_helper(output) output_seg = output_softmax.argmax(1) target = target[:, 0] axes = tuple(range(1, len(target.shape))) tp_hard = torch.zeros((target.shape[0], num_classes - 1)).to(output_seg.device.index) fp_hard = torch.zeros((target.shape[0], num_classes - 1)).to(output_seg.device.index) fn_hard = torch.zeros((target.shape[0], num_classes - 1)).to(output_seg.device.index) for c in range(1, num_classes): tp_hard[:, c - 1] = sum_tensor((output_seg == c).float() * (target == c).float(), axes=axes) fp_hard[:, c - 1] = sum_tensor((output_seg == c).float() * (target != c).float(), axes=axes) fn_hard[:, c - 1] = sum_tensor((output_seg != c).float() * (target == c).float(), axes=axes) tp_hard = tp_hard.sum(0, keepdim=False).detach().cpu().numpy() fp_hard = fp_hard.sum(0, keepdim=False).detach().cpu().numpy() fn_hard = fn_hard.sum(0, keepdim=False).detach().cpu().numpy() self.online_eval_foreground_dc.append(list((2 * tp_hard) / (2 * tp_hard + fp_hard + fn_hard + 1e-8))) self.online_eval_tp.append(list(tp_hard)) self.online_eval_fp.append(list(fp_hard)) self.online_eval_fn.append(list(fn_hard)) def finish_online_evaluation(self): self.online_eval_tp = np.sum(self.online_eval_tp, 0) self.online_eval_fp = np.sum(self.online_eval_fp, 0) self.online_eval_fn = np.sum(self.online_eval_fn, 0) global_dc_per_class = [i for i in [2 * i / (2 * i + j + k) for i, j, k in zip(self.online_eval_tp, self.online_eval_fp, self.online_eval_fn)] if not np.isnan(i)] self.all_val_eval_metrics.append(np.mean(global_dc_per_class)) self.print_to_log_file("Average global foreground Dice:", str(global_dc_per_class)) self.print_to_log_file("(interpret this as an estimate for the Dice of the different classes. This is not " "exact.)") self.online_eval_foreground_dc = [] self.online_eval_tp = [] self.online_eval_fp = [] self.online_eval_fn = [] def save_checkpoint(self, fname, save_optimizer=True): super(nnUNetTrainer, self).save_checkpoint(fname, save_optimizer) info = OrderedDict() info['init'] = self.init_args info['name'] = self.__class__.__name__ info['class'] = str(self.__class__) info['plans'] = self.plans write_pickle(info, fname + ".pkl")
class nnUNetTrainer(NetworkTrainer): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False, lam=2, gpu="0", save_dir=None): """ :param deterministic: :param fold: can be either [0 ... 5) for cross-validation, 'all' to train on all available training data or None if you wish to load some checkpoint and do inference only :param plans_file: the pkl file generated by preprocessing. This file will determine all design choices :param subfolder_with_preprocessed_data: must be a subfolder of dataset_directory (just the name of the folder, not the entire path). This is where the preprocessed data lies that will be used for network training. We made this explicitly available so that differently preprocessed data can coexist and the user can choose what to use. Can be None if you are doing inference only. :param output_folder: where to store parameters, plot progress and to the validation :param dataset_directory: the parent directory in which the preprocessed Task data is stored. This is required because the split information is stored in this directory. For running prediction only this input is not required and may be set to None :param batch_dice: compute dice loss for each sample and average over all samples in the batch or pretend the batch is a pseudo volume? :param stage: The plans file may contain several stages (used for lowres / highres / pyramid). Stage must be specified for training: if stage 1 exists then stage 1 is the high resolution stage, otherwise it's 0 :param unpack_data: if False, npz preprocessed data will not be unpacked to npy. This consumes less space but is considerably slower! Running unpack_data=False with 2d should never be done! IMPORTANT: If you inherit from nnUNetTrainer and the init args change then you need to redefine self.init_args in your init accordingly. Otherwise checkpoints won't load properly! """ super(nnUNetTrainer, self).__init__(deterministic, fp16, lam, gpu, save_dir) self.unpack_data = unpack_data self.init_args = (plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) # set through arguments from init self.stage = stage self.experiment_name = self.__class__.__name__ self.plans_file = plans_file self.output_folder = output_folder self.dataset_directory = dataset_directory self.output_folder_base = self.output_folder self.fold = fold self.plans = None # if we are running inference only then the self.dataset_directory is set (due to checkpoint loading) but it # irrelevant if self.dataset_directory is not None and isdir( self.dataset_directory): self.gt_niftis_folder = join(self.dataset_directory, "gt_segmentations") else: self.gt_niftis_folder = None self.folder_with_preprocessed_data = None # set in self.initialize() self.dl_tr = self.dl_val = None self.num_input_channels = self.num_classes = self.net_pool_per_axis = self.patch_size = self.batch_size = \ self.threeD = self.base_num_features = self.intensity_properties = self.normalization_schemes = \ self.net_num_pool_op_kernel_sizes = self.net_conv_kernel_sizes = None # loaded automatically from plans_file self.basic_generator_patch_size = self.data_aug_params = self.transpose_forward = self.transpose_backward = None self.batch_dice = batch_dice self.loss = DC_and_CE_loss( { 'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False, 'square': False }, {}) self.online_eval_foreground_dc = [] self.online_eval_tp = [] self.online_eval_fp = [] self.online_eval_fn = [] self.classes = self.do_dummy_2D_aug = self.use_mask_for_norm = self.only_keep_largest_connected_component = \ self.min_region_size_per_class = self.min_size_per_class = None self.inference_pad_border_mode = "constant" self.inference_pad_kwargs = {'constant_values': 0} self.update_fold(fold) self.pad_all_sides = None self.lr_scheduler_eps = 1e-3 self.lr_scheduler_patience = 30 self.initial_lr = 3e-4 self.weight_decay = 3e-5 self.oversample_foreground_percent = 0.33 def update_fold(self, fold): """ used to swap between folds for inference (ensemble of models from cross-validation) DO NOT USE DURING TRAINING AS THIS WILL NOT UPDATE THE DATASET SPLIT AND THE DATA AUGMENTATION GENERATORS :param fold: :return: """ if fold is not None: if isinstance(fold, str): assert fold == "all", "if self.fold is a string then it must be \'all\'" if self.output_folder.endswith("%s" % str(self.fold)): self.output_folder = self.output_folder_base self.output_folder = join(self.output_folder, "%s" % str(fold)) else: if self.output_folder.endswith("fold_%s" % str(self.fold)): self.output_folder = self.output_folder_base self.output_folder = join(self.output_folder, "fold_%s" % str(fold)) self.fold = fold def setup_DA_params(self): if self.threeD: self.data_aug_params = default_3D_augmentation_params if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params[ "rotation_x"] = default_2D_augmentation_params[ "rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params[ "mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size( self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array( [self.patch_size[0]] + list(self.basic_generator_patch_size)) patch_size_for_spatialtransform = self.patch_size[1:] else: self.basic_generator_patch_size = get_patch_size( self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) patch_size_for_spatialtransform = self.patch_size self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params[ 'patch_size_for_spatialtransform'] = patch_size_for_spatialtransform def initialize(self, training=True, force_load_plans=False): """ For prediction of test cases just set training=False, this will prevent loading of training data and training batchgenerator initialization :param training: :return: """ maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() self.AutoAugment = AutoAugment( self.data_aug_params['patch_size_for_spatialtransform'], self.data_aug_params) self.folder_with_preprocessed_data = join( self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: self.print_to_log_file("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) self.print_to_log_file("done") else: self.print_to_log_file( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") self.tr_gen, self.val_gen = get_default_augmentation( self.dl_tr, self.dl_val, self.data_aug_params['patch_size_for_spatialtransform'], self.data_aug_params) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network_optimizer_and_scheduler() # assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) self.was_initialized = True def initialize_network_optimizer_and_scheduler(self): """ This is specific to the U-Net and must be adapted for other network architectures :return: """ # self.print_to_log_file(self.net_num_pool_op_kernel_sizes) # self.print_to_log_file(self.net_conv_kernel_sizes) net_numpool = len(self.net_num_pool_op_kernel_sizes) if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, net_numpool, 2, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, amsgrad=True) self.lr_scheduler = lr_scheduler.ReduceLROnPlateau( self.optimizer, mode='min', factor=0.2, patience=self.lr_scheduler_patience, verbose=True, threshold=self.lr_scheduler_eps, threshold_mode="abs") gpu_ids = [int(x) for x in self.gpu.split(",")] if len(gpu_ids) > 1: self.network = torch.nn.DataParallel(self.network.cuda(), device_ids=gpu_ids) else: self.network = self.network.cuda() self.network.inference_apply_nonlin = softmax_helper def plot_network_architecture(self): try: from batchgenerators.utilities.file_and_folder_operations import join import hiddenlayer as hl g = hl.build_graph(self.network, torch.rand((1, self.num_input_channels, *self.patch_size)).cuda(), transforms=None) g.save(join(self.output_folder, "network_architecture.pdf")) del g except Exception as e: self.print_to_log_file("Unable to plot network architecture:") self.print_to_log_file(e) finally: torch.cuda.empty_cache() def run_training(self): dct = OrderedDict() for k in self.__dir__(): if not k.startswith("__"): if not callable(getattr(self, k)): dct[k] = str(getattr(self, k)) del dct['plans'] del dct['intensity_properties'] del dct['dataset'] del dct['dataset_tr'] del dct['dataset_val'] save_json(dct, join(self.output_folder, "debug.json")) import shutil shutil.copy(self.plans_file, join(self.output_folder_base, "plans.pkl")) super(nnUNetTrainer, self).run_training() def load_plans_file(self): """ This is what actually configures the entire experiment. The plans file is generated by experiment planning :return: """ self.plans = load_pickle(self.plans_file) def process_plans(self, plans): if self.stage is None: assert len(list(plans['plans_per_stage'].keys())) == 1, \ "If self.stage is None then there can be only one stage in the plans file. That seems to not be the " \ "case. Please specify which stage of the cascade must be trained" self.stage = list(plans['plans_per_stage'].keys())[0] self.plans = plans stage_plans = self.plans['plans_per_stage'][self.stage] self.batch_size = stage_plans['batch_size'] self.net_pool_per_axis = stage_plans['num_pool_per_axis'] self.patch_size = np.array(stage_plans['patch_size']).astype(int) self.do_dummy_2D_aug = stage_plans['do_dummy_2D_data_aug'] self.net_num_pool_op_kernel_sizes = stage_plans['pool_op_kernel_sizes'] self.net_conv_kernel_sizes = stage_plans['conv_kernel_sizes'] self.pad_all_sides = None # self.patch_size self.intensity_properties = plans['dataset_properties'][ 'intensityproperties'] self.normalization_schemes = plans['normalization_schemes'] self.base_num_features = plans['base_num_features'] self.num_input_channels = plans['num_modalities'] self.num_classes = plans[ 'num_classes'] + 1 # background is no longer in num_classes self.classes = plans['all_classes'] self.use_mask_for_norm = plans['use_mask_for_norm'] self.only_keep_largest_connected_component = plans[ 'keep_only_largest_region'] self.min_region_size_per_class = plans['min_region_size_per_class'] self.min_size_per_class = None # DONT USE THIS. plans['min_size_per_class'] if plans.get('transpose_forward') is None or plans.get( 'transpose_backward') is None: print( "WARNING! You seem to have data that was preprocessed with a previous version of nnU-Net. " "You should rerun preprocessing. We will proceed and assume that both transpose_foward " "and transpose_backward are [0, 1, 2]. If that is not correct then weird things will happen!" ) plans['transpose_forward'] = [0, 1, 2] plans['transpose_backward'] = [0, 1, 2] self.transpose_forward = plans['transpose_forward'] self.transpose_backward = plans['transpose_backward'] if len(self.patch_size) == 2: self.threeD = False elif len(self.patch_size) == 3: self.threeD = True else: raise RuntimeError("invalid patch size in plans file: %s" % str(self.patch_size)) def load_dataset(self): self.dataset = load_dataset(self.folder_with_preprocessed_data) def get_basic_generators(self): self.load_dataset() self.do_split() if self.threeD: dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, False, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, False, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) else: dl_tr = DataLoader2D( self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, transpose=None, # self.plans.get('transpose_forward'), oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) dl_val = DataLoader2D( self.dataset_val, self.patch_size, self.patch_size, self.batch_size, transpose=None, # self.plans.get('transpose_forward'), oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) return dl_tr, dl_val def preprocess_patient(self, input_files): """ Used to predict new unseen data. Not used for the preprocessing of the training/test data :param input_files: :return: """ from nnunet.preprocessing.preprocessing import GenericPreprocessor, PreprocessorFor2D if self.threeD: preprocessor = GenericPreprocessor(self.normalization_schemes, self.use_mask_for_norm, self.transpose_forward, self.intensity_properties) else: preprocessor = PreprocessorFor2D(self.normalization_schemes, self.use_mask_for_norm, self.transpose_forward, self.intensity_properties) d, s, properties = preprocessor.preprocess_test_case( input_files, self.plans['plans_per_stage'][self.stage]['current_spacing']) return d, s, properties def preprocess_predict_nifti(self, input_files, output_file=None, softmax_ouput_file=None): """ Use this to predict new data :param input_files: :param output_file: :param softmax_ouput_file: :return: """ print("preprocessing...") d, s, properties = self.preprocess_patient(input_files) print("predicting...") pred = self.predict_preprocessed_data_return_softmax( d, self.data_aug_params["mirror"], 1, False, 1, self.data_aug_params['mirror_axes'], True, True, 2, self.patch_size, True) pred = pred.transpose([0] + [i + 1 for i in self.transpose_backward]) print("resampling to original spacing and nifti export...") save_segmentation_nifti_from_softmax(pred, output_file, properties, 3, None, None, None, softmax_ouput_file, None) print("done") def predict_preprocessed_data_return_softmax(self, data, do_mirroring, num_repeats, use_train_mode, batch_size, mirror_axes, tiled, tile_in_z, step, min_size, use_gaussian): """ Don't use this. If you need softmax output, use preprocess_predict_nifti and set softmax_output_file. :param data: :param do_mirroring: :param num_repeats: :param use_train_mode: :param batch_size: :param mirror_axes: :param tiled: :param tile_in_z: :param step: :param min_size: :param use_gaussian: :param use_temporal: :return: """ assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) if isinstance(self.network, torch.nn.DataParallel): model = self.network.module else: model = self.network return model.predict_3D(data, do_mirroring, num_repeats, use_train_mode, batch_size, mirror_axes, tiled, tile_in_z, step, min_size, use_gaussian=use_gaussian, pad_border_mode=self.inference_pad_border_mode, pad_kwargs=self.inference_pad_kwargs)[2] def validate(self, do_mirroring=True, use_train_mode=False, tiled=True, step=2, save_softmax=True, use_gaussian=True, compute_global_dice=True, override=True, validation_folder_name='validation'): """ 2018_12_05: I added global accumulation of TP, FP and FN for the validation in here. This is because I believe that selecting models is easier when computing the Dice globally instead of independently for each case and then averaging over cases. The Lung dataset in particular is very unstable because of the small size of the Lung Lesions. My theory is that even though the global Dice is different than the acutal target metric it is still a good enough substitute that allows us to get a lot more stable results when rerunning the same experiment twice. FYI: computer vision community uses the global jaccard for the evaluation of Cityscapes etc, not the per-image jaccard averaged over images. The reason I am accumulating TP/FP/FN here and not from the nifti files (which are used by our Evaluator) is that all predictions made here will have identical voxel spacing whereas voxel spacings in the nifti files will be different (which we could compensate for by using the volume per voxel but that would require the evaluator to understand spacings which is does not at this point) :param do_mirroring: :param use_train_mode: :param mirror_axes: :param tiled: :param tile_in_z: :param step: :param use_nifti: :param save_softmax: :param use_gaussian: :param use_temporal_models: :return: """ assert self.was_initialized, "must initialize, ideally with checkpoint (or train first)" if self.dataset_val is None: self.load_dataset() self.do_split() output_folder = join(self.output_folder, validation_folder_name) maybe_mkdir_p(output_folder) if do_mirroring: mirror_axes = self.data_aug_params['mirror_axes'] else: mirror_axes = () pred_gt_tuples = [] export_pool = Pool(4) results = [] global_tp = OrderedDict() global_fp = OrderedDict() global_fn = OrderedDict() for k in self.dataset_val.keys(): print(k) properties = self.dataset[k]['properties'] fname = properties['list_of_data_files'][0].split("/")[-1][:-12] if override or (not isfile(join(output_folder, fname + ".nii.gz"))): data = np.load(self.dataset[k]['data_file'])['data'] print(k, data.shape) data[-1][data[-1] == -1] = 0 softmax_pred = self.predict_preprocessed_data_return_softmax( data[:-1], do_mirroring, 1, use_train_mode, 1, mirror_axes, tiled, True, step, self.patch_size, use_gaussian=use_gaussian) if compute_global_dice: predicted_segmentation = softmax_pred.argmax(0) gt_segmentation = data[-1] labels = properties['classes'] labels = [int(i) for i in labels if i > 0] for l in labels: if l not in global_fn.keys(): global_fn[l] = 0 if l not in global_fp.keys(): global_fp[l] = 0 if l not in global_tp.keys(): global_tp[l] = 0 conf = ConfusionMatrix( (predicted_segmentation == l).astype(int), (gt_segmentation == l).astype(int)) conf.compute() global_fn[l] += conf.fn global_fp[l] += conf.fp global_tp[l] += conf.tp softmax_pred = softmax_pred.transpose( [0] + [i + 1 for i in self.transpose_backward]) if save_softmax: softmax_fname = join(output_folder, fname + ".npz") else: softmax_fname = None """There is a problem with python process communication that prevents us from communicating obejcts larger than 2 GB between processes (basically when the length of the pickle string that will be sent is communicated by the multiprocessing.Pipe object then the placeholder (\%i I think) does not allow for long enough strings (lol). This could be fixed by changing i to l (for long) but that would require manually patching system python code. We circumvent that problem here by saving softmax_pred to a npy file that will then be read (and finally deleted) by the Process. save_segmentation_nifti_from_softmax can take either filename or np.ndarray and will handle this automatically""" if np.prod(softmax_pred.shape) > (2e9 / 4 * 0.9): # *0.9 just to be save np.save(join(output_folder, fname + ".npy"), softmax_pred) softmax_pred = join(output_folder, fname + ".npy") results.append( export_pool.starmap_async( save_segmentation_nifti_from_softmax, ((softmax_pred, join(output_folder, fname + ".nii.gz"), properties, 3, None, None, None, softmax_fname, None), ))) # save_segmentation_nifti_from_softmax(softmax_pred, join(output_folder, fname + ".nii.gz"), # properties, 3, None, None, # None, # softmax_fname, # None) pred_gt_tuples.append([ join(output_folder, fname + ".nii.gz"), join(self.gt_niftis_folder, fname + ".nii.gz") ]) _ = [i.get() for i in results] print("finished prediction, now evaluating...") task = self.dataset_directory.split("/")[-1] job_name = self.experiment_name _ = aggregate_scores( pred_gt_tuples, labels=list(range(self.num_classes)), json_output_file=join(output_folder, "summary.json"), json_name=job_name + " val tiled %s" % (str(tiled)), json_author="Fabian", json_task=task, num_threads=3) if compute_global_dice: global_dice = OrderedDict() all_labels = list(global_fn.keys()) for l in all_labels: global_dice[int(l)] = float( 2 * global_tp[l] / (2 * global_tp[l] + global_fn[l] + global_fp[l])) write_json(global_dice, join(output_folder, "global_dice.json")) def run_online_evaluation(self, output, target): with torch.no_grad(): num_classes = output.shape[1] output_softmax = softmax_helper(output) output_seg = output_softmax.argmax(1) target = target[:, 0] axes = tuple(range(1, len(target.shape))) tp_hard = torch.zeros( (target.shape[0], num_classes - 1)).to(output_seg.device.index) fp_hard = torch.zeros( (target.shape[0], num_classes - 1)).to(output_seg.device.index) fn_hard = torch.zeros( (target.shape[0], num_classes - 1)).to(output_seg.device.index) for c in range(1, num_classes): tp_hard[:, c - 1] = sum_tensor( (output_seg == c).float() * (target == c).float(), axes=axes) fp_hard[:, c - 1] = sum_tensor( (output_seg == c).float() * (target != c).float(), axes=axes) fn_hard[:, c - 1] = sum_tensor( (output_seg != c).float() * (target == c).float(), axes=axes) tp_hard = tp_hard.sum(0, keepdim=False).detach().cpu().numpy() fp_hard = fp_hard.sum(0, keepdim=False).detach().cpu().numpy() fn_hard = fn_hard.sum(0, keepdim=False).detach().cpu().numpy() self.online_eval_foreground_dc.append( list((2 * tp_hard) / (2 * tp_hard + fp_hard + fn_hard + 1e-8))) self.online_eval_tp.append(list(tp_hard)) self.online_eval_fp.append(list(fp_hard)) self.online_eval_fn.append(list(fn_hard)) def finish_online_evaluation(self): self.online_eval_tp = np.sum(self.online_eval_tp, 0) self.online_eval_fp = np.sum(self.online_eval_fp, 0) self.online_eval_fn = np.sum(self.online_eval_fn, 0) global_dc_per_class = [ i for i in [ 2 * i / (2 * i + j + k) for i, j, k in zip(self.online_eval_tp, self.online_eval_fp, self.online_eval_fn) ] if not np.isnan(i) ] self.all_val_eval_metrics.append(np.mean(global_dc_per_class)) self.print_to_log_file("Val glob dc per class:", str(global_dc_per_class)) self.online_eval_foreground_dc = [] self.online_eval_tp = [] self.online_eval_fp = [] self.online_eval_fn = [] def save_checkpoint(self, fname, save_optimizer=True): super(nnUNetTrainer, self).save_checkpoint(fname, save_optimizer) info = OrderedDict() info['init'] = self.init_args info['name'] = self.__class__.__name__ info['class'] = str(self.__class__) info['plans'] = self.plans write_pickle(info, fname + ".pkl")
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases input_patch_size = new_median_shape network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) ref = Generic_UNet.use_this_for_batch_size_computation_3D here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: # find the largest axis. If patch is isotropic, pick the axis with the largest spacing if len(np.unique(new_shp)) == 1: axis_to_be_reduced = np.argsort(current_spacing)[-1] else: axis_to_be_reduced = np.argsort(new_shp)[-1] tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props_poolLateV2(tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) print(new_shp) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what works with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, self.unet_min_batch_size) batch_size = min(batch_size, max_batch_size) do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[0] ) > self.anisotropy_threshold plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ Computation of input patch size starts out with the new median shape (in voxels) of a dataset. This is opposed to prior experiments where I based it on the median size in mm. The rationale behind this is that for some organ of interest the acquisition method will most likely be chosen such that the field of view and voxel resolution go hand in hand to show the doctor what they need to see. This assumption may be violated for some modalities with anisotropy (cine MRI) but we will have t live with that. In future experiments I will try to 1) base input patch size match aspect ratio of input size in mm (instead of voxels) and 2) to try to enforce that we see the same 'distance' in all directions (try to maintain equal size in mm of patch) The patches created here attempt keep the aspect ratio of the new_median_shape :param current_spacing: :param original_spacing: :param original_shape: :param num_cases: :return: """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases # the next line is what we had before as a default. The patch size had the same aspect ratio as the median shape of a patient. We swapped t # input_patch_size = new_median_shape # compute how many voxels are one mm input_patch_size = 1 / np.array(current_spacing) # normalize voxels per mm input_patch_size /= input_patch_size.mean() # create an isotropic patch of size 512x512x512mm input_patch_size *= 1 / min( input_patch_size) * 512 # to get a starting value input_patch_size = np.round(input_patch_size).astype(int) # clip it to the median shape of the dataset because patches larger then that make not much sense input_patch_size = [ min(i, j) for i, j in zip(input_patch_size, new_median_shape) ] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) ref = Generic_UNet.use_this_for_batch_size_computation_3D here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: axis_to_be_reduced = np.argsort(new_shp / new_median_shape)[-1] tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props_poolLateV2(tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) # print(new_shp) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what works with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, self.unet_min_batch_size) batch_size = max(1, min(batch_size, max_batch_size)) do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[0] ) > self.anisotropy_threshold plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan
def test_calculate_metric(iter_nums): if args.net == 'unet': # timm-efficientnet performs slightly worse. if not args.vis_mode: backbone_type = re.sub("^eff", "efficientnet", args.backbone_type) net = smp.Unet(backbone_type, classes=args.num_classes, encoder_weights='imagenet') else: net = VanillaUNet(n_channels=3, num_classes=args.num_classes) elif args.net == 'unet-scratch': # net = UNet(num_classes=args.num_classes) net = VanillaUNet(n_channels=3, num_classes=args.num_classes, use_polyformer=args.polyformer_mode, num_modes=args.num_modes) elif args.net == 'nestedunet': net = NestedUNet(num_classes=args.num_classes) elif args.net == 'unet3plus': net = UNet_3Plus(num_classes=args.num_classes) elif args.net == 'pranet': net = PraNet(num_classes=args.num_classes - 1) elif args.net == 'attunet': net = AttU_Net(output_ch=args.num_classes) elif args.net == 'attr2unet': net = R2AttU_Net(output_ch=args.num_classes) elif args.net == 'dunet': net = DeformableUNet(n_channels=3, n_classes=args.num_classes) elif args.net == 'setr': # Install mmcv first: # pip install mmcv-full==1.2.2 -f https://download.openmmlab.com/mmcv/dist/cu{Your CUDA Version}/torch{Your Pytorch Version}/index.html # E.g.: pip install mmcv-full==1.2.2 -f https://download.openmmlab.com/mmcv/dist/cu102/torch1.7.1/index.html from mmcv.utils import Config sys.path.append("networks/setr") from mmseg.models import build_segmentor task2config = { 'refuge': 'SETR_PUP_288x288_10k_refuge_context_bs_4.py', 'polyp': 'SETR_PUP_320x320_10k_polyp_context_bs_4.py' } setr_cfg = Config.fromfile("networks/setr/configs/SETR/{}".format(task2config[args.task_name])) net = build_segmentor(setr_cfg.model, train_cfg=setr_cfg.train_cfg, test_cfg=setr_cfg.test_cfg) # By default, net() calls forward_train(), which receives extra parameters, and returns losses. # net.forward_dummy() receives/returns the traditional input/output. # Relevant file: mmseg/models/segmentors/encoder_decoder.py net.forward = net.forward_dummy elif args.net == 'transunet': transunet_config = TransUNet_CONFIGS[args.backbone_type] transunet_config.n_classes = args.num_classes if args.backbone_type.find('R50') != -1: # The "patch" in TransUNet means grid-like patches of the input image. # The "patch" in our code means the whole input image after cropping/resizing (part of the augmentation) transunet_config.patches.grid = (int(args.patch_size[0] / transunet_config.patches.size[0]), int(args.patch_size[1] / transunet_config.patches.size[1])) net = TransUNet(transunet_config, img_size=args.patch_size, num_classes=args.num_classes) elif args.net.startswith('deeplab'): use_smp_deeplab = args.net.endswith('smp') if use_smp_deeplab: backbone_type = re.sub("^eff", "efficientnet", args.backbone_type) net = smp.DeepLabV3Plus(backbone_type, classes=args.num_classes, encoder_weights='imagenet') else: model_name = args.net + "_" + args.backbone_type model_map = { 'deeplabv3_resnet50': deeplab.deeplabv3_resnet50, 'deeplabv3plus_resnet50': deeplab.deeplabv3plus_resnet50, 'deeplabv3_resnet101': deeplab.deeplabv3_resnet101, 'deeplabv3plus_resnet101': deeplab.deeplabv3plus_resnet101, 'deeplabv3_mobilenet': deeplab.deeplabv3_mobilenet, 'deeplabv3plus_mobilenet': deeplab.deeplabv3plus_mobilenet } net = model_map[model_name](num_classes=args.num_classes, output_stride=8) elif args.net == 'nnunet': from nnunet.network_architecture.initialization import InitWeights_He from nnunet.network_architecture.generic_UNet import Generic_UNet net = Generic_UNet( input_channels=3, base_num_features=32, num_classes=args.num_classes, num_pool=7, num_conv_per_stage=2, feat_map_mul_on_downscale=2, norm_op=nn.InstanceNorm2d, norm_op_kwargs={'eps': 1e-05, 'affine': True}, dropout_op_kwargs={'p': 0, 'inplace': True}, nonlin_kwargs={'negative_slope': 0.01, 'inplace': True}, final_nonlin=(lambda x: x), weightInitializer=InitWeights_He(1e-2), pool_op_kernel_sizes=[[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]], conv_kernel_sizes=([[3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3]]), upscale_logits=False, convolutional_pooling=True, convolutional_upsampling=True, ) net.inference_apply_nonlin = (lambda x: F.softmax(x, 1)) elif args.net == 'segtran': get_default(args, 'num_modes', default_settings, -1, [args.net, 'num_modes', args.in_fpn_layers]) set_segtran2d_config(args) print(args) net = Segtran2d(config) else: breakpoint() net.cuda() net.eval() if args.robust_ref_cp_path: refnet = copy.deepcopy(net) print("Reference network created") load_model(refnet, args, args.robust_ref_cp_path) else: refnet = None # Currently colormap is used only for OCT task. colormap = get_seg_colormap(args.num_classes, return_torch=True).cuda() # prepred: pre-prediction. postpred: post-prediction. task2mask_prepred = { 'refuge': refuge_map_mask, 'polyp': polyp_map_mask, 'oct': partial(index_to_onehot, num_classes=args.num_classes) } task2mask_postpred = { 'refuge': refuge_inv_map_mask, 'polyp': polyp_inv_map_mask, 'oct': partial(onehot_inv_map, colormap=colormap) } mask_prepred_mapping_func = task2mask_prepred[args.task_name] mask_postpred_mapping_funcs = [ task2mask_postpred[args.task_name] ] if args.do_remove_frag: remove_frag = lambda segmap: remove_fragmentary_segs(segmap, 255) mask_postpred_mapping_funcs.append(remove_frag) if not args.checkpoint_dir: if args.vis_mode is not None: visualize_model(net, args.vis_mode, args.vis_layers, args.patch_size, db_test) return if args.eval_robustness: eval_robustness(args, net, refnet, testloader, mask_prepred_mapping_func) return allcls_avg_metric = None all_results = np.zeros((args.num_classes, len(iter_nums))) for iter_idx, iter_num in enumerate(iter_nums): if args.checkpoint_dir: checkpoint_path = os.path.join(args.checkpoint_dir, 'iter_' + str(iter_num) + '.pth') load_model(net, args, checkpoint_path) if args.vis_mode is not None: visualize_model(net, args.vis_mode, args.vis_layers, args.patch_size, db_test) continue if args.eval_robustness: eval_robustness(args, net, refnet, testloader, mask_prepred_mapping_func) continue save_results = args.save_results and (not args.test_interp) if save_results: test_save_paths = [] test_save_dirs = [] test_save_dir_tmpl = "%s-%s-%s-%d" %(args.net, args.job_name, timestamp, iter_num) for suffix in ("-soft", "-%.1f" %args.mask_thres): test_save_dir = test_save_dir_tmpl + suffix test_save_path = "../prediction/%s" %(test_save_dir) if not os.path.exists(test_save_path): os.makedirs(test_save_path) test_save_dirs.append(test_save_dir) test_save_paths.append(test_save_path) else: test_save_paths = None test_save_dirs = None if args.save_features_img_count > 0: args.save_features_file_path = "%s-%s-feat-%s.pth" %(args.net, args.job_name, timestamp) else: args.save_features_file_path = None allcls_avg_metric, allcls_metric_count = \ test_all_cases(net, testloader, task_name=args.task_name, num_classes=args.num_classes, mask_thres=args.mask_thres, model_type=args.net, orig_input_size=args.orig_input_size, patch_size=args.patch_size, stride=(args.orig_input_size[0] // 2, args.orig_input_size[1] // 2), test_save_paths=test_save_paths, out_origsize=args.out_origsize, mask_prepred_mapping_func=mask_prepred_mapping_func, mask_postpred_mapping_funcs=mask_postpred_mapping_funcs, reload_mask=args.reload_mask, test_interp=args.test_interp, save_features_img_count=args.save_features_img_count, save_features_file_path=args.save_features_file_path, verbose=args.verbose_output) print("Iter-%d scores on %d images:" %(iter_num, allcls_metric_count[0])) dice_sum = 0 for cls in range(1, args.num_classes): dice = allcls_avg_metric[cls-1] print('class %d: dice = %.3f' %(cls, dice)) dice_sum += dice all_results[cls, iter_idx] = dice avg_dice = dice_sum / (args.num_classes - 1) print("Average dice: %.3f" %avg_dice) if args.net == 'segtran': max_attn, avg_attn, clamp_count, call_count = \ [ segtran_shared.__dict__[v] for v in ('max_attn', 'avg_attn', 'clamp_count', 'call_count') ] print("max_attn={:.2f}, avg_attn={:.2f}, clamp_count={}, call_count={}".format( max_attn, avg_attn, clamp_count, call_count)) if save_results: FNULL = open(os.devnull, 'w') for pred_type, test_save_dir, test_save_path in zip(('soft', 'hard'), test_save_dirs, test_save_paths): do_tar = subprocess.run(["tar", "cvf", "%s.tar" %test_save_dir, test_save_dir], cwd="../prediction", stdout=FNULL, stderr=subprocess.STDOUT) # print(do_tar) print("{} tarball:\n{}.tar".format(pred_type, os.path.abspath(test_save_path))) np.set_printoptions(precision=3, suppress=True) print(all_results[1:]) return allcls_avg_metric
class nnUNetMultiTrainerV2(nnUNetTrainer): """ Info for Fabian: same as internal nnUNetTrainerV2_2 """ def __init__(self, plans_file, fold, tasks, tags, output_folder_dict=None, dataset_directory_dict=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): """ :param deterministic: :param fold: can be either [0 ... 5) for cross-validation, 'all' to train on all available training data or None if you wish to load some checkpoint and do inference only :param plans_file: the pkl file generated by preprocessing. This file will determine all design choices :param subfolder_with_preprocessed_data: must be a subfolder of dataset_directory (just the name of the folder, not the entire path). This is where the preprocessed data lies that will be used for network training. We made this explicitly available so that differently preprocessed data can coexist and the user can choose what to use. Can be None if you are doing inference only. :param output_folder: where to store parameters, plot progress and to the validation :param dataset_directory: the parent directory in which the preprocessed Task data is stored. This is required because the split information is stored in this directory. For running prediction only this input is not required and may be set to None :param batch_dice: compute dice loss for each sample and average over all samples in the batch or pretend the batch is a pseudo volume? :param stage: The plans file may contain several stages (used for lowres / highres / pyramid). Stage must be specified for training: if stage 1 exists then stage 1 is the high resolution stage, otherwise it's 0 :param unpack_data: if False, npz preprocessed data will not be unpacked to npy. This consumes less space but is considerably slower! Running unpack_data=False with 2d should never be done! IMPORTANT: If you inherit from nnUNetTrainer and the init args change then you need to redefine self.init_args in your init accordingly. Otherwise checkpoints won't load properly! """ self.fp16 = fp16 self.amp_initialized = False self.x_tags = None if deterministic: np.random.seed(12345) torch.manual_seed(12345) if torch.cuda.is_available(): torch.cuda.manual_seed_all(12345) cudnn.deterministic = True torch.backends.cudnn.benchmark = False else: cudnn.deterministic = False torch.backends.cudnn.benchmark = True ################# SET THESE IN self.initialize() ################################### self.network: Tuple[SegmentationNetwork, nn.DataParallel] = None self.optimizer = None self.lr_scheduler = None self.tr_gen = self.val_gen = None self.was_initialized = False ################# SET THESE IN INIT ################################################ self.output_folder = None self.fold = None self.dataset_directory = None ################# SET THESE IN LOAD_DATASET OR DO_SPLIT ############################ self.dataset = None # these can be None for inference mode # do not need to be used, they just appear if you are using the suggested load_dataset_and_do_split self.dataset_tr = self.dataset_val = None ################# THESE DO NOT NECESSARILY NEED TO BE MODIFIED ##################### self.patience = 50 self.val_eval_criterion_alpha = 0.9 # alpha * old + (1-alpha) * new # if this is too low then the moving average will be too noisy and the training may terminate early. If it is # too high the training will take forever self.train_loss_MA_alpha = 0.93 # alpha * old + (1-alpha) * new # new MA must be at least this much better (smaller) self.train_loss_MA_eps = 5e-4 self.save_every = 1 self.save_latest_only = True self.max_num_epochs = 500 self.stage_2_start_epoch = 120 self.num_batches_per_epoch = 250 self.num_val_batches_per_epoch = 50 self.also_val_in_tr_mode = False # the network will not terminate training if the lr is still above this threshold self.lr_threshold = 1e-6 ################# LEAVE THESE ALONE ################################################ self.val_eval_criterion_MA = None self.train_loss_MA = None self.best_val_eval_criterion_MA = None self.best_MA_tr_loss_for_patience = None self.best_epoch_based_on_MA_tr_loss = None self.all_tr_losses = [] self.all_val_losses = [] self.all_val_losses_tr_mode = [] self.all_val_eval_metrics = [] # does not have to be used self.epoch = 0 # self.need_updateGT = False #update p self.log_file = None self.deterministic = deterministic self.use_progress_bar = True if 'nnunet_use_progress_bar' in os.environ.keys(): self.use_progress_bar = bool( int(os.environ['nnunet_use_progress_bar'])) ################################################################# self.unpack_data = unpack_data self.init_args = (plans_file, fold, output_folder_dict, dataset_directory_dict, batch_dice, stage, unpack_data, deterministic, fp16) # set through arguments from init self.stage = stage self.experiment_name = self.__class__.__name__ self.plans_file = plans_file self.output_folder_dict = output_folder_dict self.output_folder = output_folder_dict[tasks[0]] self.dataset_directory_dict = dataset_directory_dict self.output_folder_base = self.output_folder self.fold = fold self.tasks = tasks self.tags = tags self.plans = None # if we are running inference only then the self.dataset_directory is set (due to checkpoint loading) but it # irrelevant self.gt_niftis_folder_dict = {} for task in tasks: dataset_directory = self.dataset_directory_dict[task] if dataset_directory is not None and isdir(dataset_directory): self.gt_niftis_folder_dict[task] = join( dataset_directory, "gt_segmentations") else: self.gt_niftis_folder_dict[task] = None self.gt_niftis_folder = self.gt_niftis_folder_dict[ self.tasks[0]] # 0 gt_nii self.folder_with_preprocessed_data = None # set in self.initialize() self.dl_tr = self.dl_val = None self.num_input_channels = self.num_classes = self.net_pool_per_axis = self.patch_size = self.batch_size = \ self.threeD = self.base_num_features = self.intensity_properties = self.normalization_schemes = \ self.net_num_pool_op_kernel_sizes = self.net_conv_kernel_sizes = None # loaded automatically from plans_file self.basic_generator_patch_size = self.data_aug_params = self.transpose_forward = self.transpose_backward = None self.batch_dice = batch_dice # self.loss = None self.online_eval_foreground_dc = [] self.online_eval_tp = [] self.online_eval_fp = [] self.online_eval_fn = [] self.classes = self.do_dummy_2D_aug = self.use_mask_for_norm = self.only_keep_largest_connected_component = \ self.min_region_size_per_class = self.min_size_per_class = None self.inference_pad_border_mode = "constant" self.inference_pad_kwargs = {'constant_values': 0} self.update_fold(fold) self.pad_all_sides = None self.lr_scheduler_eps = 1e-3 self.lr_scheduler_patience = 30 self.initial_lr = 3e-4 self.weight_decay = 3e-5 self.oversample_foreground_percent = 0.33 self.conv_per_stage = None self.regions_class_order = None self.initial_lr = 1e-2 self.deep_supervision_scales = None self.ds_loss_weights = None self.pin_memory = True self.loss = DC_CE_Marginal_Exclusion_loss( { 'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False }, {}) # self.loss = pann_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {}) # self.loss = DC_and_CE_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {}) def load_plans_file(self): """ This is what actually configures the entire experiment. The plans file is generated by experiment planning :return: """ self.plans = load_pickle(self.plans_file[self.tasks[0]]) def initialize(self, training=True, force_load_plans=False): """ - replaced get_default_augmentation with get_moreDA_augmentation - enforce to only run this code once - loss function wrapper for deep supervision :param training: :param force_load_plans: :return: """ if not self.was_initialized: maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() ################# Here we wrap the loss for deep supervision ############ # we need to know the number of outputs of the network net_numpool = len(self.net_num_pool_op_kernel_sizes) # print("---net_numpool:", net_numpool) #Task_100 MAB 5 class # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases # this gives higher resolution outputs more weight in the loss weights = np.array([1 / (2**i) for i in range(net_numpool)]) # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1 mask = np.array([True] + [ True if i < net_numpool - 1 else False for i in range(1, net_numpool) ]) weights[~mask] = 0 weights = weights / weights.sum() self.ds_loss_weights = weights # now wrap the loss # self.loss = MultipleOutputLoss2withTags_pann(self.loss, self.ds_loss_weights) self.loss = MultipleOutputLoss2withTags(self.loss, self.ds_loss_weights) ################# END ################### self.folder_with_preprocessed_data = {} self.dl_tr = [] self.dl_val = [] self.tr_gens = [] self.val_gens = [] for task in self.tasks: self.folder_with_preprocessed_data[task] = join( self.dataset_directory_dict[task], self.plans['data_identifier'] + "_stage%d" % self.stage) if training: dl_tr, dl_val = self.get_basic_generators(task) self.dl_tr.append(dl_tr) self.dl_val.append(dl_val) # print('%s.dl_tr raw data size:%d'%(task, len(dl_tr))) if self.unpack_data: print("unpacking dataset") unpack_dataset( self.folder_with_preprocessed_data[task]) print("done") else: print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") tr_gen, val_gen = get_moreDA_augmentation( # data augmentation dl_tr, dl_val, self. data_aug_params['patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, pin_memory=self.pin_memory) self.tr_gens.append(tr_gen) #tr_gen: multithreadaug.. self.val_gens.append(val_gen) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) print("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys()))) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass ################## dataset all in ########################### if training: self.tr_gen = switchable_generator(self.tr_gens) self.val_gen = switchable_generator(self.val_gens) self.initialize_network() self.initialize_optimizer_and_scheduler() assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) else: self.print_to_log_file( 'self.was_initialized is True, not running self.initialize again' ) self.was_initialized = True def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper def initialize_optimizer_and_scheduler(self): assert self.network is not None, "self.initialize_network must be called first" self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, momentum=0.99, nesterov=True) self.lr_scheduler = None def get_basic_generators(self, task): self.load_dataset(task) self.do_split(task) if self.threeD: dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, self.tags[task], False, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, self.tags[task], False, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) else: dl_tr = DataLoader2D( self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size, self.tags[task], # self.plans.get('transpose_forward'), transpose=None, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) dl_val = DataLoader2D( self.dataset_val, self.patch_size, self.patch_size, self.batch_size, self.tags[task], # self.plans.get('transpose_forward'), transpose=None, oversample_foreground_percent=self. oversample_foreground_percent, pad_mode="constant", pad_sides=self.pad_all_sides) return dl_tr, dl_val def load_dataset(self, task=None): if task is None: self.dataset = load_dataset( self.folder_with_preprocessed_data[self.tasks[0]]) else: self.dataset = load_dataset( self.folder_with_preprocessed_data[task]) def run_online_evaluation(self, output, target): """ due to deep supervision the return value and the reference are now lists of tensors. We only need the full resolution output because this is what we are interested in in the end. The others are ignored :param output: :param target: :return: """ target = target[0] output = output[0] return super().run_online_evaluation(output, target) def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, force_separate_z: bool = None, interpolation_order: int = 3, interpolation_order_z=0): """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().validate(do_mirroring, use_sliding_window, step_size, save_softmax, use_gaussian, overwrite, validation_folder_name, debug, all_in_gpu, force_separate_z=force_separate_z, interpolation_order=interpolation_order, interpolation_order_z=interpolation_order_z) self.network.do_ds = ds return ret def validate_specific_data(self, task, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = False, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, force_separate_z: bool = None, interpolation_order: int = 3, interpolation_order_z=0): ds = self.network.do_ds #? self.network.do_ds = False ########################################### current_mode = self.network.training self.network.eval() assert self.was_initialized, "must initialize, ideally with checkpoint (or train first)" self.load_dataset(task) self.do_split(task) # predictions as they come from the network go here self.output_folder = self.output_folder_dict[task] self.gt_niftis_folder = self.gt_niftis_folder_dict[task] output_folder = join(self.output_folder, 'fold_4', validation_folder_name) maybe_mkdir_p(output_folder) # this is for debug purposes my_input_args = { 'do_mirroring': do_mirroring, 'use_sliding_window': use_sliding_window, 'step_size': step_size, 'save_softmax': save_softmax, 'use_gaussian': use_gaussian, 'overwrite': overwrite, 'validation_folder_name': validation_folder_name, 'debug': debug, 'all_in_gpu': all_in_gpu, #? why not use 'force_separate_z': force_separate_z, 'interpolation_order': interpolation_order, 'interpolation_order_z': interpolation_order_z, } save_json(my_input_args, join(output_folder, "validation_args.json")) if do_mirroring: if not self.data_aug_params['do_mirror']: raise RuntimeError( "We did not train with mirroring so you cannot do inference with mirroring enabled" ) mirror_axes = self.data_aug_params['mirror_axes'] else: mirror_axes = () pred_gt_tuples = [] export_pool = Pool(default_num_threads) results = [] if '104' in task: #kidney temp_transpose = [0, 2, 3, 1] else: temp_transpose = [0, 1, 2, 3] for k in self.dataset_val.keys(): properties = self.dataset[k]['properties'] fname = properties['list_of_data_files'][0].split("/")[-1][:-12] if overwrite or (not isfile(join(output_folder, fname + ".nii.gz"))) or \ (save_softmax and not isfile(join(output_folder, fname + ".npz"))): data = np.load(self.dataset[k]['data_file'])['data'] print(k, data.shape) data[-1][data[-1] == -1] = 0 softmax_pred = self.predict_preprocessed_data_return_seg_and_softmax( data[:-1], do_mirroring, mirror_axes, use_sliding_window, step_size, use_gaussian, all_in_gpu=all_in_gpu)[1] softmax_pred = softmax_pred.transpose(temp_transpose) # softmax_pred = softmax_pred.transpose([0] + [i + 1 for i in self.transpose_backward]) if save_softmax: softmax_fname = join(output_folder, fname + ".npz") else: softmax_fname = None """There is a problem with python process communication that prevents us from communicating obejcts larger than 2 GB between processes (basically when the length of the pickle string that will be sent is communicated by the multiprocessing.Pipe object then the placeholder (\%i I think) does not allow for long enough strings (lol). This could be fixed by changing i to l (for long) but that would require manually patching system python code. We circumvent that problem here by saving softmax_pred to a npy file that will then be read (and finally deleted) by the Process. save_segmentation_nifti_from_softmax can take either filename or np.ndarray and will handle this automatically""" if np.prod(softmax_pred.shape) > ( 2e9 / 4 * 0.85): # *0.85 just to be save np.save(join(output_folder, fname + ".npy"), softmax_pred) softmax_pred = join(output_folder, fname + ".npy") # save_segmentation_nifti_from_softmax(softmax_pred, join(output_folder, fname + ".nii.gz"), # properties, interpolation_order, None, None, None, # softmax_fname, None, force_separate_z, # interpolation_order_z, task) results.append( export_pool.starmap_async( save_segmentation_nifti_from_softmax, ((softmax_pred, join(output_folder, fname + ".nii.gz"), properties, interpolation_order, None, None, None, softmax_fname, None, force_separate_z, interpolation_order_z, task), ))) pred_gt_tuples.append([ join(output_folder, fname + ".nii.gz"), join(self.gt_niftis_folder, fname + ".nii.gz") ]) _ = [i.get() for i in results] self.print_to_log_file("finished prediction") # evaluate raw predictions self.print_to_log_file("evaluation of raw predictions") # task = self.dataset_directory.split("/")[-1] job_name = self.experiment_name # x_tags = ['rightkidney','leftkidney'] x_tags = ['liver', 'spleen', 'pancreas', 'rightkidney', 'leftkidney'] if "100" in task: y_tags = x_tags elif "101" in task or "105" in task: y_tags = ['liver'] elif "102" in task: y_tags = ['spleen'] elif "103" in task: y_tags = ['pancreas'] elif "104" in task: y_tags = ['rightkidney', 'leftkidney'] elif "105" in task: #PrivateLiver y_tags = ['liver'] else: exit() all_score = aggregate_scores_withtags( pred_gt_tuples, labels=list(range(self.num_classes)), x_tags=x_tags, y_tags=y_tags, json_output_file=join(output_folder, "summary.json"), json_name=job_name + " val tiled %s" % (str(use_sliding_window)), json_author="Fabian", json_task=task, num_threads=default_num_threads) # in the old nnunet we would stop here. Now we add a postprocessing. This postprocessing can remove everything # except the largest connected component for each class. To see if this improves results, we do this for all # classes and then rerun the evaluation. Those classes for which this resulted in an improved dice score will # have this applied during inference as well # after this the final predictions for the vlaidation set can be found in validation_folder_name_base + "_postprocessed" # They are always in that folder, even if no postprocessing as applied! # detemining postprocesing on a per-fold basis may be OK for this fold but what if another fold finds another # postprocesing to be better? In this case we need to consolidate. At the time the consolidation is going to be # done we won't know what self.gt_niftis_folder was, so now we copy all the niftis into a separate folder to # be used later self.output_folder_base = self.output_folder gt_nifti_folder = join(self.output_folder_base, "gt_niftis") maybe_mkdir_p(gt_nifti_folder) for f in subfiles(self.gt_niftis_folder, suffix=".nii.gz"): success = False attempts = 0 e = None while not success and attempts < 10: try: shutil.copy(f, gt_nifti_folder) success = True except OSError as e: attempts += 1 sleep(1) if not success: print("Could not copy gt nifti file %s into folder %s" % (f, gt_nifti_folder)) if e is not None: raise e self.network.train(current_mode) ########################################### self.network.do_ds = ds # return ret def predict_preprocessed_data_return_seg_and_softmax( self, data: np.ndarray, do_mirroring: bool = True, mirror_axes: Tuple[int] = None, use_sliding_window: bool = True, step_size: float = 0.5, use_gaussian: bool = True, pad_border_mode: str = 'constant', pad_kwargs: dict = None, all_in_gpu: bool = True, verbose: bool = True) -> Tuple[np.ndarray, np.ndarray]: """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().predict_preprocessed_data_return_seg_and_softmax( data, do_mirroring, mirror_axes, use_sliding_window, step_size, use_gaussian, pad_border_mode, pad_kwargs, all_in_gpu, verbose) self.network.do_ds = ds return ret def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False): """ gradient clipping improves training stability :param data_generator: :param do_backprop: :param run_online_evaluation: :return: """ data_dict = next(data_generator) # length = get_length(data_generator) data = data_dict['data'] target = data_dict['target'] # self.x_tags = ['liver','spleen','pancreas','rightkidney','leftkidney'] #test-mk if self.x_tags is None: self.x_tags = [tag.lower() for tag in data_dict['tags']] y_tags = [tag.lower() for tag in data_dict['tags']] # print("------------------x_tags:",self.x_tags) # print("------------------y_tags:",y_tags) data = maybe_to_torch(data) target = maybe_to_torch(target) if torch.cuda.is_available(): data = to_cuda(data) target = to_cuda(target) self.optimizer.zero_grad() output = self.network(data) del data # loss = self.loss(output, target,self.x_tags,y_tags,need_updateGT=need_updateGT) loss = self.loss(output, target, self.x_tags, y_tags) if run_online_evaluation: self.run_online_evaluation(output, target) del target if do_backprop: if not self.fp16 or amp is None or not torch.cuda.is_available(): loss.backward() else: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() _ = clip_grad_norm_(self.network.parameters(), 12) self.optimizer.step() return loss.detach().cpu().numpy() def do_split(self, task=None): """ we now allow more than 5 splits. IMPORTANT: and fold > 4 will not be a real split but just another random 80:20 split of the data. You cannot run X-fold cross-validation with this code. It will always be a 5-fold CV. Folds > 4 will be independent from each other :return: """ if task is None: task = self.tasks[0] if self.fold == 'all' or self.fold < 5: #fold = 4 self.dataset_directory = self.dataset_directory_dict[task] return super().do_split() else: print("---------------!!!!!!!!--------------") rnd = np.random.RandomState(seed=12345 + self.fold) keys = np.sort(list(self.dataset.keys())) idx_tr = rnd.choice(len(keys), int(len(keys) * 0.8), replace=False) idx_val = [i for i in range(len(keys)) if i not in idx_tr] self.dataset_tr = OrderedDict() for i in idx_tr: self.dataset_tr[keys[i]] = self.dataset[keys[i]] self.dataset_val = OrderedDict() for i in idx_val: self.dataset_val[keys[i]] = self.dataset[keys[i]] def setup_DA_params(self): """ - we increase roation angle from [-15, 15] to [-30, 30] - scale range is now (0.7, 1.4), was (0.85, 1.25) - we don't do elastic deformation anymore :return: """ self.deep_supervision_scales = [[1, 1, 1]] + list( list(i) for i in 1 / np.cumprod( np.vstack(self.net_num_pool_op_kernel_sizes), axis=0))[:-1] if self.threeD: self.data_aug_params = default_3D_augmentation_params self.data_aug_params['rotation_x'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_y'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_z'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params[ "rotation_x"] = default_2D_augmentation_params[ "rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params[ "mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size( self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array( [self.patch_size[0]] + list(self.basic_generator_patch_size)) patch_size_for_spatialtransform = self.patch_size[1:] else: self.basic_generator_patch_size = get_patch_size( self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) patch_size_for_spatialtransform = self.patch_size self.data_aug_params["scale_range"] = (0.7, 1.4) self.data_aug_params["do_elastic"] = False self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params[ 'patch_size_for_spatialtransform'] = patch_size_for_spatialtransform self.data_aug_params["num_cached_per_thread"] = 2 def maybe_update_lr(self, epoch=None): """ if epoch is not None we overwrite epoch. Else we use epoch = self.epoch + 1 (maybe_update_lr is called in on_epoch_end which is called before epoch is incremented. herefore we need to do +1 here) :param epoch: :return: """ if epoch is None: ep = self.epoch + 1 else: ep = epoch self.optimizer.param_groups[0]['lr'] = poly_lr(ep, self.max_num_epochs, self.initial_lr, 0.9) self.print_to_log_file( "lr:", np.round(self.optimizer.param_groups[0]['lr'], decimals=6)) def on_epoch_end(self): """ overwrite patient-based early stopping. Always run to 1000 epochs :return: """ super().on_epoch_end() continue_training = self.epoch < self.max_num_epochs # it can rarely happen that the momentum of nnUNetTrainerV2 is too high for some dataset. If at epoch 100 the # estimated validation Dice is still 0 then we reduce the momentum from 0.99 to 0.95 if self.epoch == 100: if self.all_val_eval_metrics[-1] == 0: self.optimizer.param_groups[0]["momentum"] = 0.95 self.network.apply(InitWeights_He(1e-2)) self.print_to_log_file( "At epoch 100, the mean foreground Dice was 0. This can be caused by a too " "high momentum. High momentum (0.99) is good for datasets where it works, but " "sometimes causes issues such as this one. Momentum has now been reduced to " "0.95 and network weights have been reinitialized") return continue_training def run_training(self): """ if we run with -c then we need to set the correct lr for the first epoch, otherwise it will run the first continued epoch with self.initial_lr we also need to make sure deep supervision in the network is enabled for training, thus the wrapper :return: """ self.maybe_update_lr( self.epoch ) # if we dont overwrite epoch then self.epoch+1 is used which is not what we # want at the start of the training ds = self.network.do_ds self.network.do_ds = True # ret = super().run_training() ######################################################################################## dct = OrderedDict() for k in self.__dir__(): if not k.startswith("__"): if not callable(getattr(self, k)): dct[k] = str(getattr(self, k)) del dct['plans'] del dct['intensity_properties'] del dct['dataset'] del dct['dataset_tr'] del dct['dataset_val'] save_json(dct, join(self.output_folder, "debug.json")) import shutil shutil.copy(self.plans_file[self.tasks[0]], join(self.output_folder_base, "plans.pkl")) for i in range(len(self.tasks)): self.tr_gen.setPart(i) _ = self.tr_gen.next() _ = self.val_gen.next() self.tr_gen.setPart(0) if torch.cuda.is_available(): torch.cuda.empty_cache() # self._maybe_init_amp() self.plot_network_architecture() if cudnn.benchmark and cudnn.deterministic: warn( "torch.backends.cudnn.deterministic is True indicating a deterministic training is desired. " "But torch.backends.cudnn.benchmark is True as well and this will prevent deterministic training! " "If you want deterministic then set benchmark=False") maybe_mkdir_p(self.output_folder) if not self.was_initialized: self.initialize(True) flag = True while self.epoch < self.max_num_epochs: # self.need_updateGT=True self.print_to_log_file("\nepoch: ", self.epoch) epoch_start_time = time() train_losses_epoch = [] # train one epoch self.network.train() if self.epoch >= self.stage_2_start_epoch and flag: self.num_batches_per_epoch = 50 flag = False if self.use_progress_bar: with trange(self.num_batches_per_epoch) as tbar: for b in tbar: tbar.set_description("Epoch {}/{}".format( self.epoch + 1, self.max_num_epochs)) l = self.run_iteration(self.tr_gen, True) tbar.set_postfix(loss=l) train_losses_epoch.append(l) if self.epoch >= self.stage_2_start_epoch: for i in range(1, len(self.tasks)): self.tr_gen.setPart(i) _ = self.run_iteration(self.tr_gen, True) self.tr_gen.setPart(0) else: for _ in range(self.num_batches_per_epoch): l = self.run_iteration(self.tr_gen, True) train_losses_epoch.append(l) if self.epoch > self.stage_2_start_epoch: for i in range(1, len(self.tasks)): self.tr_gen.setPart(i) _ = self.run_iteration(self.tr_gen, True) self.tr_gen.setPart(0) self.all_tr_losses.append(np.mean(train_losses_epoch)) self.print_to_log_file("train loss : %.4f" % self.all_tr_losses[-1]) with torch.no_grad(): # validation with train=False self.network.eval() val_losses = [] for b in range(self.num_val_batches_per_epoch): l = self.run_iteration(self.val_gen, False, True) val_losses.append(l) self.all_val_losses.append(np.mean(val_losses)) self.print_to_log_file("validation loss: %.4f" % self.all_val_losses[-1]) if self.also_val_in_tr_mode: self.network.train() # validation with train=True val_losses = [] for b in range(self.num_val_batches_per_epoch): l = self.run_iteration(self.val_gen, False) val_losses.append(l) self.all_val_losses_tr_mode.append(np.mean(val_losses)) self.print_to_log_file( "validation loss (train=True): %.4f" % self.all_val_losses_tr_mode[-1]) self.update_train_loss_MA( ) # needed for lr scheduler and stopping of training continue_training = self.on_epoch_end() epoch_end_time = time() if not continue_training: # allows for early stopping break self.epoch += 1 self.print_to_log_file("This epoch took %f s\n" % (epoch_end_time - epoch_start_time)) self.epoch -= 1 # if we don't do this we can get a problem with loading model_final_checkpoint. self.save_checkpoint( join(self.output_folder, "model_final_checkpoint.model")) # now we can delete latest as it will be identical with final if isfile(join(self.output_folder, "model_latest.model")): os.remove(join(self.output_folder, "model_latest.model")) if isfile(join(self.output_folder, "model_latest.model.pkl")): os.remove(join(self.output_folder, "model_latest.model.pkl")) ######################################################################################### self.network.do_ds = ds
class nnUNetTrainerV2_noDeepSupervision(nnUNetTrainerV2): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) self.loss = DC_and_CE_loss( { 'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False }, {}) def setup_DA_params(self): """ we leave out the creation of self.deep_supervision_scales, so it remains None :return: """ if self.threeD: self.data_aug_params = default_3D_augmentation_params self.data_aug_params['rotation_x'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_y'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_z'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params[ "rotation_x"] = default_2D_augmentation_params[ "rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params[ "mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size( self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array( [self.patch_size[0]] + list(self.basic_generator_patch_size)) patch_size_for_spatialtransform = self.patch_size[1:] else: self.basic_generator_patch_size = get_patch_size( self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) patch_size_for_spatialtransform = self.patch_size self.data_aug_params["scale_range"] = (0.7, 1.4) self.data_aug_params["do_elastic"] = False self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params[ 'patch_size_for_spatialtransform'] = patch_size_for_spatialtransform def initialize(self, training=True, force_load_plans=False): """ removed deep supervision :return: """ if not self.was_initialized: maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() self.folder_with_preprocessed_data = join( self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: print("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) print("done") else: print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") assert self.deep_supervision_scales is None self.tr_gen, self.val_gen = get_moreDA_augmentation( self.dl_tr, self.dl_val, self.data_aug_params['patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, classes=None, pin_memory=self.pin_memory) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) else: self.print_to_log_file( 'self.was_initialized is True, not running self.initialize again' ) self.was_initialized = True def initialize_network(self): """ changed deep supervision to False :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper def run_online_evaluation(self, output, target): return nnUNetTrainer.run_online_evaluation(self, output, target)
def get_properties_for_stage(current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ Computation of input patch size starts out with the new median shape (in voxels) of a dataset. This is opposed to prior experiments where I based it on the median size in mm. The rationale behind this is that for some organ of interest the acquisition method will most likely be chosen such that the field of view and voxel resolution go hand in hand to show the doctor what they need to see. This assumption may be violated for some modalities with anisotropy (cine MRI) but we will have t live with that. In future experiments I will try to 1) base input patch size match aspect ratio of input size in mm (instead of voxels) and 2) to try to enforce that we see the same 'distance' in all directions (try to maintain equal size in mm of patch) :param current_spacing: :param original_spacing: :param original_shape: :param num_cases: :return: """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases # the next line is what we had before as a default. The patch size had the same aspect ratio as the median shape of a patient. We swapped t # input_patch_size = new_median_shape # compute how many voxels are one mm input_patch_size = 1 / np.array(current_spacing) # normalize voxels per mm input_patch_size /= input_patch_size.mean() # create an isotropic patch of size 512x512x512mm input_patch_size *= 1 / min( input_patch_size) * 512 # to get a starting value input_patch_size = np.round(input_patch_size).astype(int) # clip it to the median shape of the dataset because patches larger then that make not much sense input_patch_size = [ min(i, j) for i, j in zip(input_patch_size, new_median_shape) ] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(input_patch_size, FEATUREMAP_MIN_EDGE_LENGTH_BOTTLENECK, Generic_UNet.MAX_NUMPOOL_3D, current_spacing) ref = Generic_UNet.use_this_for_batch_size_computation_3D here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, Generic_UNet.BASE_NUM_FEATURES_3D, Generic_UNet.MAX_NUM_FILTERS_3D, num_modalities, num_classes, pool_op_kernel_sizes) while here > ref: argsrt = np.argsort(new_shp / new_median_shape)[::-1] pool_fct_per_axis = np.prod(pool_op_kernel_sizes, 0) bottleneck_size_per_axis = new_shp / pool_fct_per_axis shape_must_be_divisible_by = [ shape_must_be_divisible_by[i] if bottleneck_size_per_axis[i] > 4 else shape_must_be_divisible_by[i] / 2 for i in range(len(bottleneck_size_per_axis)) ] new_shp[argsrt[0]] -= shape_must_be_divisible_by[argsrt[0]] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(new_shp, FEATUREMAP_MIN_EDGE_LENGTH_BOTTLENECK, Generic_UNet.MAX_NUMPOOL_3D, current_spacing) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, Generic_UNet.BASE_NUM_FEATURES_3D, Generic_UNet.MAX_NUM_FILTERS_3D, num_modalities, num_classes, pool_op_kernel_sizes) print(new_shp) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what wirks with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, dataset_min_batch_size_cap) batch_size = min(batch_size, max_batch_size) do_dummy_2D_data_aug = ( max(input_patch_size) / input_patch_size[0] ) > RESAMPLING_SEPARATE_Z_ANISOTROPY_THRESHOLD plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape, dtype=np.int64) * num_cases input_patch_size = new_median_shape[1:] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing[1:], input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool) # we pretend to use 30 feature maps. This will yield the same configuration as in V1. The larger memory # footpring of 32 vs 30 is mor ethan offset by the fp16 training. We make fp16 training default # Reason for 32 vs 30 feature maps is that 32 is faster in fp16 training (because multiple of 8) ref = Generic_UNet.use_this_for_batch_size_computation_2D * Generic_UNet.DEFAULT_BATCH_SIZE_2D / 2 # for batch size 2 here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, 30, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: axis_to_be_reduced = np.argsort(new_shp / new_median_shape[1:])[-1] tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props(current_spacing[1:], tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing[1:], new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) # print(new_shp) batch_size = int(np.floor(ref / here) * 2) input_patch_size = new_shp if batch_size < self.unet_min_batch_size: raise RuntimeError("This should not happen") # check if batch size is too large (more than 5 % of dataset) max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) batch_size = max(1, min(batch_size, max_batch_size)) plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, 'do_dummy_2D_data_aug': False } return plan
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases # the next line is what we had before as a default. The patch size had the same aspect ratio as the median shape of a patient. We swapped t # input_patch_size = new_median_shape # compute how many voxels are one mm input_patch_size = 1 / np.array(current_spacing) # normalize voxels per mm input_patch_size /= input_patch_size.mean() # create an isotropic patch of size 512x512x512mm input_patch_size *= 1 / min( input_patch_size) * 512 # to get a starting value input_patch_size = np.round(input_patch_size).astype(int) # clip it to the median shape of the dataset because patches larger then that make not much sense input_patch_size = [ min(i, j) for i, j in zip(input_patch_size, new_median_shape) ] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) ref = Generic_UNet.use_this_for_batch_size_computation_3D here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: # here is the difference to ExperimentPlanner. In the old version we made the aspect ratio match # between patch and new_median_shape, regardless of spacing. It could be better to enforce isotropy # (in mm) instead current_patch_in_mm = new_shp * current_spacing axis_to_be_reduced = np.argsort(current_patch_in_mm)[-1] # from here on it's the same as before tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props_poolLateV2(tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, current_spacing) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) print(new_shp) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what works with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, self.unet_min_batch_size) batch_size = min(batch_size, max_batch_size) do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[0] ) > self.anisotropy_threshold plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ We need to adapt ref """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases # the next line is what we had before as a default. The patch size had the same aspect ratio as the median shape of a patient. We swapped t # input_patch_size = new_median_shape # compute how many voxels are one mm input_patch_size = 1 / np.array(current_spacing) # normalize voxels per mm input_patch_size /= input_patch_size.mean() # create an isotropic patch of size 512x512x512mm input_patch_size *= 1 / min( input_patch_size) * 512 # to get a starting value input_patch_size = np.round(input_patch_size).astype(int) # clip it to the median shape of the dataset because patches larger then that make not much sense input_patch_size = [ min(i, j) for i, j in zip(input_patch_size, new_median_shape) ] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing, input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool) # use_this_for_batch_size_computation_3D = 520000000 # 505789440 # typical ExperimentPlanner3D_v21 configurations use 7.5GB, but on a V100 we have 32. Allow for more space # to be used ref = Generic_UNet.use_this_for_batch_size_computation_3D * 32 / 8 here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: axis_to_be_reduced = np.argsort(new_shp / new_median_shape)[-1] tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props(current_spacing, tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, ) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing, new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, ) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) # print(new_shp) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what wirks with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, self.unet_min_batch_size) batch_size = max(1, min(batch_size, max_batch_size)) do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[0] ) > self.anisotropy_threshold plan = { 'batch_size': batch_size, 'num_pool_per_axis': network_num_pool_per_axis, 'patch_size': input_patch_size, 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan
class nnUNetTrainerV2(nnUNetTrainer): """ Info for Fabian: same as internal nnUNetTrainerV2_2 """ def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) self.max_num_epochs = 1000 self.initial_lr = 1e-2 self.deep_supervision_scales = None self.ds_loss_weights = None self.pin_memory = True def initialize(self, training=True, force_load_plans=False): """ - replaced get_default_augmentation with get_moreDA_augmentation - enforce to only run this code once - loss function wrapper for deep supervision :param training: :param force_load_plans: :return: """ if not self.was_initialized: maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() ################# Here we wrap the loss for deep supervision ############ # we need to know the number of outputs of the network net_numpool = len(self.net_num_pool_op_kernel_sizes) # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases # this gives higher resolution outputs more weight in the loss weights = np.array([1 / (2**i) for i in range(net_numpool)]) # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1 mask = np.array([True] + [ True if i < net_numpool - 1 else False for i in range(1, net_numpool) ]) weights[~mask] = 0 weights = weights / weights.sum() self.ds_loss_weights = weights # now wrap the loss self.loss = MultipleOutputLoss2(self.loss, self.ds_loss_weights) ################# END ################### self.folder_with_preprocessed_data = join( self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: print("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) print("done") else: print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") self.tr_gen, self.val_gen = get_moreDA_augmentation( self.dl_tr, self.dl_val, self.data_aug_params['patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, pin_memory=self.pin_memory) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) else: self.print_to_log_file( 'self.was_initialized is True, not running self.initialize again' ) self.was_initialized = True def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} self.network = Generic_UNet( self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, True, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True) if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper def initialize_optimizer_and_scheduler(self): assert self.network is not None, "self.initialize_network must be called first" self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, momentum=0.99, nesterov=True) self.lr_scheduler = None def run_online_evaluation(self, output, target): """ due to deep supervision the return value and the reference are now lists of tensors. We only need the full resolution output because this is what we are interested in in the end. The others are ignored :param output: :param target: :return: """ target = target[0] output = output[0] return super().run_online_evaluation(output, target) def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, segmentation_export_kwargs: dict = None): """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().validate(do_mirroring, use_sliding_window, step_size, save_softmax, use_gaussian, overwrite, validation_folder_name, debug, all_in_gpu, segmentation_export_kwargs) self.network.do_ds = ds return ret def predict_preprocessed_data_return_seg_and_softmax( self, data: np.ndarray, do_mirroring: bool = True, mirror_axes: Tuple[int] = None, use_sliding_window: bool = True, step_size: float = 0.5, use_gaussian: bool = True, pad_border_mode: str = 'constant', pad_kwargs: dict = None, all_in_gpu: bool = True, verbose: bool = True) -> Tuple[np.ndarray, np.ndarray]: """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().predict_preprocessed_data_return_seg_and_softmax( data, do_mirroring, mirror_axes, use_sliding_window, step_size, use_gaussian, pad_border_mode, pad_kwargs, all_in_gpu, verbose) self.network.do_ds = ds return ret def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False): """ gradient clipping improves training stability :param data_generator: :param do_backprop: :param run_online_evaluation: :return: """ data_dict = next(data_generator) data = data_dict['data'] target = data_dict['target'] data = maybe_to_torch(data) target = maybe_to_torch(target) if torch.cuda.is_available(): data = to_cuda(data) target = to_cuda(target) self.optimizer.zero_grad() output = self.network(data) del data loss = self.loss(output, target) if run_online_evaluation: self.run_online_evaluation(output, target) del target if do_backprop: if not self.fp16 or amp is None or not torch.cuda.is_available(): loss.backward() else: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() _ = clip_grad_norm_(self.network.parameters(), 12) self.optimizer.step() return loss.detach().cpu().numpy() def do_split(self): """ we now allow more than 5 splits. IMPORTANT: and fold > 4 will not be a real split but just another random 80:20 split of the data. You cannot run X-fold cross-validation with this code. It will always be a 5-fold CV. Folds > 4 will be independent from each other :return: """ if self.fold == "all": # if fold==all then we use all images for training and validation tr_keys = val_keys = list(self.dataset.keys()) else: splits_file = join(self.dataset_directory, "splits_final.pkl") # if the split file does not exist we need to create it if not isfile(splits_file): self.print_to_log_file("Creating new split...") splits = [] all_keys_sorted = np.sort(list(self.dataset.keys())) kfold = KFold(n_splits=5, shuffle=True, random_state=12345) for i, (train_idx, test_idx) in enumerate(kfold.split(all_keys_sorted)): train_keys = np.array(all_keys_sorted)[train_idx] test_keys = np.array(all_keys_sorted)[test_idx] splits.append(OrderedDict()) splits[-1]['train'] = train_keys splits[-1]['val'] = test_keys save_pickle(splits, splits_file) splits = load_pickle(splits_file) if self.fold < len(splits): tr_keys = splits[self.fold]['train'] val_keys = splits[self.fold]['val'] else: self.print_to_log_file( "INFO: Requested fold %d but split file only has %d folds. I am now creating a " "random 80:20 split!" % (self.fold, len(splits))) # if we request a fold that is not in the split file, create a random 80:20 split rnd = np.random.RandomState(seed=12345 + self.fold) keys = np.sort(list(self.dataset.keys())) idx_tr = rnd.choice(len(keys), int(len(keys) * 0.8), replace=False) idx_val = [i for i in range(len(keys)) if i not in idx_tr] tr_keys = [keys[i] for i in idx_tr] val_keys = [keys[i] for i in idx_val] tr_keys.sort() val_keys.sort() self.dataset_tr = OrderedDict() for i in tr_keys: self.dataset_tr[i] = self.dataset[i] self.dataset_val = OrderedDict() for i in val_keys: self.dataset_val[i] = self.dataset[i] def setup_DA_params(self): """ - we increase roation angle from [-15, 15] to [-30, 30] - scale range is now (0.7, 1.4), was (0.85, 1.25) - we don't do elastic deformation anymore :return: """ self.deep_supervision_scales = [[1, 1, 1]] + list( list(i) for i in 1 / np.cumprod( np.vstack(self.net_num_pool_op_kernel_sizes), axis=0))[:-1] if self.threeD: self.data_aug_params = default_3D_augmentation_params self.data_aug_params['rotation_x'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_y'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) self.data_aug_params['rotation_z'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi) if self.do_dummy_2D_aug: self.data_aug_params["dummy_2D"] = True self.print_to_log_file("Using dummy2d data augmentation") self.data_aug_params["elastic_deform_alpha"] = \ default_2D_augmentation_params["elastic_deform_alpha"] self.data_aug_params["elastic_deform_sigma"] = \ default_2D_augmentation_params["elastic_deform_sigma"] self.data_aug_params[ "rotation_x"] = default_2D_augmentation_params[ "rotation_x"] else: self.do_dummy_2D_aug = False if max(self.patch_size) / min(self.patch_size) > 1.5: default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi) self.data_aug_params = default_2D_augmentation_params self.data_aug_params[ "mask_was_used_for_normalization"] = self.use_mask_for_norm if self.do_dummy_2D_aug: self.basic_generator_patch_size = get_patch_size( self.patch_size[1:], self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) self.basic_generator_patch_size = np.array( [self.patch_size[0]] + list(self.basic_generator_patch_size)) patch_size_for_spatialtransform = self.patch_size[1:] else: self.basic_generator_patch_size = get_patch_size( self.patch_size, self.data_aug_params['rotation_x'], self.data_aug_params['rotation_y'], self.data_aug_params['rotation_z'], self.data_aug_params['scale_range']) patch_size_for_spatialtransform = self.patch_size self.data_aug_params["scale_range"] = (0.7, 1.4) self.data_aug_params["do_elastic"] = False self.data_aug_params['selected_seg_channels'] = [0] self.data_aug_params[ 'patch_size_for_spatialtransform'] = patch_size_for_spatialtransform self.data_aug_params["num_cached_per_thread"] = 2 def maybe_update_lr(self, epoch=None): """ if epoch is not None we overwrite epoch. Else we use epoch = self.epoch + 1 (maybe_update_lr is called in on_epoch_end which is called before epoch is incremented. herefore we need to do +1 here) :param epoch: :return: """ if epoch is None: ep = self.epoch + 1 else: ep = epoch self.optimizer.param_groups[0]['lr'] = poly_lr(ep, self.max_num_epochs, self.initial_lr, 0.9) self.print_to_log_file( "lr:", np.round(self.optimizer.param_groups[0]['lr'], decimals=6)) def on_epoch_end(self): """ overwrite patient-based early stopping. Always run to 1000 epochs :return: """ super().on_epoch_end() continue_training = self.epoch < self.max_num_epochs # it can rarely happen that the momentum of nnUNetTrainerV2 is too high for some dataset. If at epoch 100 the # estimated validation Dice is still 0 then we reduce the momentum from 0.99 to 0.95 if self.epoch == 100: if self.all_val_eval_metrics[-1] == 0: self.optimizer.param_groups[0]["momentum"] = 0.95 self.network.apply(InitWeights_He(1e-2)) self.print_to_log_file( "At epoch 100, the mean foreground Dice was 0. This can be caused by a too " "high momentum. High momentum (0.99) is good for datasets where it works, but " "sometimes causes issues such as this one. Momentum has now been reduced to " "0.95 and network weights have been reinitialized") return continue_training def run_training(self): """ if we run with -c then we need to set the correct lr for the first epoch, otherwise it will run the first continued epoch with self.initial_lr we also need to make sure deep supervision in the network is enabled for training, thus the wrapper :return: """ self.maybe_update_lr( self.epoch ) # if we dont overwrite epoch then self.epoch+1 is used which is not what we # want at the start of the training ds = self.network.do_ds self.network.do_ds = True ret = super().run_training() self.network.do_ds = ds return ret
def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, num_modalities, num_classes): """ ExperimentPlanner configures pooling so that we pool late. Meaning that if the number of pooling per axis is (2, 3, 3), then the first pooling operation will always pool axes 1 and 2 and not 0, irrespective of spacing. This can cause a larger memory footprint, so it can be beneficial to revise this. Here we are pooling based on the spacing of the data. """ new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) dataset_num_voxels = np.prod(new_median_shape) * num_cases # the next line is what we had before as a default. The patch size had the same aspect ratio as the median shape of a patient. We swapped t # input_patch_size = new_median_shape # compute how many voxels are one mm input_patch_size = 1 / np.array(current_spacing) # normalize voxels per mm input_patch_size /= input_patch_size.mean() # create an isotropic patch of size 512x512x512mm input_patch_size *= 1 / min( input_patch_size) * 512 # to get a starting value input_patch_size = np.round(input_patch_size).astype(int) # clip it to the median shape of the dataset because patches larger then that make not much sense input_patch_size = [ min(i, j) for i, j in zip(input_patch_size, new_median_shape) ] network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing, input_patch_size, self.unet_featuremap_min_edge_length, self.unet_max_numpool) # we compute as if we were using only 30 feature maps. We can do that because fp16 training is the standard # now. That frees up some space. The decision to go with 32 is solely due to the speedup we get (non-multiples # of 8 are not supported in nvidia amp) ref = ResAxialAttentionUNet.use_this_for_batch_size_computation_3D * self.unet_base_num_features / \ ResAxialAttentionUNet.BASE_NUM_FEATURES_3D here = ResAxialAttentionUNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) while here > ref: axis_to_be_reduced = np.argsort(new_shp / new_median_shape)[-1] tmp = deepcopy(new_shp) tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[ axis_to_be_reduced] _, _, _, _, shape_must_be_divisible_by_new = \ get_pool_and_conv_props(current_spacing, tmp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, ) new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[ axis_to_be_reduced] # we have to recompute numpool now: network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing, new_shp, self.unet_featuremap_min_edge_length, self.unet_max_numpool, ) here = Generic_UNet.compute_approx_vram_consumption( new_shp, network_num_pool_per_axis, self.unet_base_num_features, self.unet_max_num_filters, num_modalities, num_classes, pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) #print(new_shp) #print(here, ref) input_patch_size = new_shp batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what wirks with 128**3 batch_size = int(np.floor(max(ref / here, 1) * batch_size)) # check if batch size is too large max_batch_size = np.round( self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / np.prod(input_patch_size, dtype=np.int64)).astype(int) max_batch_size = max(max_batch_size, self.unet_min_batch_size) batch_size = min(batch_size, max_batch_size) do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[0] ) > self.anisotropy_threshold plan = { #liuyiyao #'batch_size': batch_size, 'batch_size': 4, 'num_pool_per_axis': network_num_pool_per_axis, #'patch_size': input_patch_size, #liuyiyao 'patch_size': (8, 128, 128), 'median_patient_size_in_voxels': new_median_shape, 'current_spacing': current_spacing, 'original_spacing': original_spacing, 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 'pool_op_kernel_sizes': pool_op_kernel_sizes, 'conv_kernel_sizes': conv_kernel_sizes, } return plan