-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils_v1.py
1148 lines (972 loc) · 46.2 KB
/
utils_v1.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
from torchvision import datasets, transforms
import math
import random
import torch
import copy
import csv
from datetime import datetime
import os
import numpy as np
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
from torch import nn
import functools
import operator
import transform as T
import json
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from scipy import io
import torch
class Utils():
def target_transform(target):
return int(target) - 1
def get_dataset_dist(self, args):
if args.dataset == "cifar10":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
train_dataset = datasets.CIFAR10(
root=data_dir,
train=True,
download=True,
transform=transform
)
test_dataset = datasets.CIFAR10(
root=data_dir,
train=False,
download=True,
transform=transform
)
if args.dataset == "svhn":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = datasets.SVHN(
root=data_dir,
split='train',
download=True,
transform=transform
)
test_dataset = datasets.SVHN(
root=data_dir,
split='test',
download=True,
transform=transform
)
if args.dataset == "emnist":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = datasets.EMNIST(root='./data/',
train=True,
transform=transform,split='balanced', ##byclass
download=True)
test_dataset = datasets.EMNIST(root='./data/',
train=False,split='balanced',
transform=transform)
if args.dataset == "cifar10":
if args.iid:
user_idxs,server_idxs = self.iid_dist(train_dataset, args)
# user_idxs,server_idxs = self.iid_dist_random(train_dataset,args)
else:
# user_idxs,server_idxs = self.noniid_dist(train_dataset, args)
# user_idxs,server_idxs = self.noniid_dist_2(train_dataset, args)
# user_idxs,server_idxs = self.non_iid_dist_random(train_dataset, args)
user_idxs,server_idxs = self.getNonIIDdata(train_dataset, args)
if args.dataset == "svhn":
if args.iid:
user_idxs,server_idxs = self.iid_dist_svhn(train_dataset, args)
# user_idxs,server_idxs = self.iid_dist_random(train_dataset,args)
else:
# user_idxs,server_idxs = self.noniid_dist(train_dataset, args)
# user_idxs,server_idxs = self.noniid_dist_2(train_dataset, args)
# user_idxs,server_idxs = self.non_iid_dist_random(train_dataset, args)
user_idxs,server_idxs = self.getNonIIDdata_svhn(train_dataset, args)
if args.dataset == "emnist":
if args.iid:
user_idxs,server_idxs = self.iid_dist_emnist(train_dataset, args)
# user_idxs,server_idxs = self.iid_dist_random(train_dataset,args)
else:
# user_idxs,server_idxs = self.noniid_dist(train_dataset, args)
# user_idxs,server_idxs = self.noniid_dist_2(train_dataset, args)
# user_idxs,server_idxs = self.non_iid_dist_random(train_dataset, args)
# user_idxs,server_idxs = self.getNonIIDdata_emnist(train_dataset, args)
if args.attack:
user_idxs, server_idxs, attack_idxs = self.getNonIIDdata_emnist_with_attacker(train_dataset, args)
else:
user_idxs,server_idxs = self.getNonIIDdata_emnist(train_dataset, args)
if args.attack:
return train_dataset, test_dataset, user_idxs, server_idxs, attack_idxs
else:
return train_dataset, test_dataset, user_idxs, server_idxs
def iid_dist(self, dataset, args):
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices# args.max_data_per_device
num_sample_of_server = len(dataset) - args.num_devices*data_per_device
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
return users_idxs,server_idxs
def iid_dist_svhn(self, dataset, args):
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices# args.max_data_per_device
num_sample_of_server = len(dataset) - args.num_devices*data_per_device
num_sample_of_each_class_server = int(num_sample_of_server/10)
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(10):
idxs_target_class = np.where(np.array(dataset.labels)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
return users_idxs,server_idxs
def iid_dist_emnist(self, dataset, args):
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices# args.max_data_per_device
print('data_per_device',data_per_device)
num_class = 47
num_sample_of_server = len(dataset) - args.num_devices*data_per_device
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
return users_idxs,server_idxs
def getNonIIDdata_emnist(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
labelList = labelList.cpu().numpy()#[0:50000]
num_class = 47
Total_labelList = data.targets
Total_labelList = Total_labelList.cpu().numpy()#[0:50000]
print(labelList.shape)
num_sample_of_server = args.num_data_server#4000#len(data) - args.num_devices*args.max_data_per_device
######
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
idx_target_class_list = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(labelList)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
np.random.shuffle(server_idxs)
######
# labelList = rest_idxs
rng = Random()
rng.seed(2020)
a = []
b = []
devices_labelid = []
for id in range(len(Total_labelList)):
if id not in server_idxs:
a.append((labelList[id], id))
b.append(labelList[id])
devices_labelid.append(id)
### sampels probility
sample_probility_ = []
for id in range(num_class):
index = np.where(np.array(b)==id)[0]
index = list(index)
sample_probility_.append(len(index))
sample_probility = np.array(sample_probility_)/np.sum(sample_probility_)
print(sample_probility)
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
# sizes = number of nodes
# sizes = args.num_devices
base_size = args.num_devices
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
# interval += 1
# print('requiredLabelList',requiredLabelList)
for labelIdx in requiredLabelList:
idxIncrement = int(sample_probility_[labelIdx]*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelIdx][0:idxIncrement])
labelIdxDict[labelIdx][0:idxIncrement] = []
#random part
remainLabels = list()
# for labelIdx in range(labelNum):
# remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelIdx])
# print(Total_labelList[remainLabels])
# yuyuyu
remainLabels_class = []
for target_class in range(num_class):
tmp = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
remainLabels_class.append(len(tmp))
print(np.sum(remainLabels_class))
print(remainLabels_class)
# rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
for target_class in range(num_class):
idxs_target_class = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
num_sample_of_each_class = int(remainLabels_class[partPointer]*sample_probility[target_class])
remainLabels_array = np.array(remainLabels)
partitions[partPointer].extend(remainLabels_array[idxs_target_class[0:num_sample_of_each_class]].tolist())
remainLabels = np.delete(np.array(remainLabels), idxs_target_class[0:num_sample_of_each_class]).tolist()
rng.shuffle(partitions[partPointer])
return partitions, server_idxs
def getNonIIDdata_emnist_with_attacker(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
labelList = labelList.cpu().numpy()#[0:50000]
num_class = 47
Total_labelList = data.targets
Total_labelList = Total_labelList.cpu().numpy()#[0:50000]
print(labelList.shape)
num_sample_of_server = args.num_data_server#4000#len(data) - args.num_devices*args.max_data_per_device
######
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
idx_target_class_list = []
attacker_idxs = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(labelList)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
attacker_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:num_sample_of_each_class_server+args.attack_num_data//num_class]
np.random.shuffle(server_idxs)
np.random.shuffle(attacker_idxs)
used_idx = server_idxs + attacker_idxs
######
# labelList = rest_idxs
rng = Random()
rng.seed(2020)
a = []
b = []
devices_labelid = []
for id in range(len(Total_labelList)):
if id not in used_idx:
a.append((labelList[id], id))
b.append(labelList[id])
devices_labelid.append(id)
### sampels probility
sample_probility_ = []
for id in range(num_class):
index = np.where(np.array(b)==id)[0]
index = list(index)
sample_probility_.append(len(index))
sample_probility = np.array(sample_probility_)/np.sum(sample_probility_)
print(sample_probility)
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
# sizes = number of nodes
# sizes = args.num_devices
base_size = 47#args.num_devices
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
# interval += 1
# print('requiredLabelList',requiredLabelList)
for labelIdx in requiredLabelList:
idxIncrement = int(sample_probility_[labelIdx]*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelIdx][0:idxIncrement])
labelIdxDict[labelIdx][0:idxIncrement] = []
#random part
remainLabels = list()
# for labelIdx in range(labelNum):
# remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelIdx])
# print(Total_labelList[remainLabels])
# yuyuyu
remainLabels_class = []
for target_class in range(num_class):
tmp = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
remainLabels_class.append(len(tmp))
print(np.sum(remainLabels_class))
print(remainLabels_class)
# rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
for target_class in range(num_class):
idxs_target_class = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
num_sample_of_each_class = int(remainLabels_class[partPointer]*sample_probility[target_class])
remainLabels_array = np.array(remainLabels)
partitions[partPointer].extend(remainLabels_array[idxs_target_class[0:num_sample_of_each_class]].tolist())
remainLabels = np.delete(np.array(remainLabels), idxs_target_class[0:num_sample_of_each_class]).tolist()
rng.shuffle(partitions[partPointer])
return partitions, server_idxs, attacker_idxs
def non_iid_dist_random(self, dataset, args):
### Number of samples the server has
num_sample_of_server = len(dataset) - args.num_devices*args.max_data_per_device
import itertools
all_class = np.arange(len(dataset.classes)).tolist()
### Produce all possible combinations of users' class
all_combination = list(itertools.combinations(all_class,args.class_per_device))
np.random.shuffle(all_combination) ### Shuffle the order of these combinations
idx_target_class_list = []
### Divide the samples of each class equally for the server
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs = []
rest_idxs = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs.append(idx_target_class_list[target_class][num_sample_of_each_class_server:])
users_idxs = [[] for i in range(args.num_devices)]
### distribute sample of each class to users
for user_id in range(args.num_devices):
if user_id>=len(all_combination):
combination_id = user_id%len(all_combination)
else:
combination_id = user_id
user_class = all_combination[combination_id]
user_idxs_tmp = []
for user_class_i in list(user_class):
np.random.shuffle(rest_idxs[user_class_i])
user_idxs_tmp += rest_idxs[user_class_i][0:int(args.max_data_per_device/args.class_per_device)]
users_idxs[user_id] = user_idxs_tmp
return users_idxs,server_idxs
def getNonIIDdata(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
num_sample_of_server = args.num_data_server#4000#len(data) - args.num_devices*args.max_data_per_device
######
num_sample_of_each_class_server = int(num_sample_of_server/len(data.classes))
server_idxs=[]
idx_target_class_list = []
for target_class in range(len(data.classes)):
idxs_target_class = np.where(np.array(data.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
######
# labelList = rest_idxs
rng = Random()
rng.seed(2020)
# a = [(label, idx) for idx, label in enumerate(labelList)]
a = []
for id in range(len(data)):
if id not in server_idxs:
a.append((labelList[id], id))
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
# sizes = number of nodes
# sizes = args.num_devices
base_size = 10
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
# interval += 1
for labelIdx in requiredLabelList:
# print(len(labelIdxPointer), labelIdx)
start = labelIdxPointer[labelIdx]
idxIncrement = int(eachPartitionLen*basicLabelRatio)#int(basicLabelRatio*len(labelIdxDict[labelNameList[labelIdx]]))
# print(eachPartitionLen, int(eachPartitionLen*basicLabelRatio), idxIncrement, len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement]))
partitions[partPointer].extend(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
length_tmp = len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
tmp = np.arange(start).tolist()
random.shuffle(tmp)
index_tmp = np.array(labelIdxDict[labelNameList[labelIdx]])
if length_tmp < idxIncrement:
partitions[partPointer].extend(index_tmp[tmp[0:idxIncrement-length_tmp]].tolist())
labelIdxPointer[labelIdx] += idxIncrement
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
# print(eachPartitionLen)
idxIncrement = eachPartitionLen - len(partitions[partPointer])
# print(idxIncrement)
partitions[partPointer].extend(remainLabels[:idxIncrement])
rng.shuffle(partitions[partPointer])
remainLabels = remainLabels[idxIncrement:]
if args.num_devices == 20:
partitions_list = [list() for i in range(20)]
for partPointer in range(10):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
partitions_list[partPointer] = index_partitions[0:len_partitions//2]
partitions_list[partPointer+10] = index_partitions[len_partitions//2:]
partitions = partitions_list
if args.num_devices == 30:
partitions_list = [list() for i in range(30)]
for partPointer in range(10):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
partitions_list[partPointer] = index_partitions[0:len_partitions//3]
partitions_list[partPointer+10] = index_partitions[len_partitions//3:len_partitions*2//3]
partitions_list[partPointer+20] = index_partitions[len_partitions*2//3:]
partitions = partitions_list
# server_idxs = list(set(all_index).difference(set(a)))
return partitions,server_idxs
def getNonIIDdata_svhn(self, data, args):
from random import Random
from math import ceil
labelList = copy.deepcopy(data.labels) - 1
num_sample_of_server = args.num_data_server#4000#len(data) - args.num_devices*args.max_data_per_device
server_idxs = np.arange(0,num_sample_of_server).tolist()
######
num_sample_of_each_class_server = int(num_sample_of_server/10)
server_idxs=[]
idx_target_class_list = []
for target_class in range(10):
idxs_target_class = np.where(np.array(data.labels)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
######
# labelList = rest_idxs
rng = Random()
rng.seed(2020)
# a = [(label, idx) for idx, label in enumerate(labelList)]
a = []
for id in range(len(data)):
if id not in server_idxs:
a.append((labelList[id], id))
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
# sizes = number of nodes
sizes = args.num_devices
partitions = [list() for i in range(sizes)]
eachPartitionLen= int(len(a)/sizes)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
# interval += 1
for labelIdx in requiredLabelList:
# print(len(labelIdxPointer), labelIdx)
start = labelIdxPointer[labelIdx]
idxIncrement = int(eachPartitionLen*basicLabelRatio)#int(basicLabelRatio*len(labelIdxDict[labelNameList[labelIdx]]))
# print(eachPartitionLen, int(eachPartitionLen*basicLabelRatio), idxIncrement, len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement]))
partitions[partPointer].extend(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
length_tmp = len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
tmp = np.arange(start).tolist()
#random.shuffle(tmp)
index_tmp = np.array(labelIdxDict[labelNameList[labelIdx]])
if length_tmp < idxIncrement:
partitions[partPointer].extend(index_tmp[tmp[0:idxIncrement-length_tmp]].tolist())
labelIdxPointer[labelIdx] += idxIncrement
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
# print(eachPartitionLen)
idxIncrement = eachPartitionLen - len(partitions[partPointer])
# print(idxIncrement)
partitions[partPointer].extend(remainLabels[:idxIncrement])
rng.shuffle(partitions[partPointer])
remainLabels = remainLabels[idxIncrement:]
# server_idxs = list(set(all_index).difference(set(a)))
return partitions,server_idxs
def Generate_device_server_index(args, path_device_idxs):
utils = Utils()
if args.attack:
train_dataset, test_dataset, device_idxs, server_idxs, attacker_idxs = utils.get_dataset_dist(args)
dictionary1 = {'attacker_idxs':attacker_idxs}
np.save(path_device_idxs+"attacker_idxs.npy", dictionary1)
# print('attacker_idxs:',attacker_idxs)
else:
train_dataset, test_dataset, device_idxs, server_idxs = utils.get_dataset_dist(args) ##### generate the data indexes of the users and the server
dictionary1 = {'device_idxs':device_idxs}
np.save(path_device_idxs+"device_idxs.npy", dictionary1)
dictionary2 = {'server_idxs':server_idxs}
np.save(path_device_idxs+"server_idxs.npy", dictionary2)
def Load_device_server_index(args, path_device_idxs):
#### load data index of the users and the server
device_ids = np.load(path_device_idxs + 'device_idxs' + '.npy', allow_pickle=True).item()
server_idxs = np.load(path_device_idxs + 'server_idxs' + '.npy', allow_pickle=True).item()
device_ids = device_ids['device_idxs']
server_idxs = server_idxs['server_idxs']
if args.attack:
attacker_idxs = np.load(path_device_idxs + 'attacker_idxs' + '.npy', allow_pickle=True).item()
attacker_idxs = attacker_idxs['attacker_idxs']
return server_idxs, device_ids, attacker_idxs
else:
return server_idxs, device_ids
def Generate_communicate_user_list(args, path_device_idxs):
ue_list_epoch = [[]]*args.epoch
iterations_epoch = args.k_img//args.bs
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue+1),dtype='int32')
if args.num_comm_ue <= args.size - 1:
# ue_list = np.arange(1, args.size).tolist()
# connected_user_list = random.sample(ue_list,args.num_comm_ue)
for e in range(args.epoch):
for it in range(iterations_epoch):
ue_list = np.arange(1, args.size).tolist()
connected_user_list = random.sample(ue_list, args.num_comm_ue)
ue_list = np.arange(1, args.size).tolist()
random.shuffle(ue_list)
ue_list = [0] + connected_user_list
ue_list.sort()
ue_list = np.array(ue_list, dtype='int32')
ue_list_epoch[e,it,0:len(ue_list)] = ue_list
ue_list_epoch = np.array(ue_list_epoch, dtype='int32')
io.savemat(path_device_idxs+'ue_list_epoch.mat', {'ue_list_epoch': ue_list_epoch})
dictionary1 = {'ue_list_epoch':ue_list_epoch.tolist()}
np.save(path_device_idxs + "ue_list_epoch.npy", dictionary1)
def Load_communicate_user_list(args, path_device_idxs):
if args.num_comm_ue <= args.size - 1:
ue_list_epoches = np.load(path_device_idxs + 'ue_list_epoch' + '.npy', allow_pickle=True).item()
ue_list_epoches = ue_list_epoches['ue_list_epoch']
else:
ue_list_epoches = []
return ue_list_epoches
def Generate_Train_data_loader(args, labeled_dataset, unlabeled_dataset, train_sampler, attack_dataset=None):
Train_data_loader = []
if args.attack:
for rank in range(args.size):
Data_Loader = Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler, attack_dataset)
Train_data_loader.append(Data_Loader)
else:
for rank in range(args.size):
Data_Loader = Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler)
Train_data_loader.append(Data_Loader)
return Train_data_loader
def Generate_Test_data_loader(args, test_dataset, base_dataset, device_ids):
Test_data_loader = []
for rank in range(args.size):
Data_Loader = Assign_Test_data_loader(args, rank, test_dataset, base_dataset, device_ids)
Test_data_loader.append(Data_Loader)
return Test_data_loader
def Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler, attack_dataset=None):
if attack_dataset is not None:
if rank > 0 and rank < args.size-1:
unlabeled_trainloader = DataLoader(
unlabeled_dataset[rank-1],
# sampler=train_sampler(unlabeled_dataset[rank-1]),
batch_size=args.bs,
num_workers=8,
shuffle = True,
drop_last=True)
return unlabeled_trainloader
else:
if rank == 0:
labeled_trainloader = DataLoader(
labeled_dataset,
# sampler=train_sampler(labeled_dataset),
shuffle = True,
batch_size=args.bs,
num_workers=8,
drop_last=True)
return labeled_trainloader
else:
attack_trainloader = DataLoader(
attack_dataset,
# sampler=train_sampler(labeled_dataset),
shuffle = True,
batch_size=args.bs,
num_workers=8,
drop_last=True)
return attack_trainloader
else:
if rank > 0:
unlabeled_trainloader = DataLoader(
unlabeled_dataset[rank-1],
# sampler=train_sampler(unlabeled_dataset[rank-1]),
batch_size=args.bs,
num_workers=8,
shuffle = True,
drop_last=True)
return unlabeled_trainloader
else:
labeled_trainloader = DataLoader(
labeled_dataset,
# sampler=train_sampler(labeled_dataset),
shuffle = True,
batch_size=args.bs,
num_workers=8,
drop_last=True)
return labeled_trainloader
def Assign_Test_data_loader(args, rank, test_dataset, base_dataset, device_ids):
Server_test_loader = DataLoader(test_dataset,
batch_size=args.bs,
shuffle=False)
### generate test loader for users
targets = base_dataset.targets
# print(len(set(targets)))
if args.dataset == 'cifar10':
num_calss = 10
if args.dataset == 'emnist':
num_calss = 47
# ALLusers_test_index = []
probability_all = []
if rank > 0 and rank != args.size - args.attack:
num = rank - 1
user_targets = np.array(targets)[device_ids[num]]
num_each_class=[]
for i in range(num_calss):
num_class_i = np.where(user_targets==i)
num_each_class.append(num_class_i[0].shape[0])
probability_all.append(num_each_class/np.sum(num_each_class))
user_test_idxs=[]
idx_target_class_list = []
for target_class in range(num_calss):
idxs_target_class = np.where(np.array(test_dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
# num_sample_of_each_class_server = int(num_each_class[target_class]/np.sum(num_each_class)*len(test_dataset.targets))
num_sample_of_each_class_server = int(probability_all[0][target_class]*len(idxs_target_class))
### distribute sample of each class to the server
user_test_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
test_user_sampler = torch.utils.data.sampler.SubsetRandomSampler(user_test_idxs)
User_test_loader = torch.utils.data.DataLoader(dataset=test_dataset,sampler=test_user_sampler,num_workers=2,
batch_size=args.bs)
if rank > 0 and rank != args.size - args.attack:
return User_test_loader
else:
return Server_test_loader
def Save_acc_file(args, rank, prefix=None, acc_list=None):
filename = "./results_v0/%s_Rank%s_%s_%s_iid%s_UE%s_%s_comUE%s_%s_bs%s_cp%s.txt" %(prefix, rank, args.experiment_name, args.dataset, args.iid,
args.size - 1, args.basicLabelRatio,
args.num_comm_ue, args.model, args.bs, args.cp)
if filename:
with open(filename, 'w') as f:
json.dump(acc_list, f)
def Save_model(experiment_name, model, rank, epoch):
path_checkpoint = "./checkpoint/%s/" %(experiment_name)
if not os.path.exists(path_checkpoint):
os.makedirs(path_checkpoint)
if rank == 0:
torch.save(model.state_dict(), path_checkpoint+'Rank%s_Epoch_%s_weights.pth' %(rank, epoch))
def Load_model_weights(experiment_name, epoch):
path_checkpoint = './checkpoint/%s/' %(experiment_name)
pthfile = path_checkpoint+'Rank0_Epoch_%s_weights.pth' %(epoch)
checkpoint_weights = torch.load(pthfile)
return checkpoint_weights
def Assign_ranks_to_threads(args):
User_list = np.arange(args.num_comm_ue).tolist()#[i for i in args.num_comm_ue]
increase_tmp = (args.size - 1)//len(User_list)
ranks_list = np.arange(0, args.size - 1).tolist()
rank_group = []
for rank_id in range(len(User_list)):
if rank_id == len(User_list)-1:
ranks = ranks_list[rank_id*increase_tmp:]
else:
ranks = ranks_list[rank_id*increase_tmp:(rank_id+1)*increase_tmp]
rank_group.append(ranks)
return rank_group
def Test_each_model_with_FedAvg_weights(args, user_group, model, test_loader_list):
for n in range(len(user_group)):
Users_acc = []
Users_acc1 = []
Users_acc2 = []
for i in range(args.epoch):
checkpoint_weights = Load_model_weights(args.experiment_name, i)
model.load_state_dict(checkpoint_weights)
if args.attack:
acc1, acc2 = test_with_attack(args, model, test_loader_list[user_group[n] + 1])
Users_acc1.append(round(acc1*100.0,2))
Users_acc2.append(round(acc2*100.0,2))
else:
acc = test(model, test_loader_list[user_group[n] + 1])
Users_acc.append(round(acc*100.0,2))
if args.attack:
Save_acc_file(args, user_group[n] + 1, prefix=f'FedAvg_benign_attack{args.attack}_{args.attack_class}_{args.attack_target}', acc_list=Users_acc1)
Save_acc_file(args, user_group[n] + 1, prefix=f'FedAvg_attack{args.attack}_{args.attack_class}_{args.attack_target}', acc_list=Users_acc2)
else:
Save_acc_file(args, user_group[n] + 1, prefix='FedAvg', acc_list=Users_acc)
class Sampler(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = idxs
def __getitem__(self, idx):
return self.dataset[self.idxs[idx]]
def __len__(self):
return len(self.idxs)
class Sampler_no_target(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = idxs
def __getitem__(self, idx):
return self.dataset[self.idxs[idx]][0]
def __len__(self):
return len(self.idxs)
class Sampler_distill(Dataset):
def __init__(self, dataset):
self.dataset = dataset
self.trans = T.Compose([
T.ToTensor(),
])
def __getitem__(self, idx):
# tensor2np = self.dataset[idx][0].cpu().numpy()
np2tensor = self.trans(self.dataset[idx][0])
# print('size',np2tensor.size())
# np2tensor = torch.from_numpy(tensor2np)
# np2tensor = self.dataset[idx][0]
return (np2tensor, self.dataset[idx][1])
def __len__(self):
return len(self.dataset)
def fed_avg(weights):
w = copy.deepcopy(weights[0]) # Weight from first device
for key in w.keys():
for i in range(1, len(weights)): # Other devices
w[key] += weights[i][key] # Sum up weights
w[key] = torch.div(w[key], len(weights)) # Get average weights
return w
def fed_weight_avg(weights,user_weight):
w = copy.deepcopy(weights[0]) # Weight from first device
for key in w.keys():
w[key] = torch.div(w[key], 1/user_weight[0])
for key in w.keys():
for i in range(1, len(weights)): # Other devices
w[key] += torch.div( weights[i][key], 1/user_weight[i])
return w
def weight_diff(weights, layer_name):
w_1 = copy.deepcopy(weights[0]) # Weight from first device
w_2 = copy.deepcopy(weights[0])
w_avg = copy.deepcopy(weights[-1])
layer_name_1 = layer_name + '.weight'
layer_name_2 = layer_name + '.bias'
for i in range(len(weights)-1):
for key in w_1.keys():