-
Notifications
You must be signed in to change notification settings - Fork 6
/
experiments.py
2151 lines (1775 loc) · 111 KB
/
experiments.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
import numpy as np
import json
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torch.utils.data as data
from sklearn.metrics import confusion_matrix
from sklearn.datasets import load_svmlight_file
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
import argparse
import logging
import os
import copy
import datetime
import math
import xgboost as xgb
import pandas as pd
from model import *
from datasets import MNIST_truncated, SVHN_custom, CustomTensorDataset, CelebA_custom, ImageFolder_custom, PneumoniaDataset, ImageFolder_public
from trees import *
libsvm_datasets = {
"a9a": "binary_cls",
"cod-rna": "binary_cls"
}
n_workers = 0
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='MLP', help='neural network used in training')
parser.add_argument('--dataset', type=str, default='mnist', help='dataset used for training')
parser.add_argument('--net_config', type=lambda x: list(map(int, x.split(', '))))
parser.add_argument('--partition', type=str, default='hetero-dir', help='how to partition the dataset on local workers')
parser.add_argument('--batch-size', type=int, default=128, help='input batch size for training (default: 64)')
parser.add_argument('--lr', type=float, default=0.001, help='learning rate (default: 0.01)')
parser.add_argument('--epochs', type=int, default=5, help='how many epochs will be trained in a training process')
parser.add_argument('--n_parties', type=int, default=2, help='number of workers in a distributed cluster')
parser.add_argument('--n_teacher_each_partition', type=int, default=1,
help='number of local nets in a partitioning of a party')
parser.add_argument('--alg', type=str, default='fedavg',
help='which type of communication strategy is going to be used: fedavg/fedkt/fedprox/simenb')
parser.add_argument('--comm_round', type=int, default=1,
help='number of communication rounds')
parser.add_argument('--trials', type=int, default=1, help="Number of trials for each run")
parser.add_argument('--init_seed', type=int, default=0, help="Random seed")
parser.add_argument('--dropout_p', type=float, required=False, default=0.0, help="Dropout probability. Default=0.0")
parser.add_argument('--datadir', type=str, required=False, default="./data/", help="Data directory")
parser.add_argument('--reg', type=float, default=1e-5, help="L2 regularization strength")
parser.add_argument('--logdir', type=str, required=True, default="./logs/", help='Log directory path')
parser.add_argument('--modeldir', type=str, required=False, default="./models/", help='Model directory path')
parser.add_argument('--max_tree_depth', type=int, default=6, help='Max tree depth for the tree model')
parser.add_argument('--n_ensemble_models', type=int, default=10, help="Number of the models in the final ensemble")
parser.add_argument('--train_local_student', type=int, default=1, help="whether use PATE to train local student models before aggregation")
parser.add_argument('--auxiliary_data_portion', type=float, default=0.5, help="the portion of test data that is used as the auxiliary data for PATE")
parser.add_argument('--stu_epochs', type=int, default=100, help='Number of epochs for the student model')
parser.add_argument('--with_unlabeled', type=int, default=1, help='Whether there is public unlabeled data')
parser.add_argument('--stu_lr', type=float, default=0.001, help='The learning rate for the student model')
parser.add_argument('--is_local_split', type=int, default=1, help='Whether split the local data for local model training')
parser.add_argument('--beta', type=float, default=0.5, help='The parameter for the dirichlet distribution for data partitioning')
parser.add_argument('--device', type=str, default='cuda:0', help='The device to run the program')
parser.add_argument('--ensemble_method', type=str, default='max_vote', help='Choice: max_vote or averaging')
parser.add_argument('--log_file_name', type=str, default=None, help='The log file name')
parser.add_argument('--n_partition', type=int, default=1, help='The partition times of each party')
parser.add_argument('--gamma', type=float, default=None, help='The parameter for differential privacy')
parser.add_argument('--privacy_analysis_file_name', type=str, default=None, help='The file path to save the information for privacy analysis')
parser.add_argument('--n_stu_trees', type=int, default=100, help='The number of trees in a student model')
parser.add_argument('--optimizer', type=str, default='adam', help='sgd or adam optimizer')
parser.add_argument('--local_training_epochs', type=int, default=None, help='the number of epochs for the local trainig alg')
parser.add_argument('--dp_level', type=int, default=0, help='1 represents add dp on the server side. 2 represents add dp on the party side')
parser.add_argument('--query_portion', type=float, default=0.5, help='how many queries are used to train the final model')
parser.add_argument('--local_query_portion', type=float, default=0.5, help='how many queries are used to train the student models')
parser.add_argument('--filter_query', type=int, default=0, help='Whether to filter the query or not')
parser.add_argument('--max_z', type=int, default=1, help='the maximum partition that may be influenced when changing a single record')
parser.add_argument('--mu', type=float, default=1, help='the mu parameter for fedprox')
parser.add_argument('--fedkt_seed', type=int, default=0, help='the seed before run fedkt')
parser.add_argument('--pub_datadir', type=str, default=None, help='the path to the public data')
parser.add_argument('--prob_threshold', type=float, default=None, help='a threshold to filter the votes')
parser.add_argument('--min_require', type=int, default=None, help='require that the minimum number of samples of each class is at least min_require')
parser.add_argument('--prob_threshold_apply', type=int, default=0,
help='0 means no apply, 1 means apply only at server part, 2 means apply only at party part, 3 means apply at both parts')
parser.add_argument('--apply_consistency', type=int, default=1, help='the votes of the party will only be counted if they are the same if set to 1')
parser.add_argument('--save_global_model', type=int, default=0, help='whether save the global model or not')
parser.add_argument('--final_stu_epochs', type=int, default=100, help='the number of epochs to train the final student model')
parser.add_argument('--init_std', type=float, default=-1, help='the stdv for the initialization of the weights, -1 for norm initialization')
parser.add_argument('--std_place', type=int, default=0, help='1 for std in teacher model, 2 add student model')
parser.add_argument('--retrain_local_epoch', type=int, default=10, help='the local epoch in fedavg/fedprox after fedkt')
parser.add_argument('--n_final_stu_trees', type=int, default=100, help='the number of trees of the final model')
parser.add_argument('--npartyseed', type=str, default=None, help='nparty-seed')
parser.add_argument('--new_scaffold', type=int, default=0, help='whether use new scaffold')
args = parser.parse_args()
return args
def mkdirs(dirpath):
try:
os.makedirs(dirpath)
except Exception as _:
pass
def load_mnist_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
mnist_train_ds = MNIST_truncated(datadir, train=True, download=True, transform=transform)
mnist_test_ds = MNIST_truncated(datadir, train=False, download=True, transform=transform)
X_train, y_train = mnist_train_ds.data, mnist_train_ds.target
X_test, y_test = mnist_test_ds.data, mnist_test_ds.target
X_train = X_train.data.numpy()
y_train = y_train.data.numpy()
X_test = X_test.data.numpy()
y_test = y_test.data.numpy()
return (X_train, y_train, X_test, y_test)
def load_svhn_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
svhn_train_ds = SVHN_custom(datadir, train=True, download=True, transform=transform)
svhn_test_ds = SVHN_custom(datadir, train=False, download=True, transform=transform)
X_train, y_train = svhn_train_ds.data, svhn_train_ds.target
X_test, y_test = svhn_test_ds.data, svhn_test_ds.target
# X_train = X_train.data.numpy()
# y_train = y_train.data.numpy()
# X_test = X_test.data.numpy()
# y_test = y_test.data.numpy()
return (X_train, y_train, X_test, y_test)
def load_celeba_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
celeba_train_ds = CelebA_custom(datadir, split='train', target_type="attr", download=True, transform=transform)
celeba_test_ds = CelebA_custom(datadir, split='test', target_type="attr", download=True, transform=transform)
gender_index = celeba_train_ds.attr_names.index('Male')
y_train = celeba_train_ds.attr[:,gender_index:gender_index+1].reshape(-1)
y_test = celeba_test_ds.attr[:,gender_index:gender_index+1].reshape(-1)
# y_train = y_train.numpy()
# y_test = y_test.numpy()
return (None, y_train, None, y_test)
def load_xray_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
xray_train_ds = ImageFolder_custom(datadir+'./train/', transform=transform)
xray_test_ds = ImageFolder_custom(datadir+'./test/', transform=transform)
X_train, y_train = xray_train_ds.samples, xray_train_ds.target
X_test, y_test = xray_test_ds.samples, xray_test_ds.target
return (X_train, y_train, X_test, y_test)
def record_net_data_stats(y_train, net_dataidx_map, logdir):
net_cls_counts = {}
for net_i, dataidx in net_dataidx_map.items():
unq, unq_cnt = np.unique(y_train[dataidx], return_counts=True)
tmp = {unq[i]: unq_cnt[i] for i in range(len(unq))}
net_cls_counts[net_i] = tmp
logger.info('Data statistics: %s' % str(net_cls_counts))
return net_cls_counts
def partition_data(dataset, datadir, logdir, partition, n_parties, beta=0.4, min_require=None):
if dataset == 'mnist':
X_train, y_train, X_test, y_test = load_mnist_data(datadir)
elif dataset == 'svhn':
X_train, y_train, X_test, y_test = load_svhn_data(datadir)
elif dataset == 'celeba':
X_train, y_train, X_test, y_test = load_celeba_data(datadir)
elif dataset == 'xray' :
X_train, y_train, X_test, y_test = load_xray_data(datadir)
elif dataset in libsvm_datasets:
# X_train, y_train = load_svmlight_file(datadir + dataset + '.train')
# X_test, y_test = load_svmlight_file(datadir + dataset + '.test')
X, y = load_svmlight_file(datadir + dataset)
y_i_transform = np.zeros(y.size)
for i in range(y.size):
if y[i] == y[0]:
y_i_transform[i] = 1
y=np.copy(y_i_transform)
X_train, X_test, y_train, y_test = train_test_split(X, y)
n_train = y_train.shape[0]
if partition == "homo":
idxs = np.random.permutation(n_train)
batch_idxs = np.array_split(idxs, n_parties)
net_dataidx_map = {i: batch_idxs[i] for i in range(n_parties)}
elif partition == "hetero-dir":
min_size = 0
min_require_size = 10
if min_require is not None:
min_require_size = min_require
if dataset == 'mnist' or dataset == 'svhn':
K = 10
elif dataset in libsvm_datasets or dataset == 'celeba' or dataset == 'xray':
K = 2
# min_require_size = 100
N = y_train.shape[0]
net_dataidx_map = {}
while min_size < min_require_size:
idx_batch = [[] for _ in range(n_parties)]
for k in range(K):
idx_k = np.where(y_train == k)[0]
np.random.shuffle(idx_k)
proportions = np.random.dirichlet(np.repeat(beta, n_parties))
# print("proportions1: ", proportions)
# print("sum pro1:", np.sum(proportions))
## Balance
proportions = np.array([p * (len(idx_j) < N / n_parties) for p, idx_j in zip(proportions, idx_batch)])
# print("proportions2: ", proportions)
proportions = proportions / proportions.sum()
# print("proportions3: ", proportions)
proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]
# print("proportions4: ", proportions)
idx_split = np.split(idx_k, proportions)
idx_batch = [idx_j + idx.tolist() for idx_j, idx in zip(idx_batch, idx_split)]
min_size = min([len(idx_j) for idx_j in idx_batch])
if min_require is not None:
min_size = min(min_size, min([len(idx) for idx in idx_split]))
# if K == 2 and n_parties <= 10:
# if np.min(proportions) < 200:
# min_size = 0
# break
for j in range(n_parties):
np.random.shuffle(idx_batch[j])
net_dataidx_map[j] = idx_batch[j]
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return (X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts)
def init_nets(net_configs, dropout_p, n_parties, args, n_teacher_each_partition = 1, stdv=None):
n_total_nets = n_parties * n_teacher_each_partition
nets = {net_i: None for net_i in range(n_total_nets)}
for net_i in range(n_total_nets):
if args.model == "mlp":
input_size = net_configs[0]
output_size = net_configs[-1]
hidden_sizes = net_configs[1:-1]
net = FcNet(input_size, hidden_sizes, output_size, stdv, dropout_p)
# elif args.model == "vgg":
# net = vgg11()
elif args.model == "simple-cnn":
if args.dataset in ("svhn"):
net = SimpleCNN(input_dim=(16 * 5 * 5), hidden_dims=[120, 84], output_dim=10)
elif args.dataset == "mnist":
net = SimpleCNNMNIST(input_dim=(16 * 4 * 4), hidden_dims=[120, 84], output_dim=10)
elif args.dataset == 'celeba' or args.dataset == 'xray':
net = SimpleCNN(input_dim=(16 * 5 * 5), hidden_dims=[120, 84], output_dim=2)
elif args.model == "vgg-9":
if args.dataset in ("mnist"):
net = ModerateCNNMNIST()
elif args.dataset in ("svhn"):
# print("in moderate cnn")
net = ModerateCNN()
elif args.dataset == 'celeba':
net = ModerateCNN(output_dim=2)
# elif args.model == "resnet":
# net = ResNet50()
# elif args.model == "vgg16":
# net = vgg16()
elif args.model == 'lr':
if args.dataset == 'a9a':
net = LogisticRegression(123,2)
else:
print("not supported yet")
exit(1)
nets[net_i] = net
model_meta_data = []
layer_type = []
for (k, v) in nets[0].state_dict().items():
model_meta_data.append(v.shape)
layer_type.append(k)
return nets, model_meta_data, layer_type
def init_weights(m):
if type(m)==nn.Linear or type(m)==nn.Conv2d:
torch.nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
def get_trainable_parameters(net):
'return trainable parameter values as a vector (only the first parameter set)'
trainable=filter(lambda p: p.requires_grad, net.parameters())
# print("net.parameter.data:", list(net.parameters()))
paramlist=list(trainable)
N=0
for params in paramlist:
N+=params.numel()
# print("params.data:", params.data)
X=torch.empty(N,dtype=torch.float64)
X.fill_(0.0)
offset=0
for params in paramlist:
numel=params.numel()
with torch.no_grad():
X[offset:offset+numel].copy_(params.data.view_as(X[offset:offset+numel].data))
offset+=numel
# print("get trainable x:", X)
return X
def get_all_parameters(net):
'return trainable parameter values as a vector (only the first parameter set)'
# print("net.parameter.data:", list(net.parameters()))
paramlist=list(net.parameters())
N=0
for params in paramlist:
N+=params.numel()
# print("params.data:", params.data)
X=torch.empty(N,dtype=torch.float64)
X.fill_(0.0)
offset=0
for params in paramlist:
numel=params.numel()
with torch.no_grad():
X[offset:offset+numel].copy_(params.data.view_as(X[offset:offset+numel].data))
offset+=numel
# print("get trainable x:", X)
return X
def put_trainable_parameters(net,X):
'replace trainable parameter values by the given vector (only the first parameter set)'
trainable=filter(lambda p: p.requires_grad, net.parameters())
paramlist=list(trainable)
offset=0
for params in paramlist:
numel=params.numel()
with torch.no_grad():
params.data.copy_(X[offset:offset+numel].data.view_as(params.data))
offset+=numel
def put_all_parameters(net,X):
'replace trainable parameter values by the given vector (only the first parameter set)'
paramlist=list(net.parameters())
offset=0
for params in paramlist:
numel=params.numel()
with torch.no_grad():
params.data.copy_(X[offset:offset+numel].data.view_as(params.data))
offset+=numel
def compute_accuracy(model, dataloader, get_confusion_matrix=False, device="cpu"):
was_training = False
if model.training:
model.eval()
was_training = True
true_labels_list, pred_labels_list = np.array([]), np.array([])
correct, total = 0, 0
with torch.no_grad():
for batch_idx, (x, target, _) in enumerate(dataloader):
x, target = x.to(device), target.to(device)
out = model(x)
_, pred_label = torch.max(out.data, 1)
total += x.data.size()[0]
correct += (pred_label == target.data).sum().item()
if device == "cpu":
pred_labels_list = np.append(pred_labels_list, pred_label.numpy())
true_labels_list = np.append(true_labels_list, target.data.numpy())
else:
pred_labels_list = np.append(pred_labels_list, pred_label.cpu().numpy())
true_labels_list = np.append(true_labels_list, target.data.cpu().numpy())
if get_confusion_matrix:
conf_matrix = confusion_matrix(true_labels_list, pred_labels_list)
if was_training:
model.train()
if get_confusion_matrix:
return correct/float(total), conf_matrix
return correct/float(total)
def prepare_weight_matrix(n_classes, weights: dict):
weights_list = {}
for net_i, cls_cnts in weights.items():
cls = np.array(list(cls_cnts.keys()))
cnts = np.array(list(cls_cnts.values()))
weights_list[net_i] = np.array([0] * n_classes, dtype=np.float32)
weights_list[net_i][cls] = cnts
weights_list[net_i] = torch.from_numpy(weights_list[net_i]).view(1, -1)
return weights_list
def prepare_uniform_weights(n_classes, net_cnt, fill_val=1):
weights_list = {}
for net_i in range(net_cnt):
temp = np.array([fill_val] * n_classes, dtype=np.float32)
weights_list[net_i] = torch.from_numpy(temp).view(1, -1)
return weights_list
def prepare_sanity_weights(n_classes, net_cnt):
return prepare_uniform_weights(n_classes, net_cnt, fill_val=0)
def normalize_weights(weights):
Z = np.array([])
eps = 1e-6
weights_norm = {}
for _, weight in weights.items():
if len(Z) == 0:
Z = weight.data.numpy()
else:
Z = Z + weight.data.numpy()
for mi, weight in weights.items():
weights_norm[mi] = weight / torch.from_numpy(Z + eps)
return weights_norm
def get_weighted_average_pred(models: list, weights: dict, x, device="cpu"):
out_weighted = None
# Compute the predictions
for model_i, model in enumerate(models):
#logger.info("Model: {}".format(next(model.parameters()).device))
#logger.info("data device: {}".format(x.device))
out = F.softmax(model(x), dim=-1) # (N, C)
# print("model(x):", model(x))
# print("out:", out)
weight = weights[model_i].to(device)
if out_weighted is None:
weight = weight.to(device)
out_weighted = (out * weight)
else:
out_weighted += (out * weight)
return out_weighted
def get_pred_votes(models, x, threshold=None, device="cpu"):
# print("input x:", x)
# Compute the predictions
votes=torch.LongTensor([]).to(device)
for model_i, model in enumerate(models):
#logger.info("Model: {}".format(next(model.parameters()).device))
#logger.info("data device: {}".format(x.device))
out = F.softmax(model(x), dim=-1) # (N, C)
pred_probs, pred_label = torch.max(out,1)
if threshold is not None:
# pred_probs.to("cpu")
# pred_label.to("cpu")
for index, prob in enumerate(pred_probs):
if prob < threshold:
pred_label[index] = -1
# pred_label.to(device)
votes=torch.cat((votes, pred_label),dim=0)
return votes
def compute_ensemble_accuracy(models: list, dataloader, n_classes, ensemble_method="max_vote", train_cls_counts=None,
uniform_weights=False, sanity_weights=False, device="cpu"):
correct, total = 0, 0
true_labels_list, pred_labels_list = np.array([]), np.array([])
was_training = [False]*len(models)
for i, model in enumerate(models):
if model.training:
was_training[i] = True
model.eval()
if ensemble_method == "averaging":
if uniform_weights is True:
weights_list = prepare_uniform_weights(n_classes, len(models))
elif sanity_weights is True:
weights_list = prepare_sanity_weights(n_classes, len(models))
else:
weights_list = prepare_weight_matrix(n_classes, train_cls_counts)
weights_norm = normalize_weights(weights_list)
with torch.no_grad():
for batch_idx, (x, target, _) in enumerate(dataloader):
x, target = x.to(device), target.to(device)
target = target.long()
if ensemble_method == "averaging":
out = get_weighted_average_pred(models, weights_norm, x, device=device)
_, pred_label = torch.max(out, 1)
elif ensemble_method == "max_vote":
votes = get_pred_votes(models, x, device=device)
pred_label, _ = torch.mode(votes.view(-1, x.data.size()[0]), dim=0)
total += x.data.size()[0]
correct += (pred_label == target.data).sum().item()
if device == "cpu":
pred_labels_list = np.append(pred_labels_list, pred_label.numpy())
true_labels_list = np.append(true_labels_list, target.data.numpy())
else:
pred_labels_list = np.append(pred_labels_list, pred_label.cpu().numpy())
true_labels_list = np.append(true_labels_list, target.data.cpu().numpy())
#logger.info(correct, total)
conf_matrix = confusion_matrix(true_labels_list, pred_labels_list)
for i, model in enumerate(models):
if was_training[i]:
model.train()
return correct / float(total), conf_matrix
def train_net(net_id, net, train_dataloader, test_dataloader, epochs, lr, args_optimizer, device="cpu"):
logger.info('Training network %s' % str(net_id))
logger.info('n_training: %d' % len(train_dataloader))
logger.info('n_test: %d' % len(test_dataloader))
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Pre-Training Training accuracy: {}'.format(train_acc))
logger.info('>> Pre-Training Test accuracy: {}'.format(test_acc))
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=lr, weight_decay=args.reg)
criterion = nn.CrossEntropyLoss().to(device)
cnt = 0
for epoch in range(epochs):
epoch_loss_collector = []
for batch_idx, (x, target, _) in enumerate(train_dataloader):
x, target = x.to(device), target.to(device)
#for adam l2 reg
# l2_reg = torch.zeros(1)
# l2_reg.requires_grad = True
optimizer.zero_grad()
x.requires_grad = True
target.requires_grad = False
target = target.long()
out = net(x)
loss = criterion(out, target)
loss.backward()
optimizer.step()
cnt += 1
epoch_loss_collector.append(loss.item())
# logger.info('Epoch: %d Loss: %f L2 loss: %f' % (epoch, loss.item(), reg*l2_reg))
epoch_loss = sum(epoch_loss_collector) / len(epoch_loss_collector)
if epoch % 10 == 0:
logger.info('Epoch: %d Loss: %f' % (epoch, epoch_loss))
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
logger.info(' ** Training complete **')
return train_acc, test_acc
def train_net_fedprox(net_id, net, global_net, train_dataloader, test_dataloader, epochs, lr, args_optimizer, mu, model, device="cpu"):
logger.info('Training network %s' % str(net_id))
logger.info('n_training: %d' % len(train_dataloader))
logger.info('n_test: %d' % len(test_dataloader))
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Pre-Training Training accuracy: {}'.format(train_acc))
logger.info('>> Pre-Training Test accuracy: {}'.format(test_acc))
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=lr, weight_decay=args.reg)
criterion = nn.CrossEntropyLoss().to(device)
cnt = 0
# mu = 0.001
global_weight_collector = list(global_net.to(device).parameters())
for epoch in range(epochs):
epoch_loss_collector = []
for batch_idx, (x, target, _) in enumerate(train_dataloader):
x, target = x.to(device), target.to(device)
#for adam l2 reg
# l2_reg = torch.zeros(1)
# l2_reg.requires_grad = True
optimizer.zero_grad()
x.requires_grad = True
target.requires_grad = False
target = target.long()
out = net(x)
loss = criterion(out, target)
#for fedprox
fed_prox_reg = 0.0
# fed_prox_reg += np.linalg.norm([i - j for i, j in zip(global_weight_collector, get_trainable_parameters(net).tolist())], ord=2)
for param_index, param in enumerate(net.parameters()):
fed_prox_reg += ((mu / 2) * torch.norm((param - global_weight_collector[param_index]))**2)
loss += fed_prox_reg
loss.backward()
optimizer.step()
cnt += 1
epoch_loss_collector.append(loss.item())
# logger.info('Epoch: %d Loss: %f L2 loss: %f' % (epoch, loss.item(), reg*l2_reg))
epoch_loss = sum(epoch_loss_collector) / len(epoch_loss_collector)
logger.info('Epoch: %d Loss: %f' % (epoch, epoch_loss))
if epoch % 10 == 0:
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
logger.info(' ** Training complete **')
return train_acc, test_acc
def train_net_scaffold(net_id, net, global_net, train_dataloader, test_dataloader, epochs, lr, args_optimizer, args, server_c, client_c, device="cpu"):
logger.info('Training network %s' % str(net_id))
logger.info('n_training: %d' % len(train_dataloader))
logger.info('n_test: %d' % len(test_dataloader))
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Pre-Training Training accuracy: {}'.format(train_acc))
logger.info('>> Pre-Training Test accuracy: {}'.format(test_acc))
optimizer = optim.SGD(filter(lambda p: p.requires_grad, net.parameters()), lr=lr, weight_decay=args.reg)
criterion = nn.CrossEntropyLoss().to(device)
cnt = 0
# mu = 0.001
global_collector = list(global_net.to(device).parameters())
server_c_collector = list(server_c.to(device).parameters())
client_c_collector = list(client_c.to(device).parameters())
client_c_delta = copy.deepcopy(client_c_collector)
c_global_para = get_all_parameters(server_c)
c_local_para = get_all_parameters(client_c)
for epoch in range(epochs):
epoch_loss_collector = []
for batch_idx, (x, target, _) in enumerate(train_dataloader):
x, target = x.to(device), target.to(device)
#for adam l2 reg
# l2_reg = torch.zeros(1)
# l2_reg.requires_grad = True
optimizer.zero_grad()
x.requires_grad = True
target.requires_grad = False
target = target.long()
out = net(x)
loss = criterion(out, target)
loss.backward()
for param_index, param in enumerate(net.parameters()):
param.grad += server_c_collector[param_index] - client_c_collector[param_index]
optimizer.step()
# net_para = get_all_parameters(net)
# net_para = net_para - args.lr * (c_global_para - c_local_para)
# put_all_parameters(net, net_para)
# for param_index, param in enumerate(net.parameters()):
# r_grad = param.requires_grad
# param.requires_grad = False
# param -= args.lr*(server_c_collector[param_index] - client_c_collector[param_index])
# param.requires_grad = r_grad
cnt += 1
epoch_loss_collector.append(loss.item())
# logger.info('Epoch: %d Loss: %f L2 loss: %f' % (epoch, loss.item(), reg*l2_reg))
epoch_loss = sum(epoch_loss_collector) / len(epoch_loss_collector)
logger.info('Epoch: %d Loss: %f' % (epoch, epoch_loss))
if epoch % 10 == 0:
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
for param_index, param in enumerate(net.parameters()):
client_c_delta[param_index] = (global_collector[param_index] - param) / (
args.epochs * len(train_dataloader) * lr) - server_c_collector[param_index]
client_c_collector[param_index] += client_c_delta[param_index]
train_acc = compute_accuracy(net, train_dataloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
logger.info('>> Training accuracy: %f' % train_acc)
logger.info('>> Test accuracy: %f' % test_acc)
logger.info(' ** Training complete **')
return train_acc, test_acc, client_c_delta
def save_model(model, model_index, args):
logger.info("saving model-{}".format(model_index))
with open(os.path.join(args.logdir, args.log_file_name) + ".model" + str(model_index), "wb") as f_:
torch.save(model.state_dict(), f_)
return
def load_model(model, model_index, rank=0, device="cpu"):
#
with open("trained_local_model"+str(model_index), "rb") as f_:
model.load_state_dict(torch.load(f_))
model.to(device)
return model
def local_train_net(nets, args, net_dataidx_map, X_train = None, y_train = None, X_test = None, y_test = None, remain_test_dl = None, local_split=False, retrain_epoch=None, device="cpu"):
# save local dataset
# local_datasets = []
n_teacher_each_partition = args.n_teacher_each_partition
avg_acc = 0.0
if local_split:
split_datasets = []
for party_id in range(args.n_parties):
np.random.shuffle(net_dataidx_map[party_id])
split_datasets.append(np.array_split(net_dataidx_map[party_id], args.n_teacher_each_partition))
for net_id, net in nets.items():
if not local_split:
dataidxs = net_dataidx_map[net_id//n_teacher_each_partition]
else:
dataidxs = list(split_datasets[net_id//n_teacher_each_partition][net_id%n_teacher_each_partition])
logger.info("Training network %s. n_training: %d" % (str(net_id), len(dataidxs)))
# move the model to cuda device:
net.to(device)
if args.dataset in libsvm_datasets:
party_id = net_id // n_teacher_each_partition
train_ds_local = CustomTensorDataset(torch.tensor(X_train[net_dataidx_map[party_id]].toarray(), dtype=torch.float32),
torch.tensor(y_train[net_dataidx_map[party_id]], dtype=torch.long))
public_ds = CustomTensorDataset(torch.tensor(X_test[:public_data_size].toarray(), dtype=torch.float32),
torch.tensor(y_test[:public_data_size], dtype=torch.long))
remain_test_ds = CustomTensorDataset(torch.tensor(X_test[public_data_size:].toarray(), dtype=torch.float32),
torch.tensor(y_test[public_data_size:], dtype=torch.long))
train_dl_local = data.DataLoader(dataset=train_ds_local, batch_size=args.batch_size, shuffle=True)
remain_test_dl = data.DataLoader(dataset=remain_test_ds, batch_size=32, shuffle=False)
else:
train_dl_local, test_dl_local, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32, dataidxs)
train_dl_global, test_dl_global, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32)
# local_datasets.append((train_dl_local, test_dl_local))
# switch to global test set here
# if remain_test_dl is not None:
# test_dl_global = remain_test_dl
if args.alg == 'local_training':
n_epoch = args.local_training_epochs
else:
n_epoch = args.epochs
if retrain_epoch is not None:
n_epoch = retrain_epoch
trainacc, testacc = train_net(net_id, net, train_dl_local, remain_test_dl, n_epoch, args.lr, args.optimizer, device=device)
logger.info("net %d final test acc %f" % (net_id, testacc))
avg_acc += testacc
# saving the trained models here
# save_model(net, net_id, args)
# else:
# load_model(net, net_id, device=device)
avg_acc /= args.n_parties
if args.alg == 'local_training':
logger.info("avg test acc %f" % avg_acc)
nets_list = list(nets.values())
return nets_list
def local_train_net_fedprox(nets, global_model, args, net_dataidx_map, X_train = None, y_train = None, X_test = None, y_test = None, remain_test_dl = None, local_split=False, retrain_epoch=None, device="cpu"):
# save local dataset
# local_datasets = []
n_teacher_each_partition = args.n_teacher_each_partition
avg_acc = 0.0
if local_split:
split_datasets = []
for party_id in range(args.n_parties):
np.random.shuffle(net_dataidx_map[party_id])
split_datasets.append(np.array_split(net_dataidx_map[party_id], args.n_teacher_each_partition))
for net_id, net in nets.items():
if not local_split:
dataidxs = net_dataidx_map[net_id//n_teacher_each_partition]
else:
dataidxs = list(split_datasets[net_id//n_teacher_each_partition][net_id%n_teacher_each_partition])
logger.info("Training network %s. n_training: %d" % (str(net_id), len(dataidxs)))
# move the model to cuda device:
net.to(device)
if args.dataset in libsvm_datasets:
party_id = net_id//n_teacher_each_partition
train_ds_local = CustomTensorDataset(torch.tensor(X_train[net_dataidx_map[party_id]].toarray(), dtype=torch.float32),
torch.tensor(y_train[net_dataidx_map[party_id]], dtype=torch.long))
public_ds = CustomTensorDataset(torch.tensor(X_test[:public_data_size].toarray(), dtype=torch.float32),
torch.tensor(y_test[:public_data_size], dtype=torch.long))
remain_test_ds = CustomTensorDataset(torch.tensor(X_test[public_data_size:].toarray(), dtype=torch.float32),
torch.tensor(y_test[public_data_size:], dtype=torch.long))
train_dl_local = data.DataLoader(dataset=train_ds_local, batch_size=args.batch_size, shuffle=True, num_workers=n_workers)
remain_test_dl = data.DataLoader(dataset=remain_test_ds, batch_size=32, shuffle=False)
else:
train_dl_local, test_dl_local, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32, dataidxs)
train_dl_global, test_dl_global, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32)
if args.alg == 'local_training':
n_epoch = args.local_training_epochs
else:
n_epoch = args.epochs
if retrain_epoch is not None:
n_epoch = retrain_epoch
trainacc, testacc = train_net_fedprox(net_id, net, global_model, train_dl_local, remain_test_dl, n_epoch, args.lr, args.optimizer, args.mu, args.model, device=device)
logger.info("net %d final test acc %f" % (net_id, testacc))
avg_acc += testacc
avg_acc /= args.n_parties
if args.alg == 'local_training':
logger.info("avg test acc %f" % avg_acc)
nets_list = list(nets.values())
return nets_list
def local_train_net_scaffold(nets, global_model, args, net_dataidx_map, X_train = None, y_train = None, X_test = None, y_test = None, server_c=None, clients_c=None, remain_test_dl = None, local_split=False, device="cpu"):
n_teacher_each_partition = args.n_teacher_each_partition
avg_acc = 0.0
if local_split:
split_datasets = []
for party_id in range(args.n_parties):
np.random.shuffle(net_dataidx_map[party_id])
split_datasets.append(np.array_split(net_dataidx_map[party_id], args.n_teacher_each_partition))
server_c_collector = list(server_c.to(device).parameters())
new_server_c_collector = copy.deepcopy(server_c_collector)
for net_id, net in nets.items():
if not local_split:
dataidxs = net_dataidx_map[net_id // n_teacher_each_partition]
else:
dataidxs = list(split_datasets[net_id // n_teacher_each_partition][net_id % n_teacher_each_partition])
logger.info("Training network %s. n_training: %d" % (str(net_id), len(dataidxs)))
# move the model to cuda device:
net.to(device)
if args.dataset in libsvm_datasets:
party_id = net_id // n_teacher_each_partition
train_ds_local = CustomTensorDataset(
torch.tensor(X_train[net_dataidx_map[party_id]].toarray(), dtype=torch.float32),
torch.tensor(y_train[net_dataidx_map[party_id]], dtype=torch.long))
public_ds = CustomTensorDataset(torch.tensor(X_test[:public_data_size].toarray(), dtype=torch.float32),
torch.tensor(y_test[:public_data_size], dtype=torch.long))
remain_test_ds = CustomTensorDataset(torch.tensor(X_test[public_data_size:].toarray(), dtype=torch.float32),
torch.tensor(y_test[public_data_size:], dtype=torch.long))
train_dl_local = data.DataLoader(dataset=train_ds_local, batch_size=args.batch_size, shuffle=True,
num_workers=n_workers)
remain_test_dl = data.DataLoader(dataset=remain_test_ds, batch_size=32, shuffle=False)
else:
train_dl_local, test_dl_local, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32,
dataidxs)
train_dl_global, test_dl_global, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32)
if args.alg == 'local_training':
n_epoch = args.local_training_epochs
else:
n_epoch = args.epochs
trainacc, testacc, c_delta = train_net_scaffold(net_id, net, global_model, train_dl_local, remain_test_dl, n_epoch,
args.lr, args.optimizer, args, server_c, clients_c[net_id], device=device)
if args.new_scaffold:
for param_index, param in enumerate(server_c.parameters()):
new_server_c_collector[param_index] += c_delta[param_index] / args.n_parties
logger.info("net %d final test acc %f" % (net_id, testacc))
avg_acc += testacc
if args.new_scaffold:
for param_index, param in enumerate(server_c.parameters()):
server_c_collector[param_index] = new_server_c_collector[param_index]
avg_acc /= args.n_parties
if args.alg == 'local_training':
logger.info("avg test acc %f" % avg_acc)
nets_list = list(nets.values())
return nets_list
def local_train_net_on_a_party(nets, args, net_dataidx_map, party_id, X_train = None, y_train = None, X_test = None, y_test = None, remain_test_dl = None, local_split=0, device="cpu"):
# save local dataset
# local_datasets = []
n_teacher_each_partition = args.n_teacher_each_partition
if local_split:
split_datasets = []
np.random.shuffle(net_dataidx_map[party_id])
split_datasets = np.array_split(net_dataidx_map[party_id], args.n_teacher_each_partition)
for net_id, net in nets.items():
if not local_split:
dataidxs = net_dataidx_map[party_id]
else:
dataidxs = list(split_datasets[net_id])
logger.info("Training network %s. n_training: %d" % (str(net_id), len(dataidxs)))
# move the model to cuda device:
net.to(device)
if args.dataset in libsvm_datasets:
train_ds_local = CustomTensorDataset(torch.tensor(X_train[net_dataidx_map[party_id]].toarray(), dtype=torch.float32),
torch.tensor(y_train[net_dataidx_map[party_id]], dtype=torch.long))
public_ds = CustomTensorDataset(torch.tensor(X_test[:public_data_size].toarray(), dtype=torch.float32),
torch.tensor(y_test[:public_data_size], dtype=torch.long))
remain_test_ds = CustomTensorDataset(torch.tensor(X_test[public_data_size:].toarray(), dtype=torch.float32),
torch.tensor(y_test[public_data_size:], dtype=torch.long))
train_dl_local = data.DataLoader(dataset=train_ds_local, batch_size=args.batch_size, shuffle=True)
test_dl_global = data.DataLoader(dataset=remain_test_ds, batch_size=32, shuffle=False)
else:
train_dl_local, test_dl_local, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32, dataidxs)
train_dl_global, test_dl_global, _, _ = get_dataloader(args.dataset, args.datadir, args.batch_size, 32)
# local_datasets.append((train_dl_local, test_dl_local))
# switch to global test set here
if remain_test_dl is not None: