run.py 21.5 KB
Newer Older
1
2
3
4
"""Brain Mapper Run File

Description:

5
6
7
8
9
    This file contains all the relevant functions for running BrainMapper.
    The network can be ran in one of these modes:
        - train
        - evaluate path
        - evaluate whole
10

11
    TODO: Might be worth adding some information on uncertaintiy estimation, later down the line
12

13
14
15
16
17
18
19
20
21
22
23
24
25
Usage:

    In order to run the network, in the terminal, the user needs to pass it relevant arguments:

        $ ./setup.sh
        $ source env/bin/activate
        $ python run.py --mode ...

    The arguments for mode are the following:

        mode=train # For training the model
        mode=evaluate-score # For evaluating the model score
        mode=evaluate-mapping # For evaluating the model mapping
26
27
        # For clearning the experiments and logs directories of the last experiment
        mode=clear-experiment
28
        mode=clear-all # For clearing all the files from the experiments and logs directories/
29
30
31

"""

32
import os
33
import shutil
34
35
import argparse
import logging
36
37
38

import torch
import torch.utils.data as data
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
39
import numpy as np
40
41

from solver import Solver
42
from BrainMapperAE import BrainMapperAE3D, AutoEncoder3D
43
44
from utils.data_utils import get_datasets
from utils.settings import Settings
45
import utils.data_evaluation_utils as evaluations
46
from utils.common_utils import create_folder
47
48
49
50
51

# Set the default floating point tensor type to FloatTensor

torch.set_default_tensor_type(torch.FloatTensor)

52

53
def load_data(data_parameters, cross_domain_x2x_flag, cross_domain_y2y_flag):
54
55
    """Dataset Loader

56
    This function loads the training and validation datasets.
57
58
59

    Args:
        data_parameters (dict): Dictionary containing relevant information for the datafiles.
60
61
        cross_domain_x2x_flag (bool): Flag indicating if cross-domain training is occuring between the inputs
        cross_domain_y2y_flag (bool): Flag indicating if cross-domain training is occuring between the targets
62
63
64

    Returns:
        train_data (dataset object): Pytorch map-style dataset object, mapping indices to training data samples.
65
        validation_data (dataset object): Pytorch map-style dataset object, mapping indices to testing data samples.
66
67
68

    """
    print("Data is loading...")
69
    train_data, validation_data = get_datasets(data_parameters, cross_domain_x2x_flag, cross_domain_y2y_flag)
70
71
    print("Data has loaded!")
    print("Training dataset size is {}".format(len(train_data)))
72
    print("Validation dataset size is {}".format(len(validation_data)))
73

74
    return train_data, validation_data
75

76

