-
Notifications
You must be signed in to change notification settings - Fork 3
/
MIA_torch.py
2009 lines (1731 loc) · 103 KB
/
MIA_torch.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 torch
import numpy as np
import torch.nn as nn
from torch.serialization import save
import architectures_torch as architectures
from utils import setup_logger, accuracy, AverageMeter, WarmUpLR, apply_transform_test, apply_transform, TV, l2loss, dist_corr, get_PSNR
from utils import freeze_model_bn, average_weights, DistanceCorrelationLoss, spurious_loss, prune_top_n_percent_left, dropout_defense, prune_defense
from thop import profile
import logging
from torch.autograd import Variable
from resnet_cifar import ResNet20, ResNet32
from mobilenetv2 import MobileNetV2
from vgg import vgg11, vgg13, vgg11_bn, vgg13_bn
import pytorch_ssim
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
import torchvision
from torchvision.utils import save_image
from datetime import datetime
import os
from shutil import rmtree
from datasets_torch import get_cifar100_trainloader, get_cifar100_testloader, get_cifar10_trainloader, \
get_cifar10_testloader, get_mnist_bothloader, get_facescrub_bothloader, get_SVHN_trainloader, get_SVHN_testloader, get_fmnist_bothloader, get_tinyimagenet_bothloader
def init_weights(m): # weight initialization
if type(m) == nn.Linear:
torch.nn.init.xavier_uniform_(m.weight, gain=1.0)
if m.bias is not None:
m.bias.data.zero_()
if type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d:
torch.nn.init.xavier_uniform_(m.weight, gain=1.0)
if m.bias is not None:
m.bias.data.zero_()
def denormalize(x, dataset): # normalize a zero mean, std = 1 to range [0, 1]
if dataset == "mnist" or dataset == "fmnist":
return torch.clamp((x + 1)/2, 0, 1)
elif dataset == "cifar10":
std = [0.247, 0.243, 0.261]
mean = [0.4914, 0.4822, 0.4465]
elif dataset == "cifar100":
std = [0.2673342858792401, 0.2564384629170883, 0.27615047132568404]
mean = [0.5070751592371323, 0.48654887331495095, 0.4409178433670343]
elif dataset == "imagenet":
std = [0.229, 0.224, 0.225]
mean = [0.485, 0.456, 0.406]
elif dataset == "facescrub":
std = (0.2058, 0.2275, 0.2098)
mean = (0.5708, 0.5905, 0.4272)
elif dataset == "svhn":
std = (0.1189, 0.1377, 0.1784)
mean = (0.3522, 0.4004, 0.4463)
# 3, H, W, B
tensor = x.clone().permute(1, 2, 3, 0)
for t, m, s in zip(range(tensor.size(0)), mean, std):
tensor[t] = (tensor[t]).mul_(s).add_(m)
# B, 3, H, W
return torch.clamp(tensor, 0, 1).permute(3, 0, 1, 2)
def test_denorm(): # test function for denorm
CIFAR100_TRAIN_MEAN = (0.5070751592371323, 0.48654887331495095, 0.4409178433670343)
CIFAR100_TRAIN_STD = (0.2673342858792401, 0.2564384629170883, 0.27615047132568404)
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(CIFAR100_TRAIN_MEAN, CIFAR100_TRAIN_STD)
])
cifar10_training = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_train)
cifar10_training_loader_iter = iter(DataLoader(cifar10_training, shuffle=False, num_workers=1, batch_size=128))
transform_orig = transforms.Compose([
transforms.ToTensor()
])
cifar10_original = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_orig)
cifar10_original_loader_iter = iter(DataLoader(cifar10_original, shuffle=False, num_workers=1, batch_size=128))
images, _ = next(cifar10_training_loader_iter)
orig_image, _ = next(cifar10_original_loader_iter)
recovered_image = denormalize(images, "cifar100")
return torch.isclose(orig_image, recovered_image)
def save_images(input_imgs, output_imgs, epoch, path, offset=0, batch_size=64): # saved image from tensor to jpg
"""
"""
input_prefix = "inp_"
output_prefix = "out_"
out_folder = "{}/{}".format(path, epoch)
out_folder = os.path.abspath(out_folder)
if not os.path.isdir(out_folder):
os.makedirs(out_folder)
for img_idx in range(output_imgs.shape[0]):
inp_img_path = "{}/{}{}.jpg".format(out_folder, input_prefix, offset * batch_size + img_idx)
out_img_path = "{}/{}{}.jpg".format(out_folder, output_prefix, offset * batch_size + img_idx)
if input_imgs is not None:
save_image(input_imgs[img_idx], inp_img_path)
if output_imgs is not None:
save_image(output_imgs[img_idx], out_img_path)
class MIA: # main class for every thing
def __init__(self, arch, cutting_layer, batch_size, n_epochs, scheme="V2_epoch", num_client=2, dataset="cifar10",
logger=None, save_dir=None, regularization_option="None", regularization_strength=0,
collude_use_public=False, initialize_different=False, learning_rate=0.1, local_lr = -1,
gan_AE_type="custom", random_seed=123, client_sample_ratio = 1.0,
load_from_checkpoint = False, bottleneck_option="None", measure_option=False,
optimize_computation=1, decoder_sync = False, bhtsne_option = False, gan_loss_type = "SSIM", attack_confidence_score = False,
ssim_threshold = 0.0, finetune_freeze_bn = False, load_from_checkpoint_server = False, source_task = "cifar100",
save_activation_tensor = False, save_more_checkpoints = False, dataset_portion = 1.0, noniid = 1.0):
torch.manual_seed(random_seed)
np.random.seed(random_seed)
self.arch = arch
self.bhtsne = bhtsne_option
self.batch_size = batch_size
self.lr = learning_rate
self.finetune_freeze_bn = finetune_freeze_bn
if local_lr == -1: # if local_lr is not set
self.local_lr = self.lr
else:
self.local_lr = local_lr
self.n_epochs = n_epochs
self.measure_option = measure_option
self.optimize_computation = optimize_computation
self.client_sample_ratio = client_sample_ratio
self.dataset_portion = dataset_portion
self.noniid_ratio = noniid
self.save_more_checkpoints = save_more_checkpoints
# setup save folder
if save_dir is None:
self.save_dir = "./saves/{}/".format(datetime.today().strftime('%m%d%H%M'))
else:
self.save_dir = str(save_dir) + "/"
if not os.path.exists(self.save_dir):
os.makedirs(self.save_dir)
# setup tensorboard
tensorboard_path = str(save_dir) + "/tensorboard"
if not os.path.isdir(tensorboard_path):
os.makedirs(tensorboard_path)
self.writer = SummaryWriter(log_dir=tensorboard_path)
self.save_activation_tensor = save_activation_tensor
# setup logger
model_log_file = self.save_dir + '/MIA.log'
if logger is not None:
self.logger = logger
else:
self.logger = setup_logger('{}_logger'.format(str(save_dir)), model_log_file, level=logging.DEBUG)
self.warm = 1
self.scheme = scheme
# migrate old naming:
if self.scheme == "V1" or self.scheme == "V2" or self.scheme == "V3" or self.scheme == "V4":
self.scheme = self.scheme + "_batch"
self.num_client = num_client
self.dataset = dataset
self.call_resume = False
self.load_from_checkpoint = load_from_checkpoint
self.load_from_checkpoint_server = load_from_checkpoint_server
self.source_task = source_task
self.cutting_layer = cutting_layer
if self.cutting_layer == 0:
self.logger.debug("Centralized Learning Scheme:")
if "resnet20" in arch:
self.logger.debug("Split Learning Scheme: Overall Cutting_layer {}/10".format(self.cutting_layer))
if "vgg11" in arch:
self.logger.debug("Split Learning Scheme: Overall Cutting_layer {}/13".format(self.cutting_layer))
if "mobilenetv2" in arch:
self.logger.debug("Split Learning Scheme: Overall Cutting_layer {}/9".format(self.cutting_layer))
self.confidence_score = attack_confidence_score
self.collude_use_public = collude_use_public
self.initialize_different = initialize_different
if "C" in bottleneck_option or "S" in bottleneck_option:
self.adds_bottleneck = True
self.bottleneck_option = bottleneck_option
else:
self.adds_bottleneck = False
self.bottleneck_option = bottleneck_option
self.decoder_sync = decoder_sync
''' Activation Defense '''
self.regularization_option = regularization_option
# If strength is 0.0, then there is no regularization applied, train normally.
self.regularization_strength = regularization_strength
if self.regularization_strength == 0.0:
self.regularization_option = "None"
# setup nopeek regularizer
if "nopeek" in self.regularization_option:
self.nopeek = True
else:
self.nopeek = False
self.alpha1 = regularization_strength # set to 0.1 # 1000 in Official NoteBook https://github.com/tremblerz/nopeek/blob/master/noPeekCifar10%20(1)-Copy2.ipynb
# setup gan_adv regularizer
self.gan_AE_activation = "sigmoid"
self.gan_AE_type = gan_AE_type
self.gan_loss_type = gan_loss_type
self.gan_decay = 0.2
self.alpha2 = regularization_strength # set to 1~10
self.pretrain_epoch = 100
self.ssim_threshold = ssim_threshold
if "gan_adv" in self.regularization_option:
self.gan_regularizer = True
if "step" in self.regularization_option:
try:
self.gan_num_step = int(self.regularization_option.split("step")[-1])
except:
print("Auto extract step fail, geting default value 3")
self.gan_num_step = 3
else:
self.gan_num_step = 3
if "noise" in self.regularization_option:
self.gan_noise = True
else:
self.gan_noise = False
else:
self.gan_regularizer = False
self.gan_noise = False
self.gan_num_step = 1
# setup local dp (noise-injection defense)
if "local_dp" in self.regularization_option:
self.local_DP = True
else:
self.local_DP = False
self.dp_epsilon = regularization_strength
if "dropout" in self.regularization_option:
self.dropout_defense = True
try:
self.dropout_ratio = float(self.regularization_option.split("dropout")[1].split("_")[0])
except:
self.dropout_ratio = regularization_strength
print("Auto extract dropout ratio fail, use regularization_strength input as dropout ratio")
else:
self.dropout_defense = False
self.dropout_ratio = regularization_strength
if "topkprune" in self.regularization_option:
self.topkprune = True
try:
self.topkprune_ratio = float(self.regularization_option.split("topkprune")[1].split("_")[0])
except:
self.topkprune_ratio = regularization_strength
print("Auto extract topkprune ratio fail, use regularization_strength input as topkprune ratio")
else:
self.topkprune = False
self.topkprune_ratio = regularization_strength
''' Activation Defense (end)'''
# client sampling: dividing datasets to actual number of clients, self.num_clients is fake num of clients for ease of simulation.
multiplier = 1/self.client_sample_ratio #100
actual_num_users = int(multiplier * self.num_client)
self.actual_num_users = actual_num_users
# setup dataset
if self.dataset == "cifar10":
self.client_dataloader, self.mem_trainloader, self.mem_testloader = get_cifar10_trainloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public,
data_portion=self.dataset_portion, noniid_ratio = self.noniid_ratio)
self.pub_dataloader, self.nomem_trainloader, self.nomem_testloader = get_cifar10_testloader(batch_size=self.batch_size,
num_workers=4,
shuffle=False)
self.orig_class = 10
elif self.dataset == "cifar100":
self.client_dataloader, self.mem_trainloader, self.mem_testloader = get_cifar100_trainloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public,
data_portion=self.dataset_portion, noniid_ratio = self.noniid_ratio)
self.pub_dataloader, self.nomem_trainloader, self.nomem_testloader = get_cifar100_testloader(batch_size=self.batch_size,
num_workers=4,
shuffle=False)
self.orig_class = 100
elif self.dataset == "svhn":
self.client_dataloader, self.mem_trainloader, self.mem_testloader = get_SVHN_trainloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public)
self.pub_dataloader, self.nomem_trainloader, self.nomem_testloader = get_SVHN_testloader(batch_size=self.batch_size,
num_workers=4,
shuffle=False)
self.orig_class = 10
elif self.dataset == "facescrub":
self.client_dataloader, self.pub_dataloader = get_facescrub_bothloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public)
self.orig_class = 530
elif self.dataset == "tinyimagenet":
self.client_dataloader, self.pub_dataloader = get_tinyimagenet_bothloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public)
self.orig_class = 200
elif self.dataset == "mnist":
self.client_dataloader, self.pub_dataloader = get_mnist_bothloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public)
self.orig_class = 10
elif self.dataset == "fmnist":
self.client_dataloader, self.pub_dataloader = get_fmnist_bothloader(batch_size=self.batch_size,
num_workers=4,
shuffle=True,
num_client=actual_num_users,
collude_use_public=self.collude_use_public)
self.orig_class = 10
else:
raise ("Dataset {} is not supported!".format(self.dataset))
self.num_class = self.orig_class
self.num_batches = len(self.client_dataloader[0])
print("Total number of batches per epoch for each client is ", self.num_batches)
self.model = None
# Initialze all client, server side models.
if "V" in self.scheme:
# V1, V2 initialize must be the same
if "V1" in self.scheme or "V2" in self.scheme:
self.initialize_different = False
if arch == "resnet20":
model = ResNet20(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "resnet32":
model = ResNet32(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg13":
model = vgg13(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg11":
model = vgg11(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg13_bn":
model = vgg13_bn(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg11_bn":
model = vgg11_bn(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "mobilenetv2":
model = MobileNetV2(cutting_layer, self.logger, num_client=self.num_client, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
else:
raise ("No such architecture!")
self.model = model
self.f = model.local_list[0]
if self.num_client > 1:
self.c = model.local_list[1]
self.f_tail = model.cloud
self.classifier = model.classifier
self.f.cuda()
self.f_tail.cuda()
self.classifier.cuda()
self.params = list(self.f_tail.parameters()) + list(self.classifier.parameters())
self.local_params = []
if cutting_layer > 0:
self.local_params.append(self.f.parameters())
for i in range(1, self.num_client):
self.model.local_list[i].cuda()
self.local_params.append(self.model.local_list[i].parameters())
else:
# If not V3, we set num_client to 1 when initializing the model, because there is only one version of local model.
if arch == "resnet20":
model = ResNet20(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "resnet32":
model = ResNet32(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg13":
model = vgg13(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg11":
model = vgg11(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg13_bn":
model = vgg13_bn(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "vgg11_bn":
model = vgg11_bn(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
elif arch == "mobilenetv2":
model = MobileNetV2(cutting_layer, self.logger, num_client=1, num_class=self.num_class,
initialize_different=self.initialize_different, adds_bottleneck=self.adds_bottleneck, bottleneck_option = self.bottleneck_option)
else:
raise ("No such architecture!")
self.model = model
self.f = model.local
self.c = self.f
for i in range(1, self.num_client):
self.model.local_list.append(self.f)
self.f_tail = model.cloud
self.classifier = model.classifier
self.f.cuda()
self.f_tail.cuda()
self.classifier.cuda()
self.params = list(self.f_tail.parameters()) + list(self.classifier.parameters())
self.local_params = []
if cutting_layer > 0:
self.local_params.append(self.f.parameters())
# setup optimizers
self.optimizer = torch.optim.SGD(self.params, lr=self.lr, momentum=0.9, weight_decay=5e-4)
milestones = [60, 120, 160]
if self.client_sample_ratio < 1.0:
multiplier = 1/self.client_sample_ratio
for i in range(len(milestones)):
milestones[i] = int(milestones[i] * multiplier)
self.local_optimizer_list = []
self.train_local_scheduler_list = []
self.warmup_local_scheduler_list = []
for i in range(len(self.local_params)):
self.local_optimizer_list.append(torch.optim.SGD(list(self.local_params[i]), lr=self.local_lr, momentum=0.9, weight_decay=5e-4))
self.train_local_scheduler_list.append(torch.optim.lr_scheduler.MultiStepLR(self.local_optimizer_list[i], milestones=milestones,
gamma=0.2)) # learning rate decay
self.warmup_local_scheduler_list.append(WarmUpLR(self.local_optimizer_list[i], self.num_batches * self.warm))
self.train_scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones=milestones,
gamma=0.2) # learning rate decay
self.warmup_scheduler = WarmUpLR(self.optimizer, self.num_batches * self.warm)
# Set up GAN_ADV
self.local_AE_list = []
self.gan_params = []
if self.gan_regularizer:
feature_size = self.model.get_smashed_data_size()
for i in range(self.num_client):
if self.gan_AE_type == "custom":
self.local_AE_list.append(
architectures.custom_AE(input_nc=feature_size[1], output_nc=3, input_dim=feature_size[2],
output_dim=32, activation=self.gan_AE_activation))
elif "conv_normN" in self.gan_AE_type:
try:
afterfix = self.gan_AE_type.split("conv_normN")[1]
N = int(afterfix.split("C")[0])
internal_C = int(afterfix.split("C")[1])
except:
print("auto extract N from conv_normN failed, set N to default 0")
N = 0
internal_C = 64
self.local_AE_list.append(architectures.conv_normN_AE(N = N, internal_nc = internal_C, input_nc=feature_size[1], output_nc=3,
input_dim=feature_size[2], output_dim=32,
activation=self.gan_AE_activation))
elif "res_normN" in self.gan_AE_type:
try:
afterfix = self.gan_AE_type.split("res_normN")[1]
N = int(afterfix.split("C")[0])
internal_C = int(afterfix.split("C")[1])
except:
print("auto extract N from res_normN failed, set N to default 0")
N = 0
internal_C = 64
self.local_AE_list.append(architectures.res_normN_AE(N = N, internal_nc = internal_C, input_nc=feature_size[1], output_nc=3,
input_dim=feature_size[2], output_dim=32,
activation=self.gan_AE_activation))
else:
raise ("No such GAN AE type.")
self.gan_params.append(self.local_AE_list[i].parameters())
self.local_AE_list[i].apply(init_weights)
self.local_AE_list[i].cuda()
self.gan_optimizer_list = []
self.gan_scheduler_list = []
milestones = [60, 120, 160]
if self.client_sample_ratio < 1.0:
multiplier = 1/self.client_sample_ratio
for i in range(len(milestones)):
milestones[i] = int(milestones[i] * multiplier)
for i in range(len(self.gan_params)):
self.gan_optimizer_list.append(torch.optim.Adam(list(self.gan_params[i]), lr=1e-3))
self.gan_scheduler_list.append(torch.optim.lr_scheduler.MultiStepLR(self.gan_optimizer_list[i], milestones=milestones,
gamma=self.gan_decay)) # learning rate decay
def optimizer_step(self, set_client = False, client_id = 0):
self.optimizer.step()
if set_client and len(self.local_optimizer_list) > client_id:
self.local_optimizer_list[client_id].step()
else:
for i in range(len(self.local_optimizer_list)):
self.local_optimizer_list[i].step()
def optimizer_zero_grad(self):
self.optimizer.zero_grad()
for i in range(len(self.local_optimizer_list)):
self.local_optimizer_list[i].zero_grad()
def scheduler_step(self, epoch = 0, warmup = False):
if warmup:
self.warmup_scheduler.step()
for i in range(len(self.warmup_local_scheduler_list)):
self.warmup_local_scheduler_list[i].step()
else:
self.train_scheduler.step(epoch)
for i in range(len(self.train_local_scheduler_list)):
self.train_local_scheduler_list[i].step(epoch)
def gan_scheduler_step(self, epoch = 0):
for i in range(len(self.gan_scheduler_list)):
self.gan_scheduler_list[i].step(epoch)
'''Main training function, the communication between client/server is implicit to keep a fast training speed'''
def train_target_step(self, x_private, label_private, client_id=0):
self.f_tail.train()
self.classifier.train()
if "V" in self.scheme:
self.model.local_list[client_id].train()
else:
self.f.train()
x_private = x_private.cuda()
label_private = label_private.cuda()
# Freeze batchnorm parameter of the client-side model.
if self.load_from_checkpoint and self.finetune_freeze_bn:
if client_id == 0:
freeze_model_bn(self.f)
elif client_id == 1:
freeze_model_bn(self.c)
else:
freeze_model_bn(self.model.local_list[client_id])
# Final Prediction Logits (complete forward pass)
if client_id == 0:
z_private = self.f(x_private)
elif client_id == 1:
z_private = self.c(x_private)
else:
z_private = self.model.local_list[client_id](x_private)
# Perform various activation defenses
if self.local_DP:
if "laplace" in self.regularization_option:
noise = torch.from_numpy(
np.random.laplace(loc=0, scale=1 / self.dp_epsilon, size=z_private.size())).cuda()
z_private = z_private + noise.detach().float()
else: # apply gaussian noise
delta = 10e-5
sigma = np.sqrt(2 * np.log(1.25 / delta)) * 1 / self.dp_epsilon
noise = sigma * torch.randn_like(z_private).cuda()
z_private = z_private + noise.detach().float()
if self.dropout_defense:
z_private = dropout_defense(z_private, self.dropout_ratio)
if self.topkprune:
z_private = prune_defense(z_private, self.topkprune_ratio)
if self.gan_noise:
epsilon = self.alpha2
self.local_AE_list[client_id].eval()
fake_act = z_private.clone()
grad = torch.zeros_like(z_private).cuda()
fake_act = torch.autograd.Variable(fake_act.cuda(), requires_grad=True)
x_recon = self.local_AE_list[client_id](fake_act)
x_private = denormalize(x_private, self.dataset)
if self.gan_loss_type == "SSIM":
ssim_loss = pytorch_ssim.SSIM()
loss = ssim_loss(x_recon, x_private)
loss.backward()
grad -= torch.sign(fake_act.grad)
elif self.gan_loss_type == "MSE":
mse_loss = torch.nn.MSELoss()
loss = mse_loss(x_recon, x_private)
loss.backward()
grad += torch.sign(fake_act.grad)
z_private = z_private - grad.detach() * epsilon
output = self.f_tail(z_private)
if "mobilenetv2" in self.arch:
output = F.avg_pool2d(output, 4)
output = output.view(output.size(0), -1)
output = self.classifier(output)
elif self.arch == "resnet20" or self.arch == "resnet32":
output = F.avg_pool2d(output, 8)
output = output.view(output.size(0), -1)
output = self.classifier(output)
else:
output = output.view(output.size(0), -1)
output = self.classifier(output)
criterion = torch.nn.CrossEntropyLoss()
f_loss = criterion(output, label_private)
total_loss = f_loss
# perform nopeek regularization
if self.nopeek:
#
if "ttitcombe" in self.regularization_option:
dc = DistanceCorrelationLoss()
dist_corr_loss = self.alpha1 * dc(x_private, z_private)
else:
dist_corr_loss = self.alpha1 * dist_corr(x_private, z_private).sum()
total_loss = total_loss + dist_corr_loss
# perform our proposed attacker-aware training
if self.gan_regularizer and not self.gan_noise:
self.local_AE_list[client_id].eval()
output_image = self.local_AE_list[client_id](z_private)
x_private = denormalize(x_private, self.dataset)
if self.gan_loss_type == "SSIM":
ssim_loss = pytorch_ssim.SSIM()
ssim_term = ssim_loss(output_image, x_private)
if self.ssim_threshold > 0.0:
if ssim_term > self.ssim_threshold:
gan_loss = self.alpha2 * (ssim_term - self.ssim_threshold) # Let SSIM approaches 0.4 to avoid overfitting
else:
gan_loss = 0.0 # Let SSIM approaches 0.4 to avoid overfitting
else:
gan_loss = self.alpha2 * ssim_term
elif self.gan_loss_type == "MSE":
mse_loss = torch.nn.MSELoss()
mse_term = mse_loss(output_image, x_private)
gan_loss = - self.alpha2 * mse_term
total_loss = total_loss + gan_loss
total_loss.backward()
total_losses = total_loss.detach().cpu().numpy()
f_losses = f_loss.detach().cpu().numpy()
del total_loss, f_loss
return total_losses, f_losses
# Main function for validation accuracy, is also used to get statistics
def validate_target(self, client_id=0):
"""
Run evaluation
"""
# batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
val_loader = self.pub_dataloader
# switch to evaluate mode
if client_id == 0:
self.f.eval()
elif client_id == 1:
self.c.eval()
elif client_id > 1:
self.model.local_list[client_id].eval()
self.f_tail.eval()
self.classifier.eval()
criterion = nn.CrossEntropyLoss()
activation_0 = {}
def get_activation_0(name):
def hook(model, input, output):
activation_0[name] = output.detach()
return hook
# with torch.no_grad():
# count = 0
# for name, m in self.model.cloud.named_modules():
# if attack_from_later_layer == count:
# m.register_forward_hook(get_activation_4("ACT-{}".format(name)))
# valid_key = "ACT-{}".format(name)
# break
# count += 1
# output = self.model.cloud(ir)
# ir = activation_4[valid_key]
for name, m in self.model.local_list[client_id].named_modules():
m.register_forward_hook(get_activation_0("ACT-client-{}-{}".format(name, str(m).split("(")[0])))
for name, m in self.f_tail.named_modules():
m.register_forward_hook(get_activation_0("ACT-server-{}-{}".format(name, str(m).split("(")[0])))
for i, (input, target) in enumerate(val_loader):
input = input.cuda()
target = target.cuda()
activation_0 = {}
# compute output
with torch.no_grad():
output = self.model.local_list[client_id](input)
# code for save the activation of cutlayer
if self.bhtsne:
self.save_activation_bhtsne(output, target, client_id)
exit()
'''Optional, Test validation performance with local_DP/dropout (apply DP during query)'''
if self.local_DP:
if "laplace" in self.regularization_option:
noise = torch.from_numpy(
np.random.laplace(loc=0, scale=1 / self.dp_epsilon, size=output.size())).cuda()
else: # apply gaussian noise
delta = 10e-5
sigma = np.sqrt(2 * np.log(1.25 / delta)) * 1 / self.dp_epsilon
noise = sigma * torch.randn_like(output).cuda()
output += noise
if self.dropout_defense:
output = dropout_defense(output, self.dropout_ratio)
if self.topkprune:
output = prune_defense(output, self.topkprune_ratio)
'''Optional, Test validation performance with gan_noise (apply gan_noise during query)'''
if self.gan_noise:
epsilon = self.alpha2
self.local_AE_list[client_id].eval()
fake_act = output.clone()
grad = torch.zeros_like(output).cuda()
fake_act = torch.autograd.Variable(fake_act.cuda(), requires_grad=True)
x_recon = self.local_AE_list[client_id](fake_act)
input = denormalize(input, self.dataset)
if self.gan_loss_type == "SSIM":
ssim_loss = pytorch_ssim.SSIM()
loss = ssim_loss(x_recon, input)
loss.backward()
grad -= torch.sign(fake_act.grad)
elif self.gan_loss_type == "MSE":
mse_loss = torch.nn.MSELoss()
loss = mse_loss(x_recon, input)
loss.backward()
grad += torch.sign(fake_act.grad)
output = output - grad.detach() * epsilon
with torch.no_grad():
output = self.f_tail(output)
if "mobilenetv2" in self.arch:
output = F.avg_pool2d(output, 4)
output = output.view(output.size(0), -1)
output = self.classifier(output)
elif self.arch == "resnet20" or self.arch == "resnet32":
output = F.avg_pool2d(output, 8)
output = output.view(output.size(0), -1)
output = self.classifier(output)
else:
output = output.view(output.size(0), -1)
output = self.classifier(output)
loss = criterion(output, target)
# Get statistics of server/client's per-layer activation
if i == 0:
try:
if not os.path.exists(self.save_dir):
os.makedirs(self.save_dir)
# setup tensorboard
if self.save_activation_tensor:
save_tensor_path = self.save_dir + "/saved_tensors"
if not os.path.isdir(save_tensor_path):
os.makedirs(save_tensor_path)
for key, value in activation_0.items():
if "client" in key:
self.writer.add_histogram("local_act/{}".format(key), value.clone().cpu().data.numpy(), i)
if self.save_activation_tensor:
np.save(save_tensor_path + "/{}_{}.npy".format(key, i), value.clone().cpu().data.numpy())
if "server" in key:
self.writer.add_histogram("server_act/{}".format(key), value.clone().cpu().data.numpy(), i)
if self.save_activation_tensor:
np.save(save_tensor_path + "/{}_{}.npy".format(key, i), value.clone().cpu().data.numpy())
for name, m in self.model.local_list[client_id].named_modules():
handle = m.register_forward_hook(get_activation_0("ACT-client-{}-{}".format(name, str(m).split("(")[0])))
handle.remove()
for name, m in self.f_tail.named_modules():
handle = m.register_forward_hook(get_activation_0("ACT-server-{}-{}".format(name, str(m).split("(")[0])))
handle.remove()
except:
print("something went wrong adding histogram, ignore it..")
output = output.float()
loss = loss.float()
# measure accuracy and record loss
# prec1 = accuracy(output.data, target, compress_V4shadowlabel=self.V4shadowlabel, num_client=self.num_client)[0] #If V4shadowlabel is activated, add one extra step to process output back to orig_class
prec1 = accuracy(output.data, target)[
0] # If V4shadowlabel is activated, add one extra step to process output back to orig_class
losses.update(loss.item(), input.size(0))
top1.update(prec1.item(), input.size(0))
# measure elapsed time
if i % 50 == 0:
self.logger.debug('Test (client-{0}):\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format(
client_id, loss=losses,
top1=top1))
for name, param in self.model.local_list[client_id].named_parameters():
self.writer.add_histogram("local_params/{}".format(name), param.clone().cpu().data.numpy(), 1)
for name, param in self.model.cloud.named_parameters():
self.writer.add_histogram("server_params/{}".format(name), param.clone().cpu().data.numpy(), 1)
self.logger.debug(' * Prec@1 {top1.avg:.3f}'
.format(top1=top1))
return top1.avg, losses.avg
# auto complete model's name, since we have many
def infer_path_list(self, path_to_infer):
split_list = path_to_infer.split("checkpoint_f")
first_part = split_list[0]
second_part = split_list[1]
model_path_list = []
for i in range(self.num_client):
if i == 0:
model_path_list.append(path_to_infer)
elif i == 1:
model_path_list.append(first_part + "checkpoint_c" + second_part)
else:
model_path_list.append(first_part + "checkpoint_local{}".format(i) + second_part)
return model_path_list
# resume all client and server model from checkpoint
def resume(self, model_path_f=None):
if model_path_f is None:
try:
if "V" in self.scheme:
checkpoint = torch.load(self.save_dir + "checkpoint_f_{}.tar".format(self.n_epochs))
model_path_list = self.infer_path_list(self.save_dir + "checkpoint_f_{}.tar".format(self.n_epochs))
else:
checkpoint = torch.load(self.save_dir + "checkpoint_{}.tar".format(self.n_epochs))
# model_path_list = self.infer_path_list(self.save_dir + "checkpoint_200.tar")
except:
print("No valid Checkpoint Found!")
return
else:
if "V" in self.scheme:
model_path_list = self.infer_path_list(model_path_f)
if "V" in self.scheme:
for i in range(self.num_client):
print("load client {}'s local".format(i))
checkpoint_i = torch.load(model_path_list[i])
self.model.local_list[i].cuda()
self.model.local_list[i].load_state_dict(checkpoint_i, strict = False)
else:
checkpoint = torch.load(model_path_f)
self.model.cuda()
self.model.load_state_dict(checkpoint, strict = False)
self.f = self.model.local
self.f.cuda()
try:
self.call_resume = True
print("load cloud")
checkpoint = torch.load(self.save_dir + "checkpoint_cloud_{}.tar".format(self.n_epochs))
self.f_tail.cuda()
self.f_tail.load_state_dict(checkpoint, strict = False)
print("load classifier")
checkpoint = torch.load(self.save_dir + "checkpoint_classifier_{}.tar".format(self.n_epochs))
self.classifier.cuda()
self.classifier.load_state_dict(checkpoint, strict = False)
except:
print("might be old style saving, load entire model")
checkpoint = torch.load(model_path_f)
self.model.cuda()
self.model.load_state_dict(checkpoint, strict = False)
self.call_resume = True
self.f = self.model.local
self.f.cuda()
self.f_tail = self.model.cloud
self.f_tail.cuda()
self.classifier = self.model.classifier
self.classifier.cuda()
# client-side model sync
def sync_client(self):
# update global weights
global_weights = average_weights(self.model.local_list)
# update global weights
for i in range(self.num_client):
self.model.local_list[i].load_state_dict(global_weights)
# decoder sync
def sync_decoder(self):
# update global weights
global_weights = average_weights(self.local_AE_list)
# update global weights
for i in range(self.num_client):
self.local_AE_list[i].load_state_dict(global_weights)
# train local inversion model
def gan_train_step(self, input_images, client_id, loss_type="SSIM"):
device = next(self.model.local_list[client_id].parameters()).device
input_images = input_images.to(device)
self.model.local_list[client_id].eval()
z_private = self.model.local_list[client_id](input_images)
self.local_AE_list[client_id].train()
x_private, z_private = Variable(input_images).to(device), Variable(z_private)
x_private = denormalize(x_private, self.dataset)
if self.gan_noise:
epsilon = self.alpha2
self.local_AE_list[client_id].eval()
fake_act = z_private.clone()
grad = torch.zeros_like(z_private).cuda()
fake_act = torch.autograd.Variable(fake_act.cuda(), requires_grad=True)
x_recon = self.local_AE_list[client_id](fake_act)
if loss_type == "SSIM":
ssim_loss = pytorch_ssim.SSIM()
loss = ssim_loss(x_recon, x_private)
loss.backward()
grad -= torch.sign(fake_act.grad)
elif loss_type == "MSE":
MSE_loss = torch.nn.MSELoss()
loss = MSE_loss(x_recon, x_private)
loss.backward()
grad += torch.sign(fake_act.grad)
else:
raise ("No such loss_type for gan train step")
z_private = z_private - grad.detach() * epsilon
self.local_AE_list[client_id].train()
output = self.local_AE_list[client_id](z_private.detach())
if loss_type == "SSIM":
ssim_loss = pytorch_ssim.SSIM()
loss = -ssim_loss(output, x_private)
elif loss_type == "MSE":
MSE_loss = torch.nn.MSELoss()
loss = MSE_loss(output, x_private)
else:
raise ("No such loss_type for gan train step")
for i in range(len(self.gan_optimizer_list)):
self.gan_optimizer_list[i].zero_grad()
loss.backward()
for i in range(len(self.gan_optimizer_list)):
self.gan_optimizer_list[i].step()
losses = loss.detach().cpu().numpy()
del loss
return losses
# Main function for controlling training and testing, soul of ResSFL
def __call__(self, log_frequency=500, verbose=False, progress_bar=True):
self.logger.debug("Model's smashed-data size is {}".format(str(self.model.get_smashed_data_size())))
best_avg_accu = 0.0
if not self.call_resume:
LOG = np.zeros((self.n_epochs * self.num_batches, self.num_client))
client_iterator_list = []
for client_id in range(self.num_client):