-
Notifications
You must be signed in to change notification settings - Fork 1
/
acs_train.py
184 lines (148 loc) · 7.71 KB
/
acs_train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# ------------------------------------------------------------------------------
# Code to train ACS in continual fashion
# ------------------------------------------------------------------------------
import os
import sys
from args import parse_args_as_dict
import torch
torch.set_num_threads(6)
from torch.utils.data import DataLoader
import torch.optim as optim
from mp.utils.helper_functions import seed_all
from mp.experiments.experiment import Experiment
from mp.data.data import Data
from mp.data.datasets.ds_mr_hippocampus_decathlon import DecathlonHippocampus
from mp.data.datasets.ds_mr_hippocampus_dryad import DryadHippocampus
from mp.data.datasets.ds_mr_hippocampus_harp import HarP
from mp.data.pytorch.pytorch_seg_dataset import PytorchSeg2DDatasetDomain
from mp.eval.losses.losses_segmentation import LossClassWeighted, LossDiceBCE
from mp.eval.result import Result
from mp.models.continual.acs import ACS
from mp.agents.acs_agent import ACSAgent
from mp.utils.tensorboard import create_writer
# Get configuration from arguments
config = parse_args_as_dict(sys.argv[1:])
seed_all(42)
config['class_weights'] = (0., 1.)
print('config', config)
# Create experiment directories
exp = Experiment(config=config, name=config['experiment_name'], notes='', reload_exp=(config['resume_epoch'] is not None))
# Datasets
data = Data()
dataset_domain_a = DecathlonHippocampus(merge_labels=True)
dataset_domain_a.name = 'DecathlonHippocampus'
data.add_dataset(dataset_domain_a)
dataset_domain_b = DryadHippocampus(merge_labels=True)
dataset_domain_b.name = 'DryadHippocampus'
data.add_dataset(dataset_domain_b)
dataset_domain_c = HarP(merge_labels=True)
dataset_domain_c.name = 'HarP'
data.add_dataset(dataset_domain_c)
nr_labels = data.nr_labels
label_names = data.label_names
if config['combination'] == 0:
ds_a = ('DecathlonHippocampus', 'train')
ds_b = ('DryadHippocampus', 'train')
ds_c = ('HarP', 'train')
elif config['combination'] == 1:
ds_a = ('DecathlonHippocampus', 'train')
ds_c = ('DryadHippocampus', 'train')
ds_b = ('HarP', 'train')
elif config['combination'] == 2:
ds_c = ('DecathlonHippocampus', 'train')
ds_b = ('DryadHippocampus', 'train')
ds_a = ('HarP', 'train')
# Create data splits for each repetition
exp.set_data_splits(data)
# Now repeat for each repetition
for run_ix in range(config['nr_runs']):
exp_run = exp.get_run(run_ix=0, reload_exp_run=(config['resume_epoch'] is not None))
# Bring data to Pytorch format and add domain_code
datasets = dict()
for idx, item in enumerate(data.datasets.items()):
ds_name, ds = item
for split, data_ixs in exp.splits[ds_name][exp_run.run_ix].items():
data_ixs = data_ixs[:config['n_samples']]
if len(data_ixs) > 0:
aug = config['augmentation'] if not('test' in split) else 'none'
datasets[(ds_name, split)] = PytorchSeg2DDatasetDomain(ds,
ix_lst=data_ixs, size=config['input_shape'] , aug_key=aug,
resize=(not config['no_resize']), domain_code=idx, domain_code_size=config['domain_code_size'])
dataset = torch.utils.data.ConcatDataset((datasets[(ds_a)], datasets[(ds_b)]))
train_dataloader_0 = DataLoader(dataset, batch_size=config['batch_size'], drop_last=False, pin_memory=True, num_workers=len(config['device_ids'])*config['n_workers'])
train_dataloader_1 = DataLoader(datasets[(ds_c)], batch_size=config['batch_size'], shuffle=True, drop_last=False, pin_memory=True, num_workers=len(config['device_ids'])*config['n_workers'])
if config['eval']:
drop = []
for key in datasets.keys():
if 'train' in key or 'val' in key:
drop += [key]
for d in drop:
datasets.pop(d)
model = ACS(input_shape=config['input_shape'], nr_labels=nr_labels, domain_code_size=config['domain_code_size'], latent_scaler_sample_size=250,
unet_dropout=config['unet_dropout'], unet_monte_carlo_dropout=config['unet_monte_carlo_dropout'], unet_preactivation=config['unet_preactivation'])
model.to(config['device'])
# Define loss and optimizer
loss_g = LossDiceBCE(bce_weight=1., smooth=1., device=config['device'])
loss_f = LossClassWeighted(loss=loss_g, weights=config['class_weights'], device=config['device'])
# Set optimizers
model.set_optimizers(optim.Adam, lr=config['lr'])
# Setup model
results = Result(name='training_trajectory')
agent = ACSAgent(model=model, label_names=label_names, device=config['device'])
agent.summary_writer = create_writer(os.path.join(exp_run.paths['states'], '..'), 0)
init_epoch = 0
nr_epochs = config['epochs'] // 2
# Resume training
if config['resume_epoch'] is not None:
agent.restore_state(exp_run.paths['states'], config['resume_epoch'])
init_epoch = agent.agent_state_dict['epoch'] + 1
# Training Stage 1
if init_epoch < config['epochs'] / 2:
config['continual'] = False
agent.train(results, loss_f, train_dataloader_0, train_dataloader_1, config,
init_epoch=init_epoch, nr_epochs=nr_epochs, run_loss_print_interval=1,
eval_datasets=datasets, eval_interval=config['eval_interval'],
save_path=exp_run.paths['states'], save_interval=config['save_interval'],
display_interval=config['display_interval'],
resume_epoch=config['resume_epoch'], device_ids=config['device_ids'])
print('Finished training on A and B, starting training on C')
init_epoch = config['epochs'] // 2
nr_epochs = config['epochs']
# Resume training
if config['resume_epoch'] is not None:
agent.restore_state(exp_run.paths['states'], config['resume_epoch'])
init_epoch = agent.agent_state_dict['epoch'] + 1
if init_epoch >= config['epochs'] / 2:
# Freeze model for fine-tuning
config['continual'] = True
for param in model.parameters():
param.requires_grad = False
# Unfreeze last two U-Net blocks
if len(config['device_ids']) > 1:
for param in model.unet.decoder.module.decoding_blocks[-2].parameters():
param.requires_grad = True
for param in model.unet.decoder.module.decoding_blocks[-1].parameters():
param.requires_grad = True
for param in model.unet.classifier.parameters():
param.requires_grad = True
else:
for param in model.unet.decoder.decoding_blocks[-2].parameters():
param.requires_grad = True
for param in model.unet.decoder.decoding_blocks[-1].parameters():
param.requires_grad = True
for param in model.unet.classifier.parameters():
param.requires_grad = True
# Set optimizers
model.set_optimizers(optim.Adam, lr=config['lr_2'])
config['continual'] = True
model.unet_scheduler = torch.optim.lr_scheduler.StepLR(model.unet_optim, (nr_epochs-init_epoch), gamma=0.1, last_epoch=-1)
# Training Stage 2
agent.train(results, loss_f, train_dataloader_1, train_dataloader_0, config,
init_epoch=init_epoch, nr_epochs=nr_epochs, run_loss_print_interval=1,
eval_datasets=datasets, eval_interval=config['eval_interval'],
save_path=exp_run.paths['states'], save_interval=config['save_interval'],
display_interval=config['display_interval'],
resume_epoch=config['resume_epoch'], device_ids=[0])
print('Finished training on C')
# Save and print results for this experiment run
exp_run.finish(results=results, plot_metrics=['Mean_LossBCEWithLogits', 'Mean_LossDice[smooth=1.0]', 'Mean_LossCombined[1.0xLossDice[smooth=1.0]+1.0xLossBCEWithLogits]'])