This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathutils.py
1278 lines (1033 loc) · 57.4 KB
/
utils.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 os
import argparse
import json
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import logging
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data
from itertools import product
import math
import copy
import time
from sklearn.metrics import confusion_matrix
# we've changed to a faster solver
#from scipy.optimize import linear_sum_assignment
import logging
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.init as init
from datasets import MNIST_truncated, CIFAR10_truncated, ImageFolderTruncated, CIFAR10ColorGrayScaleTruncated
from combine_nets import prepare_uniform_weights, prepare_sanity_weights, prepare_weight_matrix, normalize_weights, get_weighted_average_pred
from vgg import *
from model import *
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def mkdirs(dirpath):
try:
os.makedirs(dirpath)
except Exception as _:
pass
def parse_class_dist(net_class_config):
cls_net_map = {}
for net_idx, net_classes in enumerate(net_class_config):
for net_cls in net_classes:
if net_cls not in cls_net_map:
cls_net_map[net_cls] = []
cls_net_map[net_cls].append(net_idx)
return cls_net_map
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
logging.debug('Data statistics: %s' % str(net_cls_counts))
return net_cls_counts
def partition_data(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
X_train, y_train, X_test, y_test = load_mnist_data(datadir)
n_train = X_train.shape[0]
elif dataset == 'cifar10':
X_train, y_train, X_test, y_test = load_cifar10_data(datadir)
n_train = X_train.shape[0]
elif dataset == 'cinic10':
_train_dir = './data/cinic10/cinic-10-trainlarge/train'
cinic_mean = [0.47889522, 0.47227842, 0.43047404]
cinic_std = [0.24205776, 0.23828046, 0.25874835]
trainset = ImageFolderTruncated(_train_dir, transform=transforms.Compose([transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(Variable(x.unsqueeze(0),
requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=cinic_mean,std=cinic_std),
]))
y_train = trainset.get_train_labels
n_train = y_train.shape[0]
if partition == "homo":
idxs = np.random.permutation(n_train)
batch_idxs = np.array_split(idxs, n_nets)
net_dataidx_map = {i: batch_idxs[i] for i in range(n_nets)}
elif partition == "hetero-dir":
min_size = 0
K = 10
N = y_train.shape[0]
net_dataidx_map = {}
while min_size < 10:
idx_batch = [[] for _ in range(n_nets)]
# for each class in the dataset
for k in range(K):
idx_k = np.where(y_train == k)[0]
np.random.shuffle(idx_k)
proportions = np.random.dirichlet(np.repeat(alpha, n_nets))
## Balance
proportions = np.array([p*(len(idx_j)<N/n_nets) for p,idx_j in zip(proportions,idx_batch)])
proportions = proportions/proportions.sum()
proportions = (np.cumsum(proportions)*len(idx_k)).astype(int)[:-1]
idx_batch = [idx_j + idx.tolist() for idx_j,idx in zip(idx_batch,np.split(idx_k,proportions))]
min_size = min([len(idx_j) for idx_j in idx_batch])
for j in range(n_nets):
np.random.shuffle(idx_batch[j])
net_dataidx_map[j] = idx_batch[j]
elif partition == "hetero-fbs":
# in this part we conduct a experimental study on exploring the effect of increasing the number of batches
# but the number of data points are approximately fixed for each batch
# the arguments we need to use here are: `args.partition_step_size`, `args.local_points`, `args.partition_step`(step can be {0, 1, ..., args.partition_step_size - 1}).
# Note that `args.partition` need to be fixed as "hetero-fbs" where fbs means fixed batch size
net_dataidx_map = {}
# stage 1st: homo partition
idxs = np.random.permutation(n_train)
total_num_batches = int(n_train/args.local_points) # e.g. currently we have 180k, we want each local batch has 5k data points the `total_num_batches` becomes 36
step_batch_idxs = np.array_split(idxs, args.partition_step_size)
sub_partition_size = int(total_num_batches / args.partition_step_size) # e.g. for `total_num_batches` at 36 and `args.partition_step_size` at 6, we have `sub_partition_size` at 6
# stage 2nd: hetero partition
n_batches = (args.partition_step + 1) * sub_partition_size
min_size = 0
K = 10
#N = len(step_batch_idxs[args.step])
baseline_indices = np.concatenate([step_batch_idxs[i] for i in range(args.partition_step + 1)])
y_train = y_train[baseline_indices]
N = y_train.shape[0]
while min_size < 10:
idx_batch = [[] for _ in range(n_batches)]
# for each class in the dataset
for k in range(K):
idx_k = np.where(y_train == k)[0]
np.random.shuffle(idx_k)
proportions = np.random.dirichlet(np.repeat(alpha, n_batches))
## Balance
proportions = np.array([p*(len(idx_j)<N/n_batches) for p,idx_j in zip(proportions,idx_batch)])
proportions = proportions/proportions.sum()
proportions = (np.cumsum(proportions)*len(idx_k)).astype(int)[:-1]
idx_batch = [idx_j + idx.tolist() for idx_j,idx in zip(idx_batch,np.split(idx_k,proportions))]
min_size = min([len(idx_j) for idx_j in idx_batch])
# we leave this to the end
for j in range(n_batches):
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 y_train, net_dataidx_map, traindata_cls_counts, baseline_indices
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)
return y_train, net_dataidx_map, traindata_cls_counts
def partition_data_dist_skew(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
entire_gray_scale_indices_train = []
entire_gray_scale_indices_test = []
# we start an adjust version here:
#########################################################################################################################################
# in this setting, we corelate the majority / minory with the class
# i.e. we firstly do an extreme version where we randomly sample 5 out of 10 groups s.t. in those groups there are only grayscale images
# for the other five groups, we leave all images to be colored images
#########################################################################################################################################
grayscale_dominate_classes = np.random.choice(np.arange(10), 5, replace=False)
logger.info("Grayscale image dominated classes are : {}".format(grayscale_dominate_classes))
# we split all grayscale dominate classes to client 0 and all color dominate classes to client1
client0_indices = []
client1_indices = []
for i in range(10):
if i in grayscale_dominate_classes:
logger.info("Grayscale dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
# we fix this to be one first
###
# this is the extreme case, we now change to a relatexed case
###
#num_of_gray_scale_per_class_train = int(1.0 * class_indices_train.shape[0])
num_of_gray_scale_per_class_train = int(0.95 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
client0_indices.append(class_indices_train)
else:
logger.info("Color dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
num_of_gray_scale_per_class_train = int(0.05 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
client1_indices.append(class_indices_train)
entire_gray_scale_indices_train.append(class_gray_scale_indices_train)
entire_gray_scale_indices_train = np.concatenate(entire_gray_scale_indices_train)
client0_indices = np.concatenate(client0_indices)
client1_indices = np.concatenate(client1_indices)
###
# extreme case:
###
for i in range(10):
class_indices_test = np.where(np.array(testset.targets) == i)[0]
# training set contains skewness, but in test set colored and gray-scale images are evenly distributed
num_of_gray_scale_per_class_test = int(0.5 * class_indices_test.shape[0])
class_gray_scale_indices_test = np.random.choice(class_indices_test, num_of_gray_scale_per_class_test, replace=False)
entire_gray_scale_indices_test.append(class_gray_scale_indices_test)
logger.info("Num of gray scale image per class test: {}".format(class_gray_scale_indices_test.shape[0]))
entire_gray_scale_indices_test = np.concatenate(entire_gray_scale_indices_test)
logger.info("Total Num of gray scale image test: {}".format(entire_gray_scale_indices_test.shape[0]))
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
indices_colored = np.array([i for i in idxs if i not in entire_gray_scale_indices_train])
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = client0_indices
net_dataidx_map[1] = client1_indices
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
def partition_data_dist_skew_baseline(dataset, datadir, logdir, partition, n_nets, alpha, args):
'''
This is for one of the baseline we're going to use for rebuttal of ICLR2020
Where the entire training dataset and the entire test dataset are with all grayscale images
'''
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
n_test = testset.data.shape[0]
entire_gray_scale_indices_train = np.arange(n_train)
entire_gray_scale_indices_test = np.arange(n_test)
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
indices_colored = np.array([i for i in idxs if i not in entire_gray_scale_indices_train])
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = np.arange(n_train)
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
#return y_train, entire_gray_scale_indices_train, entire_gray_scale_indices_test
def partition_data_dist_skew_normal(dataset, datadir, logdir, partition, n_nets, alpha, args):
'''
This is for one of the baseline we're going to use for rebuttal of ICLR2020
Where the entire training dataset and the entire test dataset are with all grayscale images
'''
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
n_test = testset.data.shape[0]
entire_gray_scale_indices_train = []
entire_gray_scale_indices_test = np.arange(n_test)
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
indices_colored = np.array([i for i in idxs if i not in entire_gray_scale_indices_train])
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = np.arange(n_train)
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
def partition_data_dist_skew_baseline_balanced(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
entire_gray_scale_indices_train = []
entire_gray_scale_indices_test = []
# we start an adjust version here:
#########################################################################################################################################
# in this setting, we corelate the majority / minory with the class
# i.e. we firstly do an extreme version where we randomly sample 5 out of 10 groups s.t. in those groups there are only grayscale images
# for the other five groups, we leave all images to be colored images
#########################################################################################################################################
grayscale_dominate_classes = np.random.choice(np.arange(10), 5, replace=False)
logger.info("Grayscale image dominated classes are : {}".format(grayscale_dominate_classes))
# we split all grayscale dominate classes to client 0 and all color dominate classes to client1
for i in range(10):
if i in grayscale_dominate_classes:
logger.info("Grayscale dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
# we fix this to be one first
###
# this is the extreme case, we now change to a relatexed case
###
#num_of_gray_scale_per_class_train = int(1.0 * class_indices_train.shape[0])
num_of_gray_scale_per_class_train = int(0.5 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
else:
logger.info("Color dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
num_of_gray_scale_per_class_train = int(0.5 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
entire_gray_scale_indices_train.append(class_gray_scale_indices_train)
entire_gray_scale_indices_train = np.concatenate(entire_gray_scale_indices_train)
####################
# in this test case
####################
for i in range(10):
class_indices_test = np.where(np.array(testset.targets) == i)[0]
# training set contains skewness, but in test set colored and gray-scale images are evenly distributed
num_of_gray_scale_per_class_test = int(0.5 * class_indices_test.shape[0])
class_gray_scale_indices_test = np.random.choice(class_indices_test, num_of_gray_scale_per_class_test, replace=False)
entire_gray_scale_indices_test.append(class_gray_scale_indices_test)
logger.info("Num of gray scale image per class test: {}".format(class_gray_scale_indices_test.shape[0]))
entire_gray_scale_indices_test = np.concatenate(entire_gray_scale_indices_test)
logger.info("Total Num of gray scale image test: {}".format(entire_gray_scale_indices_test.shape[0]))
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
net_dataidx_map[0] = np.arange(n_train)
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
#return y_train, entire_gray_scale_indices_train, entire_gray_scale_indices_test
def partition_data_dist_skew_baseline_oversampled(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
entire_gray_scale_indices_train = []
entire_gray_scale_indices_test = []
# we start an adjust version here:
#########################################################################################################################################
# in this setting, we corelate the majority / minory with the class
# i.e. we firstly do an extreme version where we randomly sample 5 out of 10 groups s.t. in those groups there are only grayscale images
# for the other five groups, we leave all images to be colored images
#########################################################################################################################################
grayscale_dominate_classes = np.random.choice(np.arange(10), 5, replace=False)
logger.info("Grayscale image dominated classes are : {}".format(grayscale_dominate_classes))
# we split all grayscale dominate classes to client 0 and all color dominate classes to client1
entire_indices = []
for i in range(10):
if i in grayscale_dominate_classes:
logger.info("Grayscale dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
# we fix this to be one first
###
# this is the extreme case, we now change to a relatexed case
###
# here we created the dominated images
num_of_gray_scale_per_class_train = int(0.95 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
entire_indices.append(class_indices_train)
# here we need to oversample the underrepresented images
class_color_indices_train = [idx for idx in class_indices_train if idx not in class_gray_scale_indices_train]
logger.info("Length gray scale image train: {}".format(len(class_gray_scale_indices_train)))
logger.info("Length gray scale image test: {}".format(len(class_color_indices_train)))
# we use this way to mitigate the data bias by oversampling
for i in range(int(0.95/0.05)):
entire_indices.append(class_color_indices_train)
else:
logger.info("Color dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
num_of_gray_scale_per_class_train = int(0.05 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
logger.info("Length gray scale image train: {}".format(len(class_gray_scale_indices_train)))
entire_indices.append(class_indices_train)
# we use this way to mitigate the data bias by oversampling
for i in range(int(0.95/0.05)):
entire_indices.append(class_gray_scale_indices_train)
entire_gray_scale_indices_train.append(class_gray_scale_indices_train)
entire_gray_scale_indices_train = np.concatenate(entire_gray_scale_indices_train)
entire_indices = np.concatenate(entire_indices)
logger.info("Entire indices: {}".format(len(entire_indices)))
###
# extreme case:
###
for i in range(10):
class_indices_test = np.where(np.array(testset.targets) == i)[0]
# training set contains skewness, but in test set colored and gray-scale images are evenly distributed
num_of_gray_scale_per_class_test = int(0.5 * class_indices_test.shape[0])
class_gray_scale_indices_test = np.random.choice(class_indices_test, num_of_gray_scale_per_class_test, replace=False)
entire_gray_scale_indices_test.append(class_gray_scale_indices_test)
logger.info("Num of gray scale image per class test: {}".format(class_gray_scale_indices_test.shape[0]))
entire_gray_scale_indices_test = np.concatenate(entire_gray_scale_indices_test)
logger.info("Total Num of gray scale image test: {}".format(entire_gray_scale_indices_test.shape[0]))
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
indices_colored = np.array([i for i in idxs if i not in entire_gray_scale_indices_train])
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = entire_indices
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
#return y_train, net_dataidx_map, entire_gray_scale_indices_train, entire_gray_scale_indices_test
def partition_data_viz(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
# we start an adjust version here:
###############################################################################################
# Our strategy is like the following:
# we split the data of CIFAR=10 dataset to two different clients
# and those two clients only share on common class
###############################################################################################
# the class 5 (i.e. dog) is shared across the two clients
#classes_client1 = [class_index for class_index in range(0, 7)]
#classes_client2 = [class_index for class_index in range(2, 10)]
#classes_client1 = [0, 1]
#classes_client2 = [8, 9]
classes_client1 = [0, 1, 2, 3]
classes_client2 = [6, 7, 8, 9]
# we split all grayscale dominate classes to client 0 and all color dominate classes to client1
client0_indices = []
client1_indices = []
for ci in range(10):
class_indices_train = np.where(np.array(training_set.targets) == ci)[0]
#logger.info("############# class index: {}, class_indices: {}".format(ci, class_indices_train))
if ci in classes_client1:
logger.info("Client 1 exclusive classes: {}".format(ci))
client0_indices.append(class_indices_train)
elif ci in classes_client2:
logger.info("Client 2 exclusive classes: {}".format(ci))
client1_indices.append(class_indices_train)
else:
# here we handel the shared class
num_of_dp_per_client = int(0.5 * class_indices_train.shape[0])
shared_class_indices_client0 = np.random.choice(class_indices_train, num_of_dp_per_client, replace=False)
shared_class_indices_client1 = [idx for idx in class_indices_train if idx not in shared_class_indices_client0]
client0_indices.append(shared_class_indices_client0)
client1_indices.append(shared_class_indices_client1)
logger.info("shared_class_indices_client0: {}, length: {}, shared_class_indices_client1: {}, length: {}".format(
shared_class_indices_client0, len(shared_class_indices_client0), shared_class_indices_client1, len(shared_class_indices_client1)))
client0_indices = np.concatenate(client0_indices)
client1_indices = np.concatenate(client1_indices)
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = client0_indices
net_dataidx_map[1] = client1_indices
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts
def partition_data_viz2(dataset, datadir, logdir, partition, n_nets, alpha, args):
if dataset == 'mnist':
pass
elif dataset == 'cifar10':
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(
Variable(x.unsqueeze(0), requires_grad=False),
(4,4,4,4),mode='reflect').data.squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# data prep for test set
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize])
# load training and test set here:
training_set = torchvision.datasets.CIFAR10(root='./data/cifar10', train=True,
download=True, transform=None)
testset = torchvision.datasets.CIFAR10(root='./data/cifar10', train=False,
download=True, transform=None)
y_train = np.array(copy.deepcopy(training_set.targets))
n_train = training_set.data.shape[0]
entire_gray_scale_indices_train = []
entire_gray_scale_indices_test = []
# we start an adjust version here:
###############################################################################################
# in this setting, we corelate the majority / minory with the class
# i.e. we firstly do an extreme version where we randomly sample 5 out of 10 groups
# s.t. in those groups there are only grayscale images
# for the other five groups, we leave all images to be colored images
###############################################################################################
#grayscale_dominate_classes = np.random.choice(np.arange(10), 5, replace=False)
grayscale_dominate_classes = np.arange(0, 6)
logger.info("Grayscale image dominated classes are : {}".format(grayscale_dominate_classes))
# we split all grayscale dominate classes to client 0 and all color dominate classes to client1
client0_indices = []
client1_indices = []
for i in range(10):
if i in grayscale_dominate_classes:
logger.info("Grayscale dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
# we fix this to be one first
###
# this is the extreme case, we now change to a relatexed case
###
num_of_gray_scale_per_class_train = int(1.0 * class_indices_train.shape[0])
#num_of_gray_scale_per_class_train = int(0.95 * class_indices_train.shape[0])
class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
client0_indices.append(class_indices_train)
entire_gray_scale_indices_train.append(class_gray_scale_indices_train)
else:
logger.info("Color dominate class index: {}".format(i))
class_indices_train = np.where(np.array(training_set.targets) == i)[0]
#num_of_gray_scale_per_class_train = int(0.05 * class_indices_train.shape[0])
num_of_gray_scale_per_class_train = int(0.0 * class_indices_train.shape[0])
#class_gray_scale_indices_train = np.random.choice(class_indices_train, num_of_gray_scale_per_class_train, replace=False)
client1_indices.append(class_indices_train)
#entire_gray_scale_indices_train.append(class_gray_scale_indices_train)
entire_gray_scale_indices_train = np.concatenate(entire_gray_scale_indices_train)
client0_indices = np.concatenate(client0_indices)
client1_indices = np.concatenate(client1_indices)
###
# extreme case:
###
for i in range(10):
class_indices_test = np.where(np.array(testset.targets) == i)[0]
# training set contains skewness, but in test set colored and gray-scale images are evenly distributed
num_of_gray_scale_per_class_test = int(0.5 * class_indices_test.shape[0])
class_gray_scale_indices_test = np.random.choice(class_indices_test, num_of_gray_scale_per_class_test, replace=False)
entire_gray_scale_indices_test.append(class_gray_scale_indices_test)
logger.info("Num of gray scale image per class test: {}".format(class_gray_scale_indices_test.shape[0]))
entire_gray_scale_indices_test = np.concatenate(entire_gray_scale_indices_test)
logger.info("Total Num of gray scale image test: {}".format(entire_gray_scale_indices_test.shape[0]))
elif dataset == 'cinic10':
pass
if partition == "homo":
net_dataidx_map = {}
idxs = np.arange(n_train)
indices_colored = np.array([i for i in idxs if i not in entire_gray_scale_indices_train])
# we split grayscale and colored images on two workers entirely
net_dataidx_map[0] = client0_indices
net_dataidx_map[1] = client1_indices
elif partition == "hetero-dir":
pass
elif partition == "hetero-fbs":
pass
traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map, logdir)
return y_train, net_dataidx_map, traindata_cls_counts, entire_gray_scale_indices_train, entire_gray_scale_indices_test
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_cifar10_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
cifar10_train_ds = CIFAR10_truncated(datadir, train=True, download=True, transform=transform)
cifar10_test_ds = CIFAR10_truncated(datadir, train=False, download=True, transform=transform)
X_train, y_train = cifar10_train_ds.data, cifar10_train_ds.target
X_test, y_test = cifar10_test_ds.data, cifar10_test_ds.target
return (X_train, y_train, X_test, y_test)
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 init_cnns(net_configs, n_nets):
'''
Initialize the local CNNs
Please note that this part is hard coded right now
'''
input_size = (16 * 5 * 5) # hard coded, defined by the SimpleCNN useds
output_size = net_configs[-1] #
hidden_sizes = [120, 84]
cnns = {net_i: None for net_i in range(n_nets)}
# we add this book keeping to store meta data of model weights
model_meta_data = []
layer_type = []
for cnn_i in range(n_nets):
cnn = SimpleCNN(input_size, hidden_sizes, output_size)
cnns[cnn_i] = cnn
for (k, v) in cnns[0].state_dict().items():
model_meta_data.append(v.shape)
layer_type.append(k)
#logger.info("Layer name: {}, layer shape: {}".format(k, v.shape))
return cnns, model_meta_data, layer_type
def init_models(net_configs, n_nets, args):
'''
Initialize the local LeNets
Please note that this part is hard coded right now
'''
cnns = {net_i: None for net_i in range(n_nets)}
# we add this book keeping to store meta data of model weights
model_meta_data = []
layer_type = []
for cnn_i in range(n_nets):
if args.model == "lenet":
cnn = LeNet()
elif args.model == "vgg":
cnn = vgg11()
elif args.model == "simple-cnn":
if args.dataset in ("cifar10", "cinic10"):
cnn = SimpleCNN(input_dim=(16 * 5 * 5), hidden_dims=[120, 84], output_dim=10)
elif args.dataset == "mnist":
cnn = SimpleCNNMNIST(input_dim=(16 * 4 * 4), hidden_dims=[120, 84], output_dim=10)
elif args.model == "moderate-cnn":
if args.dataset == "mnist":
cnn = ModerateCNNMNIST()
elif args.dataset in ("cifar10", "cinic10"):
cnn = ModerateCNN()
cnns[cnn_i] = cnn
for (k, v) in cnns[0].state_dict().items():
model_meta_data.append(v.shape)
layer_type.append(k)
#logger.info("{} ::: Layer name: {}, layer shape: {}".format(args.model, k, v.shape))
return cnns, model_meta_data, layer_type
def save_model(model, model_index):
logger.info("saving local model-{}".format(model_index))
with open("trained_local_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 save_model_dist_skew(model, model_index):
logger.info("saving local model-{} dist skew".format(model_index))
with open("trained_local_model_dist_skew"+str(model_index), "wb") as f_:
torch.save(model.state_dict(), f_)
return
def load_model_dist_skew(model, model_index, device="cpu"):
logger.info("loading local model-{} dist skew".format(model_index))
with open("trained_local_model_dist_skew"+str(model_index), "rb") as f_:
model.load_state_dict(torch.load(f_))
model.to(device)
return model
def save_model_viz(model, model_index):
logger.info("saving local model-{} visulization".format(model_index))
with open("trained_local_model_viz{}_new".format(model_index), "wb") as f_:
torch.save(model.state_dict(), f_)
return
def load_model_viz(model, model_index, device="cpu"):
logger.info("loading local model-{} visulization".format(model_index))
with open("trained_local_model_viz"+str(model_index), "rb") as f_:
model.load_state_dict(torch.load(f_))
model.to(device)
return model
def get_dataloader(dataset, datadir, train_bs, test_bs, dataidxs=None):
if dataset in ('mnist', 'cifar10'):
if dataset == 'mnist':
dl_obj = MNIST_truncated
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
elif dataset == 'cifar10':
dl_obj = CIFAR10_truncated
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_train = transforms.Compose([