-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpretrain1.py
296 lines (245 loc) · 10.4 KB
/
pretrain1.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
'''
used in scritps/pretrain2
scripts/pretrain3
'''
import copy
import os
from datetime import datetime
from batchgenerators.utilities.file_and_folder_operations import *
from dataset.acdc_graph import ACDC
from dataset.chd import CHD, chd_sg_collate
from experiment_log import PytorchExperimentLogger
from loss.contrast_loss import SupConLoss
from lr_scheduler import LR_Scheduler
from myconfig import get_config
# from network.unet2d import
from network.dynamic_graph_unet2d import GraphUNet2DClassification
from torch.autograd import Variable
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from utils import *
def get_kwargs_model(args):
model_kwargs = vars(copy.deepcopy(args))
model_kwargs.pop('initial_filter_size')
model_kwargs.pop('classes')
return model_kwargs
def main():
# initialize config
args = get_config()
if args.save == '':
args.save = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
save_path = os.path.join(
args.results_dir, args.experiment_name + args.save)
if not os.path.exists(save_path):
os.makedirs(save_path)
logger = PytorchExperimentLogger(save_path, "elog", ShowTerminal=True)
model_result_dir = join(save_path, 'model')
maybe_mkdir_p(model_result_dir)
args.model_result_dir = model_result_dir
logger.print(f"saving to {save_path}")
writer = SummaryWriter('runs/' + args.experiment_name + args.save)
# setup cuda
args.device = torch.device(
args.device if torch.cuda.is_available() else "cpu")
# logger.print(f"the model will run on device {args.device}")
# create model
logger.print("creating model ...")
model_kwargs = get_kwargs_model(args)
model = GraphUNet2DClassification(
in_channels=1, initial_filter_size=args.initial_filter_size, kernel_size=3, classes=args.classes, do_instancenorm=True, **model_kwargs
)
if args.restart:
logger.print('loading from saved model'+args.pretrained_model_path)
dict = torch.load(args.pretrained_model_path,
map_location=lambda storage, loc: storage)
model_dict = model.state_dict()
save_model = dict["net"]
model_dict.update(save_model)
model.load_state_dict(model_dict)
model.to(args.device)
model = torch.nn.DataParallel(model)
num_parameters = sum([l.nelement() for l in model.module.parameters()])
logger.print(f"number of parameters: {num_parameters}")
if args.dataset == 'chd':
training_keys = os.listdir(os.path.join(args.data_dir, 'train'))
training_keys.sort()
train_dataset = CHD(keys=training_keys, purpose='train', args=args)
elif args.dataset == 'acdc':
train_dataset = ACDC(keys=list(range(1, 101)),
purpose='train', args=args)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_works, drop_last=True, collate_fn=chd_sg_collate
)
# define loss function (criterion) and optimizer
criterion = SupConLoss(threshold=args.slice_threshold, temperature=args.temp,
contrastive_method=args.contrastive_method).to(args.device)
optimizer = torch.optim.SGD(
model.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-5
)
corr_lr = 0.001
corr_optimizer = torch.optim.SGD(
model.parameters(), lr=corr_lr, momentum=0.9, weight_decay=1e-5
)
scheduler = LR_Scheduler(
args.lr_scheduler, args.lr, args.epochs, len(train_loader)
)
corr_scheduler = LR_Scheduler(
args.lr_scheduler, corr_lr, args.epochs, len(train_loader)
)
for epoch in range(args.epochs):
# train for one epoch
train_loss = train(
train_loader, model, criterion,
epoch, optimizer, corr_optimizer, scheduler, corr_scheduler, logger, args
)
logger.print('\n Epoch: {0}\t'
'Training Loss {train_loss:.4f} \t'
.format(epoch + 1, train_loss=train_loss))
writer.add_scalar('training_loss', train_loss, epoch)
writer.add_scalar('lr', optimizer.param_groups[0]['lr'], epoch)
# save model
save_dict = {"net": model.module.state_dict()}
torch.save(save_dict, os.path.join(
args.model_result_dir, "latest.pth")
)
if epoch % 50 == 0:
torch.save(
save_dict,
os.path.join(args.model_result_dir, f"epoch_{epoch:03d}.pth")
)
def train(
data_loader, model, criterion, epoch, optimizer, corr_optimizer,
scheduler, corr_scheduler, logger, args, optimizer_time=1
):
model.train()
cnn_loss = AverageMeter()
graph_loss = AverageMeter()
corr_losses = AverageMeter()
local_graph_losses = AverageMeter()
losses = AverageMeter()
for batch_idx, tup in enumerate(data_loader):
scheduler(optimizer, batch_idx, epoch)
corr_scheduler(corr_optimizer, batch_idx, epoch)
tup = {
k: v.to(args.device)
if isinstance(v, torch.Tensor) else v
for k, v in tup.items()
}
# sometimes we drop too much data and we need to skip the batch
if tup['keypoints_1'].shape[0] / 4 < 2:
print('batch size too small')
continue
if optimizer_time == 1:
corr_loss, f1_1, f2_1, graph_1, graph_2, mask, local_graph_1, local_graph_2 = model(
input_dict=tup, weight_corr=args.weight_corr, weight_local=args.weight_local_contrast
)
bsz = f1_1.shape[0]
features = torch.cat([f1_1.unsqueeze(1), f2_1.unsqueeze(1)], dim=1)
graph_features = torch.cat(
[graph_1.unsqueeze(1), graph_2.unsqueeze(1)], dim=1
)
if args.contrastive_method == 'pcl':
if bsz != tup['slice_position'].shape[0]:
print('batch size not equal')
continue
cnn_contrast_loss = criterion(
features, labels=tup['slice_position']
)
graph_scontrast_loss = criterion(
graph_features, labels=tup['slice_position']
)
cnn_loss.update(cnn_contrast_loss.item(), bsz)
graph_loss.update(graph_scontrast_loss.item(), bsz)
contrast_loss = args.weight_cnn_contrast * cnn_contrast_loss + \
args.weight_graph_contrast * graph_scontrast_loss
elif args.contrastive_method == 'gcl':
contrast_loss = criterion(
features, labels=tup['slice_position']
)
else: # simclr
contrast_loss = criterion(features)
if torch.isnan(contrast_loss):
print('nan contrast loss')
continue
corr_loss = corr_loss.mean()
corr_losses.update(corr_loss.item(), bsz)
corr_loss = args.weight_corr * corr_loss
if torch.isnan(corr_loss):
print('nan corr loss')
continue
loss = corr_loss + contrast_loss
if args.weight_local_contrast > 0.:
sum_local_graph_loss = 0.
for mask_i, local_graph_1_i, local_graph_2_i in zip(mask, local_graph_1, local_graph_2):
local_graph_1_i = local_graph_1_i.permute(1, 0)
local_graph_2_i = local_graph_2_i.permute(1, 0)
local_graph_features = torch.cat(
[local_graph_1_i.unsqueeze(1), local_graph_2_i.unsqueeze(1)], dim=1
)
local_graph_contrast_loss = criterion(
local_graph_features, mask=mask_i
)
sum_local_graph_loss = sum_local_graph_loss + local_graph_contrast_loss
mean_local_graph_contrast_loss = sum_local_graph_loss / \
mask.shape[0]
local_graph_losses.update(
mean_local_graph_contrast_loss.item(), bsz
)
loss = loss + args.weight_local_contrast * mean_local_graph_contrast_loss
else:
local_graph_losses.update(0., bsz)
losses.update(loss.item(), bsz)
optimizer.zero_grad()
loss.backward()
optimizer.step()
elif optimizer_time == 2:
# optimize contrastive loss
_, f1_1, f2_1, graph_1, graph_2 = model(tup)
bsz = f1_1.shape[0]
features = torch.cat([f1_1.unsqueeze(1), f2_1.unsqueeze(1)], dim=1)
graph_features = torch.cat(
[graph_1.unsqueeze(1), graph_2.unsqueeze(1)], dim=1
)
cnn_contrast_loss = criterion(
features, labels=tup['slice_position']
)
graph_scontrast_loss = criterion(
graph_features, labels=tup['slice_position']
)
cnn_loss.update(cnn_contrast_loss.item(), bsz)
graph_loss.update(graph_scontrast_loss.item(), bsz)
contrast_loss = args.weight_cnn_contrast * cnn_contrast_loss + \
args.weight_graph_contrast * graph_scontrast_loss
if torch.isnan(contrast_loss):
print('nan contrast loss')
continue
optimizer.zero_grad()
contrast_loss.backward()
optimizer.step()
# optimize corr loss
corr_loss, _, _, _, _ = model(tup)
corr_loss = corr_loss.mean()
corr_losses.update(corr_loss.item(), bsz)
corr_loss = args.weight_corr * corr_loss
if torch.isnan(corr_loss):
print('nan corr loss')
continue
corr_optimizer.zero_grad()
corr_loss.backward()
corr_optimizer.step()
loss = corr_loss + contrast_loss
losses.update(loss.item(), bsz)
else:
raise NotImplementedError
logger.print(
f"epoch:{epoch:4d}, batch:{batch_idx:4d}/{len(data_loader)}, "
f"lr:{optimizer.param_groups[0]['lr']:.6f}, "
f"cnn loss:{cnn_loss.avg:.4f} "
f"graph loss:{graph_loss.avg:.4f} "
f"corr loss:{corr_losses.avg:.4f} "
f"local graph loss:{local_graph_losses.avg:.4f} "
f"total loss:{losses.avg:.4f}"
)
return losses.avg
if __name__ == '__main__':
main()