-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmodel.py
executable file
·1918 lines (1647 loc) · 84.9 KB
/
model.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 __future__ import division
import os
import time
import math
from glob import glob
import tensorflow as tf
import numpy as np
from six.moves import xrange
import json
import sys
from keras.datasets import cifar10
from ops import *
from utils import *
from rdp_utils import *
from pate_core import *
import pickle
from keras.utils import np_utils
# import pandas as pd
import torch
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
import scipy
from dp_pca import ComputeDPPrincipalProjection
from sklearn.random_projection import GaussianRandomProjection
from utils import pp, visualize, to_json, show_all_variables, mkdir
from gen_data import batch2str
from PIL import Image
def partition_dataset(data, labels, nb_teachers, teacher_id):
"""
Simple partitioning algorithm that returns the right portion of the data
needed by a given teacher out of a certain nb of teachers
:param data: input data to be partitioned
:param labels: output data to be partitioned
:param nb_teachers: number of teachers in the ensemble (affects size of each
partition)
:param teacher_id: id of partition to retrieve
:return:
"""
# Sanity check
assert (int(teacher_id) < int(nb_teachers))
# This will floor the possible number of batches
batch_len = int(len(data) / nb_teachers)
# Compute start, end indices of partition
start = teacher_id * batch_len
end = (teacher_id + 1) * batch_len
# Slice partition off
partition_data = data[start:end]
if labels is not None:
partition_labels = labels[start:end]
else:
partition_labels = None
return partition_data, partition_labels
def evenly_partition_dataset(data, labels, nb_teachers):
"""
Simple partitioning algorithm that returns the right portion of the data
needed by a given teacher out of a certain nb of teachers
:param data: input data to be partitioned
:param labels: output data to be partitioned
:param nb_teachers: number of teachers in the ensemble (affects size of each
partition)
:param teacher_id: id of partition to retrieve
:return:
"""
# This will floor the possible number of batches
batch_len = int(len(data) / nb_teachers)
nclasses = len(labels[0])
print("Start Index Selection")
data_sel = [data[labels[:, j] == 1] for j in range(nclasses)]
print("End Index Selection")
i = 0
data_sel_id = [0] * len(labels[0])
partition_data = []
partition_labels = []
while True:
partition_data.append(data_sel[i][data_sel_id[i]])
partition_labels.append(np_utils.to_categorical(i, nclasses))
if len(partition_data) == batch_len:
partition_data = np.asarray(partition_data)
partition_labels = np.asarray(partition_labels)
yield partition_data, partition_labels
partition_data = []
partition_labels = []
data_sel_id[i] += 1
if data_sel_id[i] == len(data_sel[i]):
data_sel_id[i] = 0
i = (i + 1) % nclasses
def conv_out_size_same(size, stride):
return int(math.ceil(float(size) / float(stride)))
def sigmoid_cross_entropy_with_logits(x, y):
try:
return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, labels=y)
except:
return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, targets=y)
class DCGAN(object):
def __init__(self, sess, input_height=32, input_width=32, crop=False,
batch_size=64, sample_num=64, output_height=32, output_width=32,
y_dim=10, z_dim=100, gf_dim=64, df_dim=32, sample_step=800,
gfc_dim=1024, dfc_dim=256, c_dim=3, dataset_name='default',
input_fname_pattern='*.jpg', checkpoint_dir=None, teacher_dir=None, generator_dir=None,
sample_dir=None, data_dir='./data', batch_teachers=10, teachers_batch=2,
orders=None,
thresh=None, dp_delta=1e-5, pca=False, pca_dim=5, non_private=False, random_proj=False, wgan=False,
wgan_scale=10, small=False, config=None):
"""
Args:
sess: TensorFlow session
batch_size: The size of batch. Should be specified before training.
z_dim: (optional) Dimension of dim for Z. [100]
gf_dim: (optional) Dimension of gen filters in first conv layer. [64]
df_dim: (optional) Dimension of discrim filters in first conv layer. [64]
gfc_dim: (optional) Dimension of gen units for for fully connected layer. [1024]
dfc_dim: (optional) Dimension of discrim units for fully connected layer. [1024]
c_dim: (optional) Dimension of image color. For grayscale input, set to 1. [3]
batch_teachers: Number of teacher models in one batch. Default 10.
teachers_batch: Batches of training teacher models. Default 1.
"""
self.config = config
self.small = small
self.wgan = wgan
self.wgan_scale = wgan_scale
self.sample_step = sample_step
self.pca = pca
self.pca_dim = pca_dim
self.random_proj = random_proj
self.dp_eps_list = []
self.rdp_eps_list = []
self.rdp_order_list = []
self.dp_eps_list_dept = []
self.rdp_eps_list_dept = []
self.rdp_order_list_dept = []
self.thresh = thresh
self.dp_delta = dp_delta
self.sample_dir = sample_dir
self.dataset = dataset_name
self.batch_teachers = batch_teachers
self.teachers_batch = teachers_batch
self.overall_teachers = batch_teachers * teachers_batch
self.sess = sess
self.crop = crop
self.batch_size = batch_size
self.sample_num = sample_num
self.input_height = input_height
self.input_width = input_width
self.output_height = output_height
self.output_width = output_width
self.z_dim = z_dim
self.y_dim = y_dim
self.gf_dim = gf_dim
self.df_dim = df_dim
self.gfc_dim = gfc_dim
self.dfc_dim = dfc_dim
# batch normalization : deals with poor initialization helps gradient flow
self.d_bn1 = batch_norm(name='d_bn1')
self.d_bn2 = batch_norm(name='d_bn2')
self.d_bn3 = batch_norm(name='d_bn3')
self.g_bn0 = batch_norm(name='g_bn0')
self.g_bn1 = batch_norm(name='g_bn1')
self.g_bn2 = batch_norm(name='g_bn2')
self.g_bn3 = batch_norm(name='g_bn3')
self.dataset_name = dataset_name
self.input_fname_pattern = input_fname_pattern
self.checkpoint_dir = checkpoint_dir
self.teacher_dir = teacher_dir
self.generator_dir = generator_dir
self.data_dir = data_dir
if orders is not None:
self.orders = np.asarray(orders)
else:
self.orders = np.hstack([1.1, np.arange(2, config.orders)])
self.rdp_counter = np.zeros(self.orders.shape)
self.rdp_counter_dept = np.zeros(self.orders.shape)
# Load the dataset, ignore test data for now
if self.dataset_name == 'mnist':
self.data_X, self.data_y = self.load_mnist()
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 1)
self.input_height = self.input_width = 28
self.output_height = self.output_width = 28
elif self.dataset_name == 'fashion_mnist':
self.data_X, self.data_y = self.load_fashion_mnist()
self.c_dim = self.data_X[0].shape[-1]
# = (self.c_dim == 1)
self.input_height = self.input_width = 28
self.output_height = self.output_width = 28
if self.config.random_label:
np.random.shuffle(self.data_y)
elif self.dataset_name == 'cifar':
self.data_X, self.data_y = self.load_cifar()
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'cifar-ae':
_, self.data_y = self.load_cifar()
import joblib
self.data_X = joblib.load('cifar10_ae_trn_2d.pkl')
self.input_height = self.output_height = 24
self.input_width = self.output_width = 16
self.c_dim = 1
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'cifar-ae-hd':
_, self.data_y = self.load_cifar()
import joblib
self.data_X = joblib.load('cifar10_ae_trn_hd_2d.pkl')
self.input_height = self.output_height = 16
self.input_width = self.output_width = 16
self.c_dim = 3
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'cifar-ae-hd-hu':
_, self.data_y = self.load_cifar()
import joblib
self.data_X = joblib.load('cifar10_ae_trn_hd_hu_2d.pkl')
self.input_height = self.output_height = 16
self.input_width = self.output_width = 16
self.c_dim = 3
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'cinic-ae-hd-hu':
import joblib
self.data_X = joblib.load('cinic10_ae_trn_hd_hu_2d.pkl')
self.data_y = joblib.load('cinic10_y_trn.pkl')
self.input_height = self.output_height = 16
self.input_width = self.output_width = 16
self.c_dim = 3
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'cinic-ae-20d':
import joblib
self.data_X = joblib.load('cinic10_ae_trn_20d.pkl')
self.data_y = joblib.load('cinic10_y_trn_20d.pkl')
self.input_height = self.output_height = 2
self.input_width = self.output_width = 2
self.c_dim = 5
self.grayscale = (self.c_dim == 5)
elif 'small-celebA-gender' in self.dataset_name:
mode = self.dataset_name.split('-')[-1]
self.y_dim = 2
self.input_size = self.input_height = self.input_width = 32
self.output_size = self.output_height = self.output_width = 32
self.data_X, self.data_y = self.load_small_celebA_gender(mode)
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 1)
if self.config.random_label:
np.random.shuffle(self.data_y)
elif 'celebA-hair' in self.dataset_name:
mode = self.dataset_name.split('-')[-1]
self.y_dim = 3
self.input_size = self.input_height = self.input_width = 64
self.output_size = self.output_height = self.output_width = 64
self.data_X, self.data_y = self.load_batch_celebA_hair(mode)
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 1)
if self.config.random_label:
np.random.shuffle(self.data_y)
elif 'celebA-gender' in self.dataset_name:
mode = self.dataset_name.split('-')[-1]
self.y_dim = 2
self.input_size = self.input_height = self.input_width = 64
self.output_size = self.output_height = self.output_width = 64
self.data_X, self.data_y = self.load_batch_celebA_gender(mode)
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 1)
if self.config.random_label:
np.random.shuffle(self.data_y)
elif self.dataset_name == 'cinic':
self.data_X, self.data_y = self.load_cinic()
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 3)
elif self.dataset_name == 'stl':
self.data_X, self.data_y = self.load_stl()
self.c_dim = self.data_X[0].shape[-1]
self.grayscale = (self.c_dim == 3)
elif 'isolet' in self.dataset_name:
self.data_X, self.data_y = self.load_isolet()
self.train_size, self.input_size = self.data_X.shape
self.output_size = self.input_size
# self.y_dim = None
# self.crop = False
if self.pca_dim > self.input_size:
self.pca_dim = self.input_size
elif 'fire-small' in self.dataset_name:
self.data_X = self.load_fire_data()
self.data_y = None
self.train_size, self.input_size = self.data_X.shape
self.output_size = self.input_size
self.y_dim = None
self.crop = False
if self.pca_dim > self.input_size:
self.pca_dim = self.input_size
elif 'census' in self.dataset_name:
self.data_X = self.load_census_data()
self.data_y = None
self.train_size, self.input_size = self.data_X.shape
self.output_size = self.input_size
self.y_dim = None
self.crop = False
if self.pca_dim > self.input_size:
self.pca_dim = self.input_size
else:
raise Exception("Check value of dataset flag")
print("Dataset load finished!")
self.train_data_list = []
self.train_label_list = []
# if non_private:
# for i in range(self.overall_teachers):
# partition_data, partition_labels = partition_dataset(self.data_X, self.data_y, 1, i)
# self.train_data_list.append(partition_data)
# self.train_label_list.append(partition_labels)
# else:
from collections import defaultdict
from tqdm import tqdm
self.save_dict = defaultdict(lambda: False)
# stats = []
if config.shuffle:
gen = evenly_partition_dataset(self.data_X, self.data_y, self.overall_teachers)
for i in tqdm(range(self.overall_teachers)):
partition_data, partition_labels = next(gen)
self.train_data_list.append(partition_data)
self.train_label_list.append(partition_labels)
# stats.append(np.average(partition_labels, axis=0))
# print(stats[-1])
else:
for i in tqdm(range(self.overall_teachers)):
partition_data, partition_labels = partition_dataset(self.data_X, self.data_y, self.overall_teachers, i)
self.train_data_list.append(partition_data)
self.train_label_list.append(partition_labels)
# stats.append(np.average(partition_labels, axis=0))
# print(stats[-1])
# stats = np.asarray(stats)
# print("avg:", np.average(stats, axis=0))
# print("max:", np.max(stats, axis=0))
# print("min:", np.min(stats, axis=0))
# print(self.train_label_list)
self.train_size = len(self.train_data_list[0])
if self.train_size < self.batch_size:
self.batch_size = self.train_size
print('adjusted batch size:', self.batch_size)
# raise Exception("[!] Entire dataset size (%d) is less than the configured batch_size (%d) " % (
# self.train_size, self.batch_size))
self.build_model()
def init_ae(self, load=None):
if self.config.ae == 'segnet':
from ae.segnet import segnet
import torchvision.models as models
self.ae = segnet(hid_dim=self.config.hid_dim)
if self.config.hid_dim == 512:
vgg16 = models.vgg16(pretrained=True)
self.ae.init_vgg16_params(vgg16)
elif self.config.ae == 'convnet':
from ae.convnet import convnet
self.ae = convnet()
elif self.config.ae == 'convnetv2':
from ae.convnetv2 import convnetv2
self.ae = convnetv2()
elif self.config.ae == 'convnetv3':
from ae.convnetv3 import convnetv3
self.ae = convnetv3()
elif self.config.ae == 'convnetv4':
from ae.convnetv4 import convnetv4
self.ae = convnetv4()
else:
raise Exception("Operation not supported")
if load:
self.ae.load_state_dict(torch.load(load))
def init_multitask_ae(self, load=None):
if self.config.ae == 'segnet':
from ae.segnet import segnet
import torchvision.models as models
self.ae = segnet(hid_dim=self.config.hid_dim)
if self.config.hid_dim == 512:
vgg16 = models.vgg16(pretrained=True)
self.ae.init_vgg16_params(vgg16)
elif self.config.ae == 'convnet':
from ae.convnet import convnet, convnet_multitask
self.ae = convnet_multitask(convnet())
elif self.config.ae == 'convnetv2':
from ae.convnetv2 import convnetv2, convnetv2_multitask
self.ae = convnetv2_multitask(convnetv2())
elif self.config.ae == 'convnetv3':
from ae.convnetv3 import convnetv3, convnetv3_multitask
self.ae = convnetv3_multitask(convnetv3())
elif self.config.ae == 'convnetv4':
from ae.convnetv4 import convnetv4, convnetv4_multitask
self.ae = convnetv4_multitask(convnetv4())
else:
raise Exception("Operation not supported")
if load:
self.ae.model.load_state_dict(torch.load(load))
def finetune_ae(self):
from tensorboardX import SummaryWriter
from tqdm import tqdm
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
ckpt = os.path.join(self.config.checkpoint_dir, self.config.checkpoint_name)
self.init_multitask_ae(ckpt)
model = self.ae = self.ae.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=self.config.learning_rate, weight_decay=1e-5)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: max(0.98**x, 1e-6))
if self.config.loss == 'l2':
alpha = 20
criterion = torch.nn.MSELoss()
elif self.config.loss == 'BCE':
criterion = torch.nn.BCELoss()
alpha = 5
elif self.config.loss == 'l1':
criterion = torch.nn.L1Loss()
# alpha = 0
reconstruct_criterion = torch.nn.MSELoss()
task_criterion = torch.nn.CrossEntropyLoss()
ckpt_dir = 'finetune-{}-{}/'.format(self.dataset_name, alpha) + self.config.checkpoint_dir
x = self.data_X
y = self.data_y
writer = SummaryWriter(ckpt_dir)
if self.dataset_name == 'cifar':
test_x, test_y = self.load_cifar_test()
else:
test_x, test_y = self.load_cinic_test()
# _, y = torch.max(y, dim=0)
# _, test_y = torch.max(test_y, dim=0)
x = np.transpose(x, (0, 3, 2, 1))
test_x = np.transpose(test_x, (0, 3, 2, 1))
best_test_loss = np.inf
for epoch in range(self.config.epoch):
total_loss = []
flag = False
## training on the stl
model.train()
from sklearn.utils import shuffle
x, y = shuffle(x, y)
for i in tqdm(range(0, len(x), self.batch_size)):
batch_x = torch.FloatTensor(x[i:min(i + self.batch_size, len(x))]).to(device)
batch_y = torch.LongTensor(y[i:min(i + self.batch_size, len(y))]).to(device)
_, batch_y = torch.max(batch_y, dim=1)
logits, decoded = model(batch_x)
task_loss = task_criterion(logits, batch_y)
reconstruct_loss = criterion(decoded, batch_x)
loss = task_loss + reconstruct_loss * alpha
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item(),
writer.add_scalar('ae/loss', loss, i + epoch * len(x))
total_loss = np.mean(total_loss)
print("|epoch {} | total loss: {}".format(epoch, total_loss))
test_loss = []
test_acc = []
test_reconstruct = []
## testing on
model.eval()
with torch.no_grad():
for i in tqdm(range(0, len(test_x), self.batch_size)):
batch_x = torch.tensor(test_x[i:min(i + self.batch_size, len(x))]).to(device)
batch_y = torch.LongTensor(test_y[i:min(i + self.batch_size, len(y))]).to(device)
_, batch_y = torch.max(batch_y, dim=1)
logits, decoded = model(batch_x)
_, pred = torch.max(logits, dim=1)
accuracy = (batch_y == pred).float().mean().item()
reconstruct_loss = reconstruct_criterion(decoded, batch_x)
loss = reconstruct_loss * alpha + task_criterion(logits, batch_y)
test_loss += loss.item(),
test_reconstruct = reconstruct_loss.item(),
test_acc += accuracy,
test_loss = np.mean(test_loss)
test_acc = np.mean(test_acc)
test_reconstruct = np.mean(test_reconstruct)
print("|epoch {} | total test loss: {} | total test accuracy: {} | reconstruct loss: {}".
format(epoch, test_loss, test_acc, test_reconstruct))
if test_loss < best_test_loss:
best_test_loss = test_loss
## save model
torch.save(model.state_dict(), os.path.join(ckpt_dir, 'model-epoch_{}.pth'.format(epoch)))
elif epoch % 50 == 0:
torch.save(model.state_dict(), os.path.join(ckpt_dir, 'model-epoch_{}.pth'.format(epoch)))
scheduler.step()
writer.close()
def train_ae(self):
from tensorboardX import SummaryWriter
from tqdm import tqdm
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.init_ae()
model = self.ae = self.ae.to(device)
# optimizer = torch.optim.Adam(model.parameters(), lr=self.config.learning_rate, betas=(0.9, 0.999), eps=1e-8,
# weight_decay=1e-5)
optimizer = torch.optim.Adam(model.parameters(), lr=self.config.learning_rate, weight_decay=1e-5)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: max(0.98**x, 1e-6))
if self.config.loss == 'l2':
criterion = torch.nn.MSELoss()
elif self.config.loss == 'BCE':
criterion = torch.nn.BCELoss()
elif self.config.loss == 'l1':
criterion = torch.nn.L1Loss()
ckpt_dir = 'runs/' + self.config.checkpoint_name
x = self.data_X
writer = SummaryWriter(ckpt_dir)
test_x, test_y = self.load_cifar()
x = np.transpose(x, (0, 3, 2, 1))
test_x = np.transpose(test_x, (0, 3, 2, 1))
best_test_loss = np.inf
for epoch in range(self.config.epoch):
total_loss = []
flag = False
## training on the stl
model.train()
from sklearn.utils import shuffle
x = shuffle(x)
for i in tqdm(range(0, len(x), self.batch_size)):
batch_x = torch.FloatTensor(x[i:min(i + self.batch_size, len(x))]).to(device)
outputs = model(batch_x)
if not flag:
flag = True
import joblib
joblib.dump((outputs, batch_x), os.path.join(ckpt_dir, 'debug.pkl'))
loss = criterion(outputs, batch_x)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item(),
writer.add_scalar('ae/loss', loss, i + epoch * len(x))
total_loss = np.mean(total_loss)
print("|epoch {} | total loss: {}".format(epoch, total_loss))
test_loss = []
## testing on
model.eval()
with torch.no_grad():
for i in tqdm(range(0, len(test_x), self.batch_size)):
batch_x = torch.tensor(test_x[i:min(i + self.batch_size, len(x))]).to(device)
outputs = model(batch_x)
loss = criterion(outputs, batch_x)
test_loss += loss.item(),
test_loss = np.mean(test_loss)
print("|epoch {} | total test loss: {}".format(epoch, test_loss))
if test_loss < best_test_loss:
best_test_loss = test_loss
## save model
torch.save(model.state_dict(), os.path.join(ckpt_dir, 'model-epoch_{}.pth'.format(epoch)))
elif epoch % 50 == 0:
torch.save(model.state_dict(), os.path.join(ckpt_dir, 'model-epoch_{}.pth'.format(epoch)))
scheduler.step()
writer.close()
## nonprivate aggregation
def aggregate_topk(self, output_list, topk, alpha=1e-3):
flatten_grad = np.asarray([arr.flatten() for arr in output_list])
flatten_grad_pos = np.array(flatten_grad).clip(0)
flatten_grad_neg = np.array(flatten_grad).clip(max=0)
concat_grad = np.hstack((flatten_grad_pos, flatten_grad_neg))
aggregate_grad = np.abs(np.sum(concat_grad, axis=0))
if self.config.save_vote and self.epoch_change:
self.epoch_change = False
def save_sign_weighted_votes():
save_dir = os.path.join(self.checkpoint_dir, 'sign_weighted_votes.pkl')
import joblib
if os.path.exists(save_dir):
votes = joblib.load(save_dir)
votes = np.vstack((votes, aggregate_grad))
joblib.dump(votes, save_dir)
print(aggregate_grad.shape)
else:
joblib.dump(aggregate_grad, save_dir)
def save_sign_equal_votes():
save_dir = os.path.join(self.checkpoint_dir, 'sign_equal_votes.pkl')
voted_arr = np.sum(convert2topk(np.abs(concat_grad), topk), axis=0)
import joblib
if os.path.exists(save_dir):
votes = joblib.load(save_dir)
votes = np.vstack((votes, voted_arr))
print(voted_arr.shape)
joblib.dump(votes, save_dir)
else:
joblib.dump(voted_arr, save_dir)
def save_unsign_equal_votes():
save_dir = os.path.join(self.checkpoint_dir, 'unsign_equal_votes.pkl')
voted_arr = np.sum(convert2topk(np.abs(flatten_grad), topk), axis=0)
import joblib
if os.path.exists(save_dir):
votes = joblib.load(save_dir)
votes = np.vstack((votes, voted_arr))
print(voted_arr.shape)
joblib.dump(votes, save_dir)
else:
joblib.dump(voted_arr, save_dir)
def save_unsign_weighted_votes():
save_dir = os.path.join(self.checkpoint_dir, 'unsign_weighted_votes.pkl')
voted_arr = np.sum(np.abs(flatten_grad), axis=0)
import joblib
if os.path.exists(save_dir):
votes = joblib.load(save_dir)
votes = np.vstack((votes, voted_arr))
print(voted_arr.shape)
joblib.dump(votes, save_dir)
else:
joblib.dump(voted_arr, save_dir)
save_sign_equal_votes()
save_sign_weighted_votes()
save_unsign_equal_votes()
save_unsign_weighted_votes()
topk_ind = np.argpartition(aggregate_grad, -topk)[-topk:]
pos_ind = topk_ind[topk_ind < flatten_grad[0].shape]
neg_ind = topk_ind[topk_ind >= flatten_grad[0].shape]
neg_ind -= flatten_grad[0].shape
sign_grad = np.zeros_like(flatten_grad[0])
sign_grad[pos_ind] = 1
sign_grad[neg_ind] = -1
return alpha * sign_grad.reshape(output_list[0].shape)
def aggregate_results(self, output_list, config, thresh=None, epoch=None):
if self.pca:
res, rdp_budget = gradient_voting_rdp(
output_list,
config.step_size,
config.sigma,
config.sigma_thresh,
self.orders,
pca_mat=self.pca_components,
thresh=thresh
)
elif self.config.mean_kernel:
from skimage.measure import block_reduce
from skimage.transform import resize
arr = np.asarray(output_list)
mean_arr = block_reduce(arr, block_size=(1, 8, 8, 1), func=np.mean)
res, rdp_budget = gradient_voting_rdp(
mean_arr,
config.step_size,
config.sigma,
config.sigma_thresh,
self.orders,
thresh=thresh
)
res = resize(res, (16, 16, 3), clip=False)
elif self.config.signsgd:
# res = self.aggregate_topk(output_list, topk=self.config.topk, alpha=self.config.learning_rate)
# rdp_budget = 0
if self.config.save_vote and self.epoch_change:
self.epoch_change = False
ablation_test_on_different_k(output_list, self.checkpoint_dir, self.epoch)
b = config.max_grad if config.max_grad > 0 else None
res, rdp_budget = signsgd_aggregate(output_list, config.sigma, self.orders, config.topk, config.thresh,
alpha=config.learning_rate, stochastic=config.stochastic, b=b)
elif self.config.signsgd_nothresh:
# res = self.aggregate_topk(output_list, topk=self.config.topk, alpha=self.config.learning_rate)
# rdp_budget = 0
if self.config.save_vote and self.epoch_change:
self.epoch_change = False
ablation_test_on_different_k(output_list, self.checkpoint_dir, self.epoch)
b = config.max_grad if config.max_grad > 0 else None
res, rdp_budget = signsgd_aggregate_no_thresh(output_list, config.sigma, self.orders, config.topk, config.thresh,
alpha=config.learning_rate, stochastic=config.stochastic, b=b)
elif self.config.sketchsgd:
b = config.max_grad if config.max_grad > 0 else None
res, rdp_budget = sketchtopk_aggregate(output_list, config.sigma, self.orders, config.topk, config.thresh,
alpha=config.learning_rate, stochastic=config.stochastic, b=b)
elif self.config.klevelsgd:
# res = self.aggregate_topk(output_list, topk=self.config.topk, alpha=self.config.learning_rate)
# rdp_budget = 0
b = config.max_grad if config.max_grad > 0 else None
res, rdp_budget = k_level_sgd_aggregate(output_list, config.sigma, self.orders, config.klevel, config.thresh,
alpha=config.learning_rate, b=b)
elif self.config.signsgd_dept:
if self.config.save_vote and self.epoch_change:
self.epoch_change = False
ablation_test_on_different_k(output_list, self.checkpoint_dir, self.epoch)
b = config.max_grad if config.max_grad > 0 else None
res, rdp_budget, dept_rdp_budget = signsgd_aggregate_dept(output_list, config.sigma, self.orders, config.topk, config.thresh,
alpha=config.learning_rate, stochastic=config.stochastic, b=b)
return res, rdp_budget, dept_rdp_budget
elif self.random_proj:
orig_dim = 1
for dd in self.image_dims:
orig_dim = orig_dim * dd
if epoch is not None:
proj_dim = min(epoch + 1, self.pca_dim)
else:
proj_dim = self.pca_dim
n_data = output_list[0].shape[0]
if config.proj_mat > 1:
proj_dim_ = proj_dim // config.proj_mat
n_data_ = n_data // config.proj_mat
orig_dim_ = orig_dim // config.proj_mat
print("n_data:", n_data)
print("orig_dim:", orig_dim)
transformers = [GaussianRandomProjection(n_components=proj_dim_) for _ in range(config.proj_mat)]
for transformer in transformers:
transformer.fit(np.zeros([n_data_, orig_dim_]))
print(transformer.components_.shape)
proj_matrices = [np.transpose(transformer.components_) for transformer in transformers]
res, rdp_budget = gradient_voting_rdp_multiproj(
output_list,
config.step_size,
config.sigma,
config.sigma_thresh,
self.orders,
pca_mats=proj_matrices,
thresh=thresh
)
else:
transformer = GaussianRandomProjection(n_components=proj_dim)
transformer.fit(np.zeros([n_data, orig_dim])) # only the shape of output_list[0] is used
proj_matrix = np.transpose(transformer.components_)
# proj_matrix = np.random.normal(loc=np.zeros([orig_dim, proj_dim]), scale=1/float(proj_dim), size=[orig_dim, proj_dim])
res, rdp_budget = gradient_voting_rdp(
output_list,
config.step_size,
config.sigma,
config.sigma_thresh,
self.orders,
pca_mat=proj_matrix,
thresh=thresh
)
else:
res, rdp_budget = gradient_voting_rdp(output_list, config.step_size, config.sigma, config.sigma_thresh,
self.orders, thresh=thresh)
return res, rdp_budget
def non_private_aggregation(self, output_list, config):
# TODO update nonprivate aggregation
sum_arr = np.zeros(output_list[0].shape)
for arr in output_list:
sum_arr += arr
return sum_arr / len(output_list)
def load_fire_data(self):
dataset_name = os.path.join(self.data_dir, self.dataset_name)
dataset_name += '.csv'
X = np.loadtxt(dataset_name)
seed = 307
np.random.seed(seed)
np.random.shuffle(X)
return X
def load_census_data(self):
dataset_name = os.path.join(self.data_dir, self.dataset_name)
dataset_name += '.pkl'
with open(dataset_name, "rb") as f:
X = pickle.load(f)
seed = 37
np.random.seed(seed)
np.random.shuffle(X)
return X
def load_isolet(self):
dataset_name = os.path.join(self.data_dir, self.dataset_name)
dataset_name += '.csv'
X = np.loadtxt(dataset_name)
# print(X.shape)
seed = 37
np.random.seed(seed)
np.random.shuffle(X)
X = np.hsplit(X, [-1])
x = X[0]
# print(X.shape)
y = X[1]
# print(y.shape)
y = np_utils.to_categorical(y, 2)
# print(y.shape)
return x, y
def load_cifar(self):
# dataset_name = os.path.join(self.data_dir, self.dataset_name)
# dataset_name += '.csv'
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = np_utils.to_categorical(y_train, 10)
x_train = x_train.reshape(x_train.shape[0], 32, 32, 3)
x_train = x_train.astype('float32') / 255.
return x_train, y_train
def load_cifar_test(self):
# dataset_name = os.path.join(self.data_dir, self.dataset_name)
# dataset_name += '.csv'
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_test = np_utils.to_categorical(y_test, 10)
x_test = x_test.reshape(x_test.shape[0], 32, 32, 3)
x_test = x_test.astype('float32') / 255.
return x_test, y_test
def load_stl(self):
path_to_data = '../data/stl10_binary/unlabeled_X.bin'
with open(path_to_data, 'rb') as f:
# read whole file in uint8 chunks
everything = np.fromfile(f, dtype=np.uint8)
# We force the data into 3x96x96 chunks, since the
# images are stored in "column-major order", meaning
# that "the first 96*96 values are the red channel,
# the next 96*96 are green, and the last are blue."
# The -1 is since the size of the pictures depends
# on the input file, and this way numpy determines
# the size on its own.
images = np.reshape(everything, (-1, 3, 96, 96))
# Now transpose the images into a standard image format
# readable by, for example, matplotlib.imshow
# You might want to comment this line or reverse the shuffle
# if you will use a learning algorithm like CNN, since they like
# their channels separated.
images = np.transpose(images, (0, 3, 2, 1))
X_resized = np.zeros((100000, 32, 32, 3))
for i in range(0, 100000):
img = images[i]
img = Image.fromarray(img)
img = np.array(img.resize((32, 32), Image.BICUBIC)) # 修改分辨率,再转为array类
X_resized[i, :, :, :] = img
y = np.random.randint(10, size=(100000, 1))
y = np_utils.to_categorical(y, 10)
X_resized /= 255
print(X_resized)
return X_resized, y
def load_cinic(self):
import torchvision
import torchvision.transforms as transforms
from keras.utils import np_utils
cinic_directory = '../data/cinic'
# cinic_mean = [0.47889522, 0.47227842, 0.43047404]
# cinic_std = [0.24205776, 0.23828046, 0.25874835]
image_folder = torchvision.datasets.ImageFolder(cinic_directory + '/train/',
# transform=transforms.Compose([transforms.ToTensor(),
# transforms.Normalize(mean=cinic_mean,std=cinic_std)])),
transform=transforms.ToTensor())
cinic_train = torch.utils.data.DataLoader(image_folder, batch_size=180000, shuffle=True)
print(image_folder.class_to_idx)
for batch_ndx, sample in enumerate(cinic_train):
x = np.asarray(sample[0])
y = np.asarray(sample[1])
x = np.transpose(x, [0, 2, 3, 1])
y = np_utils.to_categorical(y, 10)
return x, y
def load_cinic_test(self):
import torchvision
import torchvision.transforms as transforms
from keras.utils import np_utils
cinic_directory = '../data/cinic'
# cinic_mean = [0.47889522, 0.47227842, 0.43047404]
# cinic_std = [0.24205776, 0.23828046, 0.25874835]
image_folder = torchvision.datasets.ImageFolder(cinic_directory + '/test/',
# transform=transforms.Compose([transforms.ToTensor(),
# transforms.Normalize(mean=cinic_mean,std=cinic_std)])),
transform=transforms.ToTensor())
cinic_train = torch.utils.data.DataLoader(image_folder, batch_size=90000, shuffle=True)
print(image_folder.class_to_idx)
for batch_ndx, sample in enumerate(cinic_train):
x = np.asarray(sample[0])
y = np.asarray(sample[1])
x = np.transpose(x, [0, 2, 3, 1])
y = np_utils.to_categorical(y, 10)
return x, y
def load_celebA_gender(self, mode='train'):
celebA_directory = '../../data/celebA/'
import joblib
if mode == 'train':
train_x = joblib.load(celebA_directory + 'celebA-trn-x-lg-ups.pkl')
train_y = joblib.load(celebA_directory + 'celebA-trn-gender-lg-ups.pkl')
train_y = np_utils.to_categorical(train_y, 2)
val_x = joblib.load(celebA_directory + 'celebA-val-x-lg-ups.pkl')
val_y = joblib.load(celebA_directory + 'celebA-val-gender-lg-ups.pkl')
val_y = np_utils.to_categorical(val_y, 2)
return np.vstack((train_x, val_x)), np.vstack((train_y, val_y))
elif mode == 'val':
val_x = joblib.load(celebA_directory + 'celebA-val-x-lg-ups.pkl')
val_y = joblib.load(celebA_directory + 'celebA-val-gender-lg-ups.pkl')
val_y = np_utils.to_categorical(val_y, 2)
return val_x, val_y
elif mode == 'tst':
tst_x = joblib.load(celebA_directory + 'celebA-tst-x.pkl')
tst_y = joblib.load(celebA_directory + 'celebA-tst-gender.pkl')
tst_y = np_utils.to_categorical(tst_y, 2)
return tst_x, tst_y
else:
raise Exception("Mode {} Not support".format(mode))
def load_batch_celebA_gender(self, mode='train'):
celebA_directory = '../../data/celebA/'
import joblib
from tqdm import tqdm
if mode == 'train':
train_x = np.zeros((189018 + 22818, 64, 64, 3))
dim = 0
for i in tqdm(range(20)):
x = joblib.load(celebA_directory + f'celebA-trn-x-lg-ups-{i}.pkl')
train_x[dim: dim + len(x)] = x
dim += len(x)
train_y = joblib.load(celebA_directory + 'celebA-trn-gender-lg-ups.pkl')
train_y = np_utils.to_categorical(train_y, 2)
for i in tqdm(range(10)):
x = joblib.load(celebA_directory + f'celebA-val-x-lg-ups-{i}.pkl')
train_x[dim: dim + len(x)] = x
dim += len(x)
val_y = joblib.load(celebA_directory + 'celebA-val-gender-lg-ups.pkl')
val_y = np_utils.to_categorical(val_y, 2)
print("Load train x finished!")
return train_x, np.vstack((train_y, val_y))
elif mode == 'val':
val_x = []
for i in tqdm(range(10)):
val_x.append(joblib.load(celebA_directory + f'celebA-val-x-lg-ups-{i}.pkl'))