forked from JoshuaChou2018/PPPML-HMI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrainPPPML.py
2558 lines (2246 loc) · 116 KB
/
TrainPPPML.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import h5py
import matplotlib.pyplot as plt
import numpy as np
import argparse
import importlib
import random
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import json
import copy
from torch.utils.data import DataLoader
from torch.optim import Optimizer
from math import sqrt, exp
from scipy.special import erf
import covseg.models.Unet_2D.U_net_loss_function as unlf
from covseg.models.Unet_2D.dataset import RandomFlipWithWeight, RandomRotateWithWeight, ToTensorWithWeight, \
WeightedTissueDataset
import covseg.models.Unet_2D.U_net_Model as unm
from copy import deepcopy
import torchvision.transforms
import collections
import time
import tenseal as ts
from torchvision.models import densenet121
import pandas as pd
from sklearn.model_selection import train_test_split
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
import logging
from Net import DenseNet
from covseg.Tool_Functions import Functions
def log_creater(final_log_file):
# creat a log
log = logging.getLogger('train_log')
log.setLevel(logging.DEBUG)
# FileHandler
file = logging.FileHandler(final_log_file,'w')
file.setLevel(logging.DEBUG)
# StreamHandler
stream = logging.StreamHandler()
stream.setLevel(logging.DEBUG)
# Formatter
formatter = logging.Formatter(
'[%(asctime)s][line: %(lineno)d] ==> [INFO] %(message)s')
# setFormatter
file.setFormatter(formatter)
stream.setFormatter(formatter)
# addHandler
log.addHandler(file)
log.addHandler(stream)
log.info('creating {}'.format(final_log_file))
return log
## For RAD Dataset
my_transform = transforms.Compose([
transforms.Resize((299,299)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
class RADDataset(Dataset):
def __init__(self, x=None, y=None, thickness = -1):
self.x = x
self.y = y
self.thickness = thickness
def __len__(self):
return len(self.y)
def __getitem__(self, index):
img_path = self.x[index]
if self.thickness!=-1:
ct_array = np.load(f'my_rescaled_70x/{self.x[index]}.npy')
ct_array = ct_array.reshape(ct_array.shape[0]//self.thickness, self.thickness, ct_array.shape[1], ct_array.shape[2])
ct_array = ct_array.mean(axis = 1)
#ct_array = np.array([Functions.rescale_2d_array(ct_array[:,:,i],(70,70)) for i in range(int(ct_array.shape[2]))])
#ct_array = ct_array.transpose((1,2,0))
new_data = np.zeros(shape=[70,70,70], dtype=np.float32)
new_data[int((70-ct_array.shape[0])/2):int((70-ct_array.shape[0])/2)+ct_array.shape[0],:,:]=ct_array
ct_array = new_data
else:
ct_array = np.load(f'my_rescaled/{self.x[index]}.npy')
return torch.tensor(ct_array).unsqueeze(0), torch.tensor(self.y[index])
def read_user_data_RAD(index, args):
id = index
exp = args.exp
df = pd.read_csv(f'{exp}.csv')
user_params = deepcopy(args.params)
check_point_dict = f"{user_params['checkpoint_dir']}/{index}/"
user_params["checkpoint_dir"] = check_point_dict
params = deepcopy(user_params)
try:
if not os.path.isdir(params["checkpoint_dir"]):
os.system(f'mkdir -p {params["checkpoint_dir"]}')
logger.info(f'mkdir {params["checkpoint_dir"]}')
except:
pass
if True:
client = str(index)
X = list(df[df.client==client].NoteAcc_DEID)
Y = list(df[df.client==client].binary_infection_to_lung_ratio)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=30)
logger.info(f'client {client}, #Train: {len(Y_train)}, #Test: {len(Y_test)}, #Train posi: {sum(np.array(Y_train)>0)}, #Test posi: {sum(np.array(Y_test)>0)}')
if client == '0':
thickness = 1
elif client == '1':
thickness = 5
elif client == '2':
thickness = 10
train_dataset = RADDataset(X_train, Y_train, thickness = thickness)
test_dataset = RADDataset(X_test, Y_test, thickness = thickness)
return id, train_dataset, test_dataset, user_params
# load COVID data for each user
def read_user_data_COVID(index, args):
#index: user index, 对应COVID_client_labels中的label
label = args.COVID_client_labels[index]
id = index
user_params = deepcopy(args.params)
logger.info(f'>> reading data at client: {label}')
user_params["test_id"] = args.test_id
train_dict = f"{args.COVID_data_root}/{label}/training_samples/{args.direction}"
user_params["train_data_dir"] = train_dict
user_params["test_data_dir"] = train_dict
check_point_dict = f"{args.COVID_checkpoint_root}/{label}/{args.direction}"
user_params["checkpoint_dir"] = check_point_dict
if user_params["balance_weights"] is None:
user_params["balance_weights"] = [1000000000, 1]
flag=False
#other_ids=deepcopy(args.test_ids)
other_ids=[0,1,2,3,4]
other_ids.remove(args.test_id)
params = deepcopy(user_params)
while flag!=True and len(other_ids)>=0:
try:
if not os.path.isdir(params["checkpoint_dir"]):
os.makedirs(params["checkpoint_dir"])
except:
pass
train_transform = torchvision.transforms.Compose([
ToTensorWithWeight(),
RandomFlipWithWeight(),
RandomRotateWithWeight()
])
train_transform_no_rotate = torchvision.transforms.Compose([
ToTensorWithWeight(),
RandomFlipWithWeight(),
])
test_transform = torchvision.transforms.Compose([
ToTensorWithWeight()
])
if params["no_rotate"] is True:
train_dataset = WeightedTissueDataset(
params["train_data_dir"],
params["weight_dir"],
transform=train_transform_no_rotate,
channels=params["channels"],
mode="train",
test_id=params["test_id"],
wrong_patient_id=params["wrong_patient_id"],
default_weight=params["default_weight"]
)
else:
train_dataset = WeightedTissueDataset(
params["train_data_dir"],
params["weight_dir"],
transform=train_transform,
channels=params["channels"],
mode="train",
test_id=params["test_id"],
wrong_patient_id=params["wrong_patient_id"],
default_weight=params["default_weight"]
)
test_dataset = WeightedTissueDataset(
params["train_data_dir"],
params["weight_dir"],
transform=test_transform,
channels=params["channels"],
mode='test',
test_id=params["test_id"],
wrong_patient_id=params["wrong_patient_id"],
default_weight=params["default_weight"]
)
logger.info("train:", params["train_data_dir"], len(train_dataset))
logger.info("test:", params["test_data_dir"], len(test_dataset))
if len(test_dataset)>0:
flag=True
else:
old_id = params["test_id"]
params["test_id"]=other_ids[0]
other_ids.remove(params["test_id"])
logger.info(f'>> Because test id: {old_id} has no data in this client, so we change the test id to: {params["test_id"]}, remaining choice: {other_ids}')
return id, train_dataset, test_dataset, user_params
# User
class User:
"""
Base class for users in federated learning.
"""
def __init__(self, device, id, train_data, test_data, model, batch_size=0, learning_rate=0, beta=0, lamda=0,
local_epochs=0,user_params=None):
self.device = device
self.model = copy.deepcopy(model)
self.id = id # integer
self.train_samples = len(train_data)
self.test_samples = len(test_data)
self.batch_size = batch_size
self.learning_rate = learning_rate
self.beta = beta
self.lamda = lamda
self.local_epochs = local_epochs
self.trainloader = DataLoader(train_data, self.batch_size,shuffle=True)
self.testloader = DataLoader(test_data, self.batch_size,shuffle=False)
self.testloaderfull = DataLoader(test_data, self.test_samples)
self.trainloaderfull = DataLoader(train_data, self.train_samples)
self.iter_trainloader = iter(self.trainloader)
self.iter_testloader = iter(self.testloader)
self.user_params=user_params
# those parameters are for persionalized federated learing.
self.local_model = copy.deepcopy(list(self.model.parameters()))
self.persionalized_model = copy.deepcopy(list(self.model.parameters()))
self.persionalized_model_bar = copy.deepcopy(list(self.model.parameters()))
def set_parameters(self, model):
for old_param, new_param, local_param in zip(self.model.parameters(), model.parameters(), self.local_model):
old_param.data = new_param.data.clone()
local_param.data = new_param.data.clone()
# self.local_weight_updated = copy.deepcopy(self.optimizer.param_groups[0]['params'])
def get_parameters(self):
for param in self.model.parameters():
param.detach()
return self.model.parameters()
def clone_model_paramenter(self, param, clone_param):
for param, clone_param in zip(param, clone_param):
clone_param.data = param.data.clone()
return clone_param
def get_updated_parameters(self):
return self.local_weight_updated
def update_parameters(self, new_params):
for param, new_param in zip(self.model.parameters(), new_params):
param.data = new_param.data.clone()
def get_grads(self):
grads = []
for param in self.model.parameters():
if param.grad is None:
grads.append(torch.zeros_like(param.data))
else:
grads.append(param.grad.data)
return grads
def train_COVID(self):
self.model.train()
logger.info(f'--------------- Local train on client: {args.COVID_client_labels[self.numeric_id]} ---------------')
params = self.user_params
params[
"saved_model_filename"] = f"rep{args.current_repeat_experiment_id}_globalepoch{args.current_global_epoch_id}_testid{str(args.test_id)}_saved_model.pth"
resume = True
if resume and params["best_f1"] is not None: # direct give freq best_f1
best_f1 = params["best_f1"]
else:
best_f1 = 0
saved_model_path = os.path.join(params["checkpoint_dir"], 'current_' + params["saved_model_filename"])
if resume and os.path.isfile(saved_model_path):
logger.info(">> load saved model")
data_dict = torch.load(saved_model_path)
epoch_start = data_dict["epoch"]
if type(self.model) == nn.DataParallel:
self.model.module.load_state_dict(data_dict["state_dict"])
else:
self.model.load_state_dict(data_dict["state_dict"])
self.optimizer.load_state_dict(data_dict["optimizer"])
history = data_dict["history"]
best_f1 = data_dict["best_f1"]
self.phase_info = data_dict["phase_info"]
logger.info("best_f1 is:", best_f1)
else: # this means we do not have freq checkpoint
epoch_start = 0
history = collections.defaultdict(list)
self.phase_info = None
logger.info("Going to train epochs [%d-%d]" % (epoch_start + 1, epoch_start + args.local_epochs))
if self.phase_info is None:
base = 1
self.precision_phase = True # if in precision phase, the model increase the precision
flip_remaining = params[
"flip_remaining:"] # initially, model has high recall low precision. Thus, we initially
# in the precision phase. When precision is high and recall is low, we flip to recall phase.
# flip_remaining is the number times flip precision phase to recall phase
self.fluctuate_phase = False
# when flip_remaining is 0 and the model reached target_performance during recall phase, change to fluctuate
# phase during this phase, the recall fluctuate around the target_performance.
fluctuate_epoch = 0
current_phase = "precision"
else:
current_phase, base, flip_remaining, fluctuate_epoch = self.phase_info
if current_phase == 'precision':
self.precision_phase = True
else:
self.precision_phase = False
if current_phase == 'fluctuate':
self.fluctuate_phase = True
else:
self.fluctuate_phase = False
logger.info("current_phase, base, flip_remaining, fluctuate_epoch:", current_phase, base, flip_remaining,
fluctuate_epoch)
previous_recall = 0
precision_to_recall_count = 4
for epoch in range(epoch_start + 1, epoch_start + 1 + args.local_epochs):
logger.info(
f"--------------- Local train on client: {args.COVID_client_labels[self.numeric_id]}, Local training epoch: {epoch} ---------------")
logger.info("fluctuate_epoch:", fluctuate_epoch)
if fluctuate_epoch > 50:
break
if precision_to_recall_count < 0:
break
self.model.train()
for i, sample in enumerate(self.trainloader):
current_batch_size, input_channel, width, height = sample["image"].shape
image = sample["image"].to(self.device).float()
label = torch.zeros([current_batch_size, 2, width, height])
label[:, 0:1, :, :] = 1 - sample["label"]
label[:, 1::, :, :] = sample["label"]
label = label.to(self.device).float()
weight = sample["weight"].to(self.device).float()
pred = self.model(image)
maximum_balance = params["balance_weights"][0]
hyper_balance = base
if hyper_balance > maximum_balance:
hyper_balance = maximum_balance
if args.algorithm=='FedAvg':
loss = unlf.cross_entropy_pixel_wise_multi_class(pred, label, weight,
(hyper_balance, 100 / hyper_balance))
# loss = unlf.cross_entropy_pixel_wise_2d_binary_with_pixel_weight(pred, sample["label"].to(params["device"]), weight)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if i % 10 == 0:
logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss), base,
(hyper_balance, 100 / hyper_balance))
elif args.algorithm=='PerAvg' or args.algorithm == 'CSAPerAvg':
temp_model = copy.deepcopy(list(self.model.parameters()))
loss = unlf.cross_entropy_pixel_wise_multi_class(pred, label, weight,
(hyper_balance, 100 / hyper_balance))
# loss = unlf.cross_entropy_pixel_wise_2d_binary_with_pixel_weight(pred, sample["label"].to(params["device"]), weight)
if i%2==0:
# step 1
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
else:
tmp_optimizer=torch.optim.Adam(self.model.parameters(),lr=self.beta)
tmp_optimizer.zero_grad()
loss.backward()
# step 2
# restore the model parameters to the one before first update
for old_p, new_p in zip(self.model.parameters(), temp_model):
old_p.data = new_p.data.clone()
tmp_optimizer.step()
#self.optimizer.step(beta=self.beta)
# clone model to user model
self.clone_model_paramenter(self.model.parameters(), self.local_model)
if i % 10 == 0:
logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss), base,
(hyper_balance, 100 / hyper_balance))
logger.info("\tEvaluating")
eval_vals_train = evaluate_COVID(self.model, self.testloader, params, self.device)
logger.info("flip_remaining:", flip_remaining, "self.precision_phase:", self.precision_phase)
if epoch >= 0 and not self.fluctuate_phase: # recall will be very very high, start with precision phase
if eval_vals_train["precision"] < params["target_performance"] and self.precision_phase:
logger.info("precision phase, increase base to", base * 1.13)
base = base * 1.13
elif self.precision_phase:
self.precision_phase = False
logger.info("change to recall phase")
if eval_vals_train["recall"] < params["baseline_performance_recall"] and self.precision_phase:
logger.info("the recall is too low when we try to improve precision")
self.precision_phase = False
logger.info("change to recall phase")
if eval_vals_train["recall"] < params["target_performance"] and not self.precision_phase:
logger.info("recall phase, decrease base to", base / 1.15)
base = base / 1.15
elif not self.precision_phase:
if flip_remaining > 0:
flip_remaining -= 1
self.precision_phase = True
logger.info("change to precision phase")
else:
logger.info("change to fluctuate phase")
self.fluctuate_phase = True
if self.fluctuate_phase:
if eval_vals_train['recall'] > params["target_performance"] > previous_recall:
precision_to_recall_count -= 1
logger.info("precision to recall count:", precision_to_recall_count)
if eval_vals_train["recall"] < params["target_performance"]:
logger.info("fluctuate phase, decrease base to", base / 1.025)
base = base / 1.025
else:
logger.info("fluctuate phase, increase base to", base * 1.024)
base = base * 1.024
fluctuate_epoch += 1
previous_recall = eval_vals_train['recall']
if self.precision_phase:
current_phase = 'precision'
elif self.fluctuate_phase:
current_phase = 'fluctuate'
else:
current_phase = 'recall'
self.phase_info = [current_phase, base, flip_remaining, fluctuate_epoch]
for k, v in eval_vals_train.items():
history[k + "_train"].append(v)
logger.info("\tloss=%.4f, precision=%.4f, recall=%.4f, f1=%.4f"
% (
eval_vals_train["loss"], eval_vals_train["precision"], eval_vals_train["recall"],
eval_vals_train["f1"]))
if eval_vals_train["f1"] > best_f1 and eval_vals_train["recall"] > params["target_performance"] - 0.01:
logger.info(">> saving local model")
best_f1 = eval_vals_train["f1"]
save_checkpoint(epoch, self.model, self.optimizer, history, best_f1, params, phase_info=self.phase_info)
save_checkpoint(epoch, self.model, self.optimizer, history, eval_vals_train["f1"], params, False,
phase_info=self.phase_info)
logger.info("Training finished")
logger.info("best_f1:", best_f1)
def train_RAD(self):
self.model.train()
logger.info(f'--------------- Local train on client: {self.numeric_id} ---------------')
params = self.user_params
params[
"saved_model_filename"] = f"rep{args.current_repeat_experiment_id}_globalepoch{args.current_global_epoch_id}_saved_model.pth"
loss_criterion = torch.nn.CrossEntropyLoss()
best_acc = 0
for epoch in range(args.local_epochs):
logger.info(
f"--------------- Local train on client: {self.numeric_id}, Local training epoch: {epoch} ---------------")
self.model.train()
i=0
for data, target in tqdm(self.trainloader):
data = data.to(device=self.device)
target = target.to(device=self.device)
score = self.model(data)
#logger.info(score,target)
if args.algorithm == 'FedAvg':
loss = loss_criterion(score, target)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if i % 10 == 0:
logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss))
elif args.algorithm == 'PerAvg' or args.algorithm == 'CSAPerAvg':
temp_model = copy.deepcopy(list(self.model.parameters()))
loss = loss_criterion(score, target)
if i % 2 == 0:
# step 1
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
else:
tmp_optimizer=torch.optim.Adam(self.model.parameters(),lr=self.beta)
tmp_optimizer.zero_grad()
loss.backward()
# step 2
# restore the model parameters to the one before first update
for old_p, new_p in zip(self.model.parameters(), temp_model):
old_p.data = new_p.data.clone()
tmp_optimizer.step()
# self.optimizer.step(beta=self.beta)
# clone model to user model
self.clone_model_paramenter(self.model.parameters(), self.local_model)
if i % 10 == 0:
logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss))
i+=1
logger.info("\tEvaluating")
eval_vals_train = evaluate_RAD(self.model, self.testloader, params, self.device)
logger.info("\tloss=%.4f"% (eval_vals_train["acc"]))
if eval_vals_train["acc"] > best_acc:
logger.info(">> saving local model")
best_acc = eval_vals_train["acc"]
save_checkpoint(epoch, self.model, self.optimizer, None, best_acc, params, phase_info=None)
save_checkpoint(epoch, self.model, self.optimizer, None, eval_vals_train["acc"], params, False,
phase_info=None)
logger.info("Training finished")
logger.info(f"best_acc: {best_acc}")
def train_COVID_onestep(self):
self.model.train()
#logger.info(f'--------------- Local train on client: {args.COVID_client_labels[self.numeric_id]} ---------------')
params = self.user_params
params[
"saved_model_filename"] = f"rep{args.current_repeat_experiment_id}_globalepoch{args.current_global_epoch_id}_testid{str(args.test_id)}_onestepfinetune_saved_model.pth"
resume = True
if resume and params["best_f1"] is not None: # direct give freq best_f1
best_f1 = params["best_f1"]
else:
best_f1 = 0
saved_model_path = os.path.join(params["checkpoint_dir"], 'current_' + params["saved_model_filename"])
if resume and os.path.isfile(saved_model_path):
#logger.info(">> load saved model")
data_dict = torch.load(saved_model_path)
epoch_start = data_dict["epoch"]
if type(self.model) == nn.DataParallel:
self.model.module.load_state_dict(data_dict["state_dict"])
else:
self.model.load_state_dict(data_dict["state_dict"])
self.optimizer.load_state_dict(data_dict["optimizer"])
history = data_dict["history"]
best_f1 = data_dict["best_f1"]
self.phase_info = data_dict["phase_info"]
#logger.info("best_f1 is:", best_f1)
else: # this means we do not have freq checkpoint
epoch_start = 0
history = collections.defaultdict(list)
self.phase_info = None
#logger.info("Going to train epochs [%d-%d]" % (epoch_start + 1, epoch_start + params["n_epochs"]))
if self.phase_info is None:
base = 1
self.precision_phase = True # if in precision phase, the model increase the precision
flip_remaining = params[
"flip_remaining:"] # initially, model has high recall low precision. Thus, we initially
# in the precision phase. When precision is high and recall is low, we flip to recall phase.
# flip_remaining is the number times flip precision phase to recall phase
self.fluctuate_phase = False #TODO finetune的时候让模型直接进去fluctuate phase
# when flip_remaining is 0 and the model reached target_performance during recall phase, change to fluctuate
# phase during this phase, the recall fluctuate around the target_performance.
fluctuate_epoch = 0
current_phase = "precision"
else:
current_phase, base, flip_remaining, fluctuate_epoch = self.phase_info
if current_phase == 'precision':
self.precision_phase = True
else:
self.precision_phase = False
if current_phase == 'fluctuate':
self.fluctuate_phase = True
else:
self.fluctuate_phase = False
#logger.info("current_phase, base, flip_remaining, fluctuate_epoch:", current_phase, base, flip_remaining,fluctuate_epoch)
previous_recall = 0
precision_to_recall_count = 4
for epoch in range(epoch_start + 1, epoch_start + 1 + args.onestepupdate):
#logger.info(f"--------------- Local train on client: {args.COVID_client_labels[self.numeric_id]}, Local training epoch: {epoch} ---------------")
#logger.info("fluctuate_epoch:", fluctuate_epoch)
logger.info(f'onestep finetune: {epoch}/{args.onestepupdate} @ {args.COVID_client_labels[self.id]}')
if fluctuate_epoch > 50:
break
if precision_to_recall_count < 0:
break
self.model.train()
for i, sample in enumerate(self.trainloader):
current_batch_size, input_channel, width, height = sample["image"].shape
image = sample["image"].to(self.device).float()
label = torch.zeros([current_batch_size, 2, width, height])
label[:, 0:1, :, :] = 1 - sample["label"]
label[:, 1::, :, :] = sample["label"]
label = label.to(self.device).float()
weight = sample["weight"].to(self.device).float()
pred = self.model(image)
maximum_balance = params["balance_weights"][0]
hyper_balance = base
if hyper_balance > maximum_balance:
hyper_balance = maximum_balance
if args.algorithm == 'FedAvg':
loss = unlf.cross_entropy_pixel_wise_multi_class(pred, label, weight,
(hyper_balance, 100 / hyper_balance))
# loss = unlf.cross_entropy_pixel_wise_2d_binary_with_pixel_weight(pred, sample["label"].to(params["device"]), weight)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if i % 10 == 0:
pass
#logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss), base,(hyper_balance, 100 / hyper_balance))
elif args.algorithm == 'PerAvg' or args.algorithm == 'CSAPerAvg':
temp_model = copy.deepcopy(list(self.model.parameters()))
loss = unlf.cross_entropy_pixel_wise_multi_class(pred, label, weight,
(hyper_balance, 100 / hyper_balance))
# loss = unlf.cross_entropy_pixel_wise_2d_binary_with_pixel_weight(pred, sample["label"].to(params["device"]), weight)
if i % 2 == 0:
# step 1
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
else:
tmp_optimizer=torch.optim.Adam(self.model.parameters(),lr=self.beta)
tmp_optimizer.zero_grad()
loss.backward()
# step 2
# restore the model parameters to the one before first update
for old_p, new_p in zip(self.model.parameters(), temp_model):
old_p.data = new_p.data.clone()
tmp_optimizer.step()
# self.optimizer.step(beta=self.beta)
# clone model to user model
self.clone_model_paramenter(self.model.parameters(), self.local_model)
if i % 10 == 0:
pass
#logger.info("\tstep [%d/%d], loss=%.4f" % (i + 1, len(self.trainloader), loss), base,(hyper_balance, 100 / hyper_balance))
#logger.info("\tEvaluating")
eval_vals_train = evaluate_COVID(self.model, self.testloader, params, self.device)
#logger.info("flip_remaining:", flip_remaining, "self.precision_phase:", self.precision_phase)
# 对于finetune来说 30没有作用了
if epoch >= 0 and not self.fluctuate_phase: # recall will be very very high, start with precision phase
if eval_vals_train["precision"] < params["target_performance"] and self.precision_phase:
#logger.info("precision phase, increase base to", base * 1.13)
base = base * 1.13
elif self.precision_phase:
self.precision_phase = False
#logger.info("change to recall phase")
if eval_vals_train["recall"] < params["baseline_performance_recall"] and self.precision_phase:
#logger.info("the recall is too low when we try to improve precision")
self.precision_phase = False
#logger.info("change to recall phase")
if eval_vals_train["recall"] < params["target_performance"] and not self.precision_phase:
#logger.info("recall phase, decrease base to", base / 1.15)
base = base / 1.15
elif not self.precision_phase:
if flip_remaining > 0:
flip_remaining -= 1
self.precision_phase = True
#logger.info("change to precision phase")
else:
#logger.info("change to fluctuate phase")
self.fluctuate_phase = True
if self.fluctuate_phase:
if eval_vals_train['recall'] > params["target_performance"] > previous_recall:
precision_to_recall_count -= 1
#logger.info("precision to recall count:", precision_to_recall_count)
if eval_vals_train["recall"] < params["target_performance"]:
#logger.info("fluctuate phase, decrease base to", base / 1.025)
base = base / 1.025
else:
#logger.info("fluctuate phase, increase base to", base * 1.024)
base = base * 1.024
fluctuate_epoch += 1
previous_recall = eval_vals_train['recall']
if self.precision_phase:
current_phase = 'precision'
elif self.fluctuate_phase:
current_phase = 'fluctuate'
else:
current_phase = 'recall'
self.phase_info = [current_phase, base, flip_remaining, fluctuate_epoch]
for k, v in eval_vals_train.items():
history[k + "_train"].append(v)
#logger.info("\tloss=%.4f, precision=%.4f, recall=%.4f, f1=%.4f"% (eval_vals_train["loss"], eval_vals_train["precision"], eval_vals_train["recall"],eval_vals_train["f1"]))
if eval_vals_train["f1"] > best_f1 and eval_vals_train["recall"] > params["target_performance"] - 0.01:
#logger.info(">> saving local model")
best_f1 = eval_vals_train["f1"]
save_checkpoint(epoch, self.model, self.optimizer, history, best_f1, params, phase_info=self.phase_info)
save_checkpoint(epoch, self.model, self.optimizer, history, eval_vals_train["f1"], params, False,
phase_info=self.phase_info)
logger.info(f'>> onestep finetune precision: {eval_vals_train["precision"]}, recall: {eval_vals_train["recall"]}, f1: {eval_vals_train["f1"]}')
#logger.info("Training finished")
#logger.info("best_f1:", best_f1)
def train_RAD_onestep(self):
self.model.train()
params = self.user_params
params[
"saved_model_filename"] = f"rep{args.current_repeat_experiment_id}_globalepoch{args.current_global_epoch_id}_onestepfinetune_saved_model.pth"
loss_criterion = torch.nn.CrossEntropyLoss()
best_acc = 0
for epoch in range(args.onestepupdate):
logger.info(f'onestep finetune: {epoch}/{args.onestepupdate} @ {self.id}')
self.model.train()
i=0
for data, target in tqdm(self.trainloader):
data = data.to(device=self.device)
target = target.to(device=self.device)
score = self.model(data)
#logger.info(score,target)
if args.algorithm == 'FedAvg':
loss = loss_criterion(score, target)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
elif args.algorithm == 'PerAvg' or args.algorithm == 'CSAPerAvg':
temp_model = copy.deepcopy(list(self.model.parameters()))
loss = loss_criterion(score, target)
if i % 2 == 0:
# step 1
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
else:
tmp_optimizer=torch.optim.Adam(self.model.parameters(),lr=self.beta)
tmp_optimizer.zero_grad()
loss.backward()
# step 2
# restore the model parameters to the one before first update
for old_p, new_p in zip(self.model.parameters(), temp_model):
old_p.data = new_p.data.clone()
tmp_optimizer.step()
# self.optimizer.step(beta=self.beta)
# clone model to user model
self.clone_model_paramenter(self.model.parameters(), self.local_model)
i+=1
eval_vals_train = evaluate_RAD(self.model, self.testloader, params, self.device)
if eval_vals_train["acc"] > best_acc:
best_acc = eval_vals_train["acc"]
save_checkpoint(epoch, self.model, self.optimizer, None, best_acc, params, phase_info=None)
save_checkpoint(epoch, self.model, self.optimizer, None, eval_vals_train["acc"], params, False,
phase_info=None)
logger.info(f'>> onestep finetune acc: {eval_vals_train["acc"]}')
def test(self):
self.model.eval()
test_acc = 0
#if True:
with torch.no_grad():
for x, y in self.testloaderfull:
x, y = x.to(self.device), y.to(self.device)
output = self.model(x)
test_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item()
# @loss += self.loss(output, y)
# logger.info(self.id + ", Test Accuracy:", test_acc / y.shape[0] )
# logger.info(self.id + ", Test Loss:", loss)
return test_acc, y.shape[0]
def test_COVID(self):
self.model.eval()
count=0
with torch.no_grad():
vals = {
'loss': 0,
'tp': 0,
'fp': 0,
'fn': 0,
"tot_pixels": 0,
}
for i, sample in enumerate(self.testloader):
current_batch_size, input_channel, width, height = sample["image"].shape
vals["tot_pixels"] += current_batch_size * width * height
image = sample["image"].to(self.device).float()
label = sample["label"].to(self.device).float()
pred = self.model(image)
loss = unlf.cross_entropy_pixel_wise_2d_binary(pred, label,
balance_weights=args.params["balance_weights"]).item()
# here we use not_voxel_weighted loss to illustrate the performance
vals["loss"] += loss
pred = (pred[:, 1, :, :] > pred[:, 0, :, :]).float().unsqueeze(1)
pred_tp = pred * label
tp = pred_tp.sum().float().item()
vals["tp"] += tp
vals["fp"] += pred.sum().float().item() - tp
pred_fn = (1 - pred) * label
vals["fn"] += pred_fn.sum().float().item()
count+=image.shape[0]
eps = 1e-6
vals["loss"] = vals["loss"] / vals["tot_pixels"]
beta = args.params['beta'] # number times recall is more important than precision
vals["precision"] = (vals["tp"] + eps) / (vals["tp"] + vals["fp"] + eps)
vals["recall"] = (vals["tp"] + eps) / (vals["tp"] + vals["fn"] + eps)
vals["f1"] = (1 + beta * beta) * (vals["precision"] * vals["recall"] + eps) / \
(vals["precision"] * (beta * beta) + vals["recall"] + eps)
return vals, count
def test_RAD(self):
self.model.eval()
correct_output = 0
total_output = 0
with torch.no_grad():
vals = {}
for x, y in tqdm(self.testloader):
x = x.to(device=self.device)
y = y.to(device=self.device)
score = self.model(x)
_,predictions = score.max(1)
correct_output += (y==predictions).sum()
total_output += predictions.shape[0]
test_acc = float(correct_output.item()/total_output)
vals['acc'] = test_acc
return vals, total_output
def train_error_and_loss(self):
self.model.eval()
train_acc = 0
loss = 0
#count=0
#if True:
with torch.no_grad():
for x, y in self.trainloaderfull:
#logger.info(count)
#count+=1
x, y = x.to(self.device), y.to(self.device)
output = self.model(x)
train_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item()
loss += self.loss(output, y)
# logger.info(self.id + ", Train Accuracy:", train_acc)
# logger.info(self.id + ", Train Loss:", loss)
return train_acc, loss, self.train_samples
def train_error_and_loss_COVID(self):
self.model.eval()
#count=0
#if True:
count=0
with torch.no_grad():
vals = {
'loss': 0,
'tp': 0,
'fp': 0,
'fn': 0,
"tot_pixels": 0,
}
for i, sample in enumerate(self.trainloader):
current_batch_size, input_channel, width, height = sample["image"].shape
vals["tot_pixels"] += current_batch_size * width * height
image = sample["image"].to(self.device).float()
label = sample["label"].to(self.device).float()
pred = self.model(image)
loss = unlf.cross_entropy_pixel_wise_2d_binary(pred, label,
balance_weights=args.params["balance_weights"]).item()
# here we use not_voxel_weighted loss to illustrate the performance
vals["loss"] += loss
pred = (pred[:, 1, :, :] > pred[:, 0, :, :]).float().unsqueeze(1)
pred_tp = pred * label
tp = pred_tp.sum().float().item()
vals["tp"] += tp
vals["fp"] += pred.sum().float().item() - tp
pred_fn = (1 - pred) * label
vals["fn"] += pred_fn.sum().float().item()
count+=image.shape[0]
eps = 1e-6
vals["loss"] = vals["loss"] / vals["tot_pixels"]
beta = args.params['beta'] # number times recall is more important than precision
vals["precision"] = (vals["tp"] + eps) / (vals["tp"] + vals["fp"] + eps)
vals["recall"] = (vals["tp"] + eps) / (vals["tp"] + vals["fn"] + eps)
vals["f1"] = (1 + beta * beta) * (vals["precision"] * vals["recall"] + eps) / \
(vals["precision"] * (beta * beta) + vals["recall"] + eps)
return vals['f1'], vals['loss'], count
def train_error_and_loss_RAD(self):
self.model.eval()
#count=0
#if True:
count=0
correct_output = 0
total_output = 0
loss_criterion = torch.nn.CrossEntropyLoss()
with torch.no_grad():
vals = {
'loss': 0,
}
for data, target in tqdm(self.trainloader):
data = data.to(device=self.device)
target = target.to(device=self.device)
score = self.model(data)
self.optimizer.zero_grad()
loss = loss_criterion(score, target).item()
vals["loss"] += loss
_,predictions = score.max(1)
correct_output += (target==predictions).sum()
total_output += predictions.shape[0]
test_acc = float(correct_output.item()/total_output)
vals['acc'] = test_acc
return vals['acc'], vals['loss'], total_output
def test_persionalized_model(self):
self.model.eval()
test_acc = 0
self.update_parameters(self.persionalized_model_bar)
#if True:
with torch.no_grad():
for x, y in self.testloaderfull:
x, y = x.to(self.device), y.to(self.device)
output = self.model(x)
test_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item()
# @loss += self.loss(output, y)
# logger.info(self.id + ", Test Accuracy:", test_acc / y.shape[0] )
# logger.info(self.id + ", Test Loss:", loss)
self.update_parameters(self.local_model)
return test_acc, y.shape[0]
def test_persionalized_model_COVID(self):
self.model.eval()
self.update_parameters(self.persionalized_model_bar)
count = 0
with torch.no_grad():
vals = {
'loss': 0,
'tp': 0,
'fp': 0,
'fn': 0,
"tot_pixels": 0,
}
for i, sample in enumerate(self.testloader):
current_batch_size, input_channel, width, height = sample["image"].shape
vals["tot_pixels"] += current_batch_size * width * height
image = sample["image"].to(self.device).float()
label = sample["label"].to(self.device).float()
pred = self.model(image)
loss = unlf.cross_entropy_pixel_wise_2d_binary(pred, label,
balance_weights=args.params["balance_weights"]).item()
# here we use not_voxel_weighted loss to illustrate the performance
vals["loss"] += loss
pred = (pred[:, 1, :, :] > pred[:, 0, :, :]).float().unsqueeze(1)
pred_tp = pred * label
tp = pred_tp.sum().float().item()
vals["tp"] += tp
vals["fp"] += pred.sum().float().item() - tp
pred_fn = (1 - pred) * label
vals["fn"] += pred_fn.sum().float().item()
count += image.shape[0]
eps = 1e-6
vals["loss"] = vals["loss"] / vals["tot_pixels"]