77
78
def train(data_parameters, training_parameters, network_parameters, misc_parameters):
    """Training Function
79

80
    This function trains a given model using the provided training data.
81
    Currently, the data loaded is set to have multiple sub-processes.
82
83
    A high enough number of workers assures that CPU computations are efficiently managed, i.e. that the bottleneck is indeed the neural network's forward and backward operations on the GPU (and not data generation)
    Loader memory is also pinned, to speed up data transfer from CPU to GPU  by using the page-locked memory.
84
    Train data is also re-shuffled at each training epoch.
85
86

    Args:
87
88
89
90
91
        data_parameters (dict): Dictionary containing relevant information for the datafiles.

        training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
        training_parameters = {
            'training_batch_size': 5
92
            'validation_batch_size: 5
93
94
95
96
97
98
99
100
101
102
103
104
105
            'use_pre_trained': False
            'pre_trained_path': 'pre_trained/path'
            'experiment_name': 'experiment_name'
            'learning_rate': 1e-4
            'optimizer_beta': (0.9, 0.999)
            'optimizer_epsilon': 1e-8
            'optimizer_weigth_decay': 1e-5
            'number_of_epochs': 10
            'loss_log_period': 50
            'learning_rate_scheduler_step_size': 3
            'learning_rate_scheduler_gamma': 1e-1
            'use_last_checkpoint': True
            'final_model_output_file': 'path/to/model'
106
        }
107

108
        network_parameters (dict): Contains information relevant parameters
109

110
111
112
113
114
115
116
117
        misc_parameters (dict): Dictionary of aditional hyperparameters
        misc_parameters = {
            'save_model_directory': 'directory_name'
            'model_name': 'BrainMapper'
            'logs_directory': 'log-directory'
            'device': 1
            'experiments_directory': 'experiments-directory'
        }
118
119
    """

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

    def _load_pretrained_cross_domain(x2y_model, save_model_directory, experiment_name):
        """ Pretrained cross-domain loader

        This function loads the pretrained X2X and Y2Y autuencoders.
        After, it initializes the X2Y model's weights using the X2X encoder and teh Y2Y decoder weights.

        Args:
            x2y_model (class): Original x2y model initialised using the standard parameters.
            save_model_directory (str): Name of the directory where the model is saved
            experiment_name (str): Name of the experiment

        Returns:
            x2y_model (class): New x2y model with encoder and decoder paths weights reinitialised.
        """

        x2y_model_state_dict = x2y_model.state_dict()
        x2x_model_state_dict = torch.load(os.path.join(save_model_directory, experiment_name + '_x2x.pth.tar')).state_dict()
        y2y_model_state_dict = torch.load(os.path.join(save_model_directory, experiment_name + '_y2y.pth.tar')).state_dict()

        half_point = len(x2x_model_state_dict)//2 + 1

        counter = 1
        for key, _ in x2y_model_state_dict.items():
            if counter <= half_point:
                x2y_model_state_dict.update({key : x2x_model_state_dict[key]})
                counter+=1
            else:
                if key in y2y_model_state_dict:
                    x2y_model_state_dict.update({key : y2y_model_state_dict[key]})

        x2y_model.load_state_dict(x2y_model_state_dict)

        return x2y_model


    def _train_runner(data_parameters, 
                      training_parameters, 
                      network_parameters, 
                      misc_parameters,
                      optimizer = torch.optim.Adam,
                      loss_function = torch.nn.MSELoss(),
                      ):
163
164
165
166
167
168
169
170
171
172
173
        """Wrapper for the training operation

        This function wraps the training operation for the network

        Args:
            data_parameters (dict): Dictionary containing relevant information for the datafiles.
            training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
            network_parameters (dict): Contains information relevant parameters
            misc_parameters (dict): Dictionary of aditional hyperparameters

        """
174
175
176
177
178

        train_data, validation_data = load_data(data_parameters,
                                                cross_domain_x2x_flag = network_parameters['cross_domain_x2x_flag'], 
                                                cross_domain_y2y_flag = network_parameters['cross_domain_y2y_flag']
                                                )
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

        train_loader = data.DataLoader(
            dataset=train_data,
            batch_size=training_parameters['training_batch_size'],
            shuffle=True,
            pin_memory=True
        )

        validation_loader = data.DataLoader(
            dataset=validation_data,
            batch_size=training_parameters['validation_batch_size'],
            shuffle=False,
            pin_memory=True
        )

        if training_parameters['use_pre_trained']:
195
            BrainMapperModel = torch.load(training_parameters['pre_trained_path'])
Andrei Roibu's avatar
Andrei Roibu committed
196
        else:
197
198
            # BrainMapperModel = BrainMapperAE3D(network_parameters)
            BrainMapperModel = AutoEncoder3D(network_parameters) # temprorary change for testing encoder-decoder effective receptive field
199

200
201
202
        custom_weight_reset_flag = network_parameters['custom_weight_reset_flag']

        BrainMapperModel.reset_parameters(custom_weight_reset_flag)
203

204
205
206
207
208
        if network_parameters['cross_domain_x2y_flag'] == True:
            BrainMapperModel = _load_pretrained_cross_domain(x2y_model=BrainMapperModel, 
                                                             save_model_directory=misc_parameters['save_model_directory'], 
                                                             experiment_name=training_parameters['experiment_name']
                                                             )
209

210
211
212
213
        solver = Solver(model=BrainMapperModel,
                        device=misc_parameters['device'],
                        number_of_classes=network_parameters['number_of_classes'],
                        experiment_name=training_parameters['experiment_name'],
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
214
                        optimizer=optimizer,
215
                        optimizer_arguments={'lr': training_parameters['learning_rate'],
216
217
218
219
                                             'betas': training_parameters['optimizer_beta'],
                                             'eps': training_parameters['optimizer_epsilon'],
                                             'weight_decay': training_parameters['optimizer_weigth_decay']
                                             },
220
                        loss_function=loss_function,
221
                        model_name=training_parameters['experiment_name'],
222
223
224
225
226
227
228
229
                        number_epochs=training_parameters['number_of_epochs'],
                        loss_log_period=training_parameters['loss_log_period'],
                        learning_rate_scheduler_step_size=training_parameters[
                            'learning_rate_scheduler_step_size'],
                        learning_rate_scheduler_gamma=training_parameters['learning_rate_scheduler_gamma'],
                        use_last_checkpoint=training_parameters['use_last_checkpoint'],
                        experiment_directory=misc_parameters['experiments_directory'],
                        logs_directory=misc_parameters['logs_directory'],
230
231
                        checkpoint_directory=misc_parameters['checkpoint_directory'],
                        save_model_directory=misc_parameters['save_model_directory'],
232
                        crop_flag = data_parameters['crop_flag']
233
234
                        )

235
236
237
        # _ = solver.train(train_loader, validation_loader)

        solver.train(train_loader, validation_loader)
238

239
        del train_data, validation_data, train_loader, validation_loader, BrainMapperModel, solver, optimizer
240
241
        torch.cuda.empty_cache()

242
        # return None
243
244


245
246
247
248
    if training_parameters['adam_w_flag'] == True:
        optimizer = torch.optim.AdamW
    else:
        optimizer = torch.optim.Adam
249
250
251
252
253
254

    loss_function = torch.nn.MSELoss()
    # loss_function=torch.nn.L1Loss()
    # loss_function=torch.nn.CosineEmbeddingLoss()

    if network_parameters['cross_domain_flag'] == False:
255
256
257
258
259
260
261
        _train_runner(data_parameters, 
                    training_parameters, 
                    network_parameters, 
                    misc_parameters,
                    optimizer=optimizer,
                    loss_function=loss_function
                    )
262
263
264
265
    
    elif network_parameters['cross_domain_flag'] == True:
        if network_parameters['cross_domain_x2x_flag'] == True:

Andrei Roibu's avatar
Andrei Roibu committed
266
            training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_x2x"
267
268
269
            data_parameters['target_data_train'] = data_parameters['input_data_train']
            data_parameters['target_data_validation'] = data_parameters['input_data_validation']

270
            # loss_function = torch.nn.L1Loss()
271

272
273
274
275
276
277
278
            _train_runner(data_parameters, 
                        training_parameters, 
                        network_parameters, 
                        misc_parameters,
                        optimizer=optimizer,
                        loss_function=loss_function
                        )
279
280
281

        if network_parameters['cross_domain_y2y_flag'] == True:

Andrei Roibu's avatar
Andrei Roibu committed
282
            training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_y2y"
283
284
285
            data_parameters['input_data_train'] = data_parameters['target_data_train']
            data_parameters['input_data_validation'] = data_parameters['target_data_validation']

286
            # loss_function = torch.nn.L1Loss()
287

288
289
290
291
292
293
294
            _train_runner(data_parameters, 
                        training_parameters, 
                        network_parameters, 
                        misc_parameters,
                        optimizer=optimizer,
                        loss_function=loss_function
                        )
295
296
297

        if network_parameters['cross_domain_x2y_flag'] == True:

298
299
300
301
302
303
304
            _train_runner(data_parameters, 
                        training_parameters, 
                        network_parameters, 
                        misc_parameters,
                        optimizer=optimizer,
                        loss_function=loss_function
                        )
305

Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
306

307
308
def evaluate_mapping(mapping_evaluation_parameters):
    """Mapping Evaluator
309

310
311
312
313
314
    This function passes through the network an input and generates the rsfMRI outputs.

    Args:
        mapping_evaluation_parameters (dict): Dictionary of parameters useful during mapping evaluation.
        mapping_evaluation_parameters = {
315
            'trained_model_path': 'path/to/model'
316
317
318
319
320
321
322
323
324
            'data_directory': 'path/to/data'
            'data_list': 'path/to/datalist.txt/
            'prediction_output_path': 'directory-of-saved-predictions'
            'batch_size': 2
            'device': 0
            'exit_on_error': True
        }

    """
325
    trained_model_path = mapping_evaluation_parameters['trained_model_path']
326
    data_directory = mapping_evaluation_parameters['data_directory']
327
    mapping_data_file = mapping_evaluation_parameters['mapping_data_file']
328
329
    data_list = mapping_evaluation_parameters['data_list']
    prediction_output_path = mapping_evaluation_parameters['prediction_output_path']
Andrei Roibu's avatar
Andrei Roibu committed
330
331
    dmri_mean_mask_path = mapping_evaluation_parameters['dmri_mean_mask_path']
    rsfmri_mean_mask_path = mapping_evaluation_parameters['rsfmri_mean_mask_path']
332
    device = mapping_evaluation_parameters['device']
333
    exit_on_error = mapping_evaluation_parameters['exit_on_error']
334
    brain_mask_path = mapping_evaluation_parameters['brain_mask_path']
Andrei Roibu's avatar
Andrei Roibu committed
335
    regression_factors = mapping_evaluation_parameters['regression_factors']
336
337
338
339
340
    mean_regression_flag = mapping_evaluation_parameters['mean_regression_flag']
    mean_regression_all_flag = mapping_evaluation_parameters['mean_regression_all_flag']
    mean_subtraction_flag = mapping_evaluation_parameters['mean_subtraction_flag']
    scale_volumes_flag = mapping_evaluation_parameters['scale_volumes_flag']
    normalize_flag = mapping_evaluation_parameters['normalize_flag']
341
    minus_one_scaling_flag = mapping_evaluation_parameters['minus_one_scaling_flag']
342
343
344
345
346
    negative_flag = mapping_evaluation_parameters['negative_flag']
    outlier_flag = mapping_evaluation_parameters['outlier_flag']
    shrinkage_flag = mapping_evaluation_parameters['shrinkage_flag']
    hard_shrinkage_flag = mapping_evaluation_parameters['hard_shrinkage_flag']
    crop_flag = mapping_evaluation_parameters['crop_flag']
347

348
    evaluations.evaluate_mapping(trained_model_path,
Andrei Roibu's avatar
Andrei Roibu committed
349
350
351
352
353
354
355
356
                                 data_directory,
                                 mapping_data_file,
                                 data_list,
                                 prediction_output_path,
                                 brain_mask_path,
                                 dmri_mean_mask_path,
                                 rsfmri_mean_mask_path,
                                 regression_factors,
357
358
359
360
361
                                 mean_regression_flag,
                                 mean_regression_all_flag, 
                                 mean_subtraction_flag,
                                 scale_volumes_flag,
                                 normalize_flag,
362
                                 minus_one_scaling_flag,
363
364
365
366
367
368
369
                                 negative_flag, 
                                 outlier_flag,
                                 shrinkage_flag,
                                 hard_shrinkage_flag,
                                 crop_flag,
                                 device, 
                                 exit_on_error)
370

371

372
def delete_files(folder):
373
    """ Clear Folder Contents
374

375
376
377
378
    Function which clears contents (like experiments or logs)

    Args:
        folder (str): Name of folders whose conents is to be deleted
379

380
    """
381

382
383
384
385
386
387
388
389
390
391
    for object_name in os.listdir(folder):
        file_path = os.path.join(folder, object_name)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as exception:
            print(exception)

392
393

if __name__ == '__main__':
394
    parser = argparse.ArgumentParser()
395
396
    parser.add_argument('--mode', '-m', required=True,
                        help='run mode, valid values are train or evaluate')
397
398
    parser.add_argument('--model_name', '-n', required=True,
                        help='model name, required for identifying the settings file modelName.ini & modelName_eval.ini')
399
    parser.add_argument('--use_last_checkpoint', '-c', required=False,
400
                        help='flag indicating if the last checkpoint should be used if 1; useful when wanting to time-limit jobs.')
401
402
    parser.add_argument('--number_of_epochs', '-e', required=False,
                        help='flag indicating how many epochs the network will train for; should be limited to ~3 hours or 2/3 epochs')
403
404
405

    arguments = parser.parse_args()

406
407
408
409
    settings_file_name = arguments.model_name + '.ini'
    evaluation_settings_file_name = arguments.model_name + '_eval.ini'

    settings = Settings(settings_file_name)
410
411
412
413
414
415
    data_parameters = settings['DATA']
    training_parameters = settings['TRAINING']
    network_parameters = settings['NETWORK']
    misc_parameters = settings['MISC']
    evaluation_parameters = settings['EVALUATION']

416
    if arguments.use_last_checkpoint == '1':
417
        training_parameters['use_last_checkpoint'] = True
418
419
420
421
422
    elif arguments.use_last_checkpoint == '0':
        training_parameters['use_last_checkpoint'] = False

    if arguments.number_of_epochs is not None:
        training_parameters['number_of_epochs'] = int(arguments.number_of_epochs)
423

424
425
    if arguments.mode == 'train':
        train(data_parameters, training_parameters,
426
              network_parameters, misc_parameters)
427
428
429

    elif arguments.mode == 'evaluate-mapping':
        logging.basicConfig(filename='evaluate-mapping-error.log')
430
        settings_evaluation = Settings(evaluation_settings_file_name)
431
432
        mapping_evaluation_parameters = settings_evaluation['MAPPING']
        evaluate_mapping(mapping_evaluation_parameters)
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

    elif arguments.mode == 'clear-checkpoints':
        if network_parameters['cross_domain_flag'] == True:
            if network_parameters['cross_domain_x2x_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_x2x"
            if network_parameters['cross_domain_y2y_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_y2y"

        shutil.rmtree(os.path.join(misc_parameters['experiments_directory'], training_parameters['experiment_name']))
        print('Cleared the current experiment checkpoints successfully!')

    elif arguments.mode == 'clear-logs':
        if network_parameters['cross_domain_flag'] == True:
            if network_parameters['cross_domain_x2x_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_x2x"
            if network_parameters['cross_domain_y2y_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_y2y"

        shutil.rmtree(os.path.join(misc_parameters['logs_directory'], training_parameters['experiment_name']))
        print('Cleared the current experiment logs directory successfully!')

    elif arguments.mode == 'clear-experiment':
        if network_parameters['cross_domain_flag'] == True:
            if network_parameters['cross_domain_x2x_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_x2x"
            if network_parameters['cross_domain_y2y_flag'] == True:
                training_parameters['experiment_name'] = training_parameters['experiment_name'] + "_y2y"

        shutil.rmtree(os.path.join(misc_parameters['experiments_directory'], training_parameters['experiment_name']))
        shutil.rmtree(os.path.join(misc_parameters['logs_directory'], training_parameters['experiment_name']))
        print('Cleared the current experiment checkpoints and logs directory successfully!')

    # elif arguments.mode == 'clear-everything':
    #     delete_files(misc_parameters['experiments_directory'])
    #     delete_files(misc_parameters['logs_directory'])
    #     print('Cleared the all the checkpoints and logs directory successfully!')

470
    elif arguments.mode == 'train-and-evaluate-mapping':
471
        settings_evaluation = Settings(evaluation_settings_file_name)
472
473
474
475
476
        mapping_evaluation_parameters = settings_evaluation['MAPPING']
        train(data_parameters, training_parameters,
              network_parameters, misc_parameters)
        logging.basicConfig(filename='evaluate-mapping-error.log')
        evaluate_mapping(mapping_evaluation_parameters)
477
        
478
479
    else:
        raise ValueError(
480
            'Invalid mode value! Only supports: train, evaluate-score, evaluate-mapping, train-and-evaluate-mapping, clear-checkpoints, clear-logs,  clear-experiment and clear-everything (req uncomment for safety!)')