-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.py
1761 lines (1526 loc) · 61.8 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import getpass
import json
import os
import sys
import time
from datetime import datetime
from enum import Enum
from typing import Dict
from typing import Optional
from typing import Union
from typing import List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from easydict import EasyDict as edict
from sklearn import metrics
from torch import Tensor
from torch.nn import DataParallel
from torch.optim import SGD, Adadelta, Adagrad, Adam, RMSprop
from torch.optim.lr_scheduler import MultiStepLR
# from torch.optim.lr_scheduler import OneCycleLR
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader, Subset, ConcatDataset
from torchvision import datasets, transforms
from datasets.svhn.svhn_utils import FromSVHNtoMNIST
from datasets.cifar.cifar_utils import get_cifar_private_data, get_cifar_dataset
from datasets.deprecated.coco.helper_functions.helper_functions import \
average_precision
from datasets.deprecated.coco.helper_functions.helper_functions import mAP
from datasets.mnist.mnist_utils import get_mnist_dataset, get_mnist_private_data
from datasets.mnist.mnist_utils import get_mnist_dataset_by_name
from datasets.mnist.mnist_utils import get_mnist_transforms
from datasets.svhn.svhn_utils import get_svhn_private_data
from datasets.imagenet.dataset_imagenet import get_imagenet_dataset
from models.private_model import get_private_model_by_id
from queryset import QuerySet
from queryset import get_aggregated_labels_filename
from queryset import get_targets_filename
from queryset import get_raw_queries_filename
from queryset import get_queries_filename
from general_utils.save_load import save_obj
from general_utils.functions import sigmoid
import random
import pickle
import socket
from pow.hashcash import mint_iteractive, generate_challenge, check, _to_binary
from ax.service.managed_loop import optimize # pip install ax-platform
class metric(Enum):
"""
Evaluation metrics for the models.
"""
acc = 'acc'
acc2 = 'acc2' # For fidelity accuracy
acc_detailed = 'acc_detailed'
acc_detailed_avg = 'acc_detailed_avg'
balanced_acc = 'balanced_acc'
balanced_acc_detailed = 'balanced_acc_detailed'
auc = 'auc'
auc_detailed = 'auc_detailed'
f1_score = 'f1_score'
f1_score_detailed = 'f1_score_detailed'
loss = 'loss'
test_loss = 'test_loss'
train_loss = 'train_loss'
map = 'map'
map_detailed = 'map_detailed'
gaps_mean = 'gaps_mean'
gaps_detailed = 'gaps_detailed'
pc = 'pc'
rc = 'rc'
fc = 'fc'
po = 'po'
ro = 'ro'
fo = 'fo'
def __str__(self):
return self.name
class result(Enum):
"""
Properties of the results.
"""
aggregated_labels = 'aggregated_labels'
indices_answered = 'indices_answered'
predictions = 'predictions'
labels_answered = 'labels_answered'
count_answered = 'count_answered'
def __str__(self):
return self.name
def get_device(args):
num_devices = torch.cuda.device_count()
device_ids = args.device_ids
if not torch.cuda.is_available():
return torch.device('cpu'), []
if num_devices < len(device_ids):
raise Exception(
'#available gpu : {} < --device_ids : {}'
.format(num_devices, len(device_ids)))
if args.cuda:
device = torch.device('cuda:{}'.format(device_ids[0]))
else:
device = torch.device('cpu')
return device, device_ids
def get_auc(classification_type, y_true, y_pred, num_classes=None):
"""
Compute the AUC (Area Under the receiver operator Curve).
:param classification_type: the type of classification.
:param y_true: the true labels.
:param y_pred: the scores or predicted labels.
:return: AUC score.
"""
if classification_type == 'binary':
# fpr, tpr, thresholds = metrics.roc_curve(
# y_true, y_pred, pos_label=1)
# auc = metrics.auc(fpr, tpr)
auc = metrics.roc_auc_score(
y_true=y_true,
y_score=y_pred,
average='weighted'
)
elif classification_type == 'multiclass':
auc = metrics.roc_auc_score(
y_true=y_true,
y_score=y_pred,
# one-vs-one, insensitive to class imbalances when average==macro
multi_class='ovo',
average='macro',
labels=[x for x in range(num_classes)]
)
else:
raise Exception(
f"Unexpected classification_type: {classification_type}.")
return auc
def get_prediction(args, model, unlabeled_dataloader):
initialized = False
with torch.no_grad():
for data, _ in unlabeled_dataloader:
if args.cuda:
data = data.cuda()
output = model(data)
if not initialized:
result = output
initialized = True
else:
result = torch.cat((result, output), 0)
return result
def get_predictionnet(args, model, unlabeled_dataloader):
"""Get predictions using a server client setup with POW on the server side."""
initialized = False
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
timequery = 0
start1 = time.time()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (HOST, PORT)
sock.connect(server_address)
end1 = time.time()
timequery+=end1-start1
try:
with torch.no_grad():
for data, _ in unlabeled_dataloader:
start1 = time.time()
datastr = pickle.dumps(data)
sock.sendall(datastr)
time.sleep(0.1)
str = "done"
sock.sendall(str.encode())
### POW Challenge
challenge = sock.recv(4096)
challenge = pickle.loads(challenge)
pos = challenge.find(":")
pos2 = challenge[pos+1:].find(":")
bits = challenge[pos+1:pos+pos2+1]
bits = int(bits)
xtype = 'bin'
stamp = mint_iteractive(challenge=challenge, bits=bits, xtype=xtype)
datastamp = pickle.dumps(stamp)
sock.sendall(datastamp)
#####
output = sock.recv(4096)
output = pickle.loads(output)
if not initialized:
result = output
initialized = True
else:
result = torch.cat((result, output), 0)
end1 = time.time()
timequery += end1-start1
start1 = time.time()
time.sleep(0.1)
str = "doneiter"
sock.sendall(str.encode())
end1 = time.time()
timequery += end1-start1
finally:
sock.close()
return result, timequery
def count_samples_per_class(dataloader):
steps = len(dataloader)
dataiter = iter(dataloader)
targets = []
for step in range(steps):
_, target = next(dataiter)
if isinstance(target, (int, float)):
targets.append(target)
else:
if isinstance(target, torch.Tensor):
target = target.detach().cpu().squeeze().squeeze().numpy()
targets += list(target)
targets = np.array(targets)
uniques = np.unique(targets)
counts = {u: 0 for u in uniques}
for u in targets:
counts[u] += 1
return counts
def get_timestamp():
dateTimeObj = datetime.now()
# timestampStr = dateTimeObj.strftime("%Y-%B-%d-(%H:%M:%S.%f)")
timestampStr = dateTimeObj.strftime("%Y-%m-%d-%H-%M-%S-%f")
return timestampStr
def get_cfg(cfg_path):
with open(cfg_path) as f:
cfg = edict(json.load(f))
user = getpass.getuser()
for k, v in cfg.items():
if '{user}' in str(v):
cfg[k] = v.replace('{user}', user)
return cfg
def lr_schedule(lr, lr_factor, epoch_now, lr_epochs):
"""
Learning rate schedule with respect to epoch
lr: float, initial learning rate
lr_factor: float, decreasing factor every epoch_lr
epoch_now: int, the current epoch
lr_epochs: list of int, decreasing every epoch in lr_epochs
return: lr, float, scheduled learning rate.
"""
count = 0
for epoch in lr_epochs:
if epoch_now >= epoch:
count += 1
continue
break
return lr * np.power(lr_factor, count)
def class_wise_loss_reweighting(beta, samples_per_cls):
"""
https://towardsdatascience.com/handling-class-imbalanced-data-using-a-loss-specifically-made-for-it-6e58fd65ffab
:param samples_per_cls: number of samples per class
:return: weights per class for the loss function
"""
num_classes = len(samples_per_cls)
effective_sample_count = 1.0 - np.power(beta, samples_per_cls)
weights = (1.0 - beta) / np.array(effective_sample_count)
# normalize the weights
weights = weights / np.sum(weights) * num_classes
return weights
def load_private_data_and_qap(args):
"""Load labeled private data and query-answer pairs for retraining private models."""
kwargs = get_kwargs(args=args)
args.kwargs = kwargs
if 'mnist' in args.dataset:
all_private_datasets = get_mnist_dataset(args=args, train=True)
private_dataset_size = len(all_private_datasets) // args.num_models
all_augmented_dataloaders = []
for i in range(args.num_querying_parties):
begin = i * private_dataset_size
if i == args.num_models - 1:
end = len(all_private_datasets)
else:
end = (i + 1) * private_dataset_size
indices = list(range(begin, end))
private_dataset = Subset(all_private_datasets, indices)
query_dataset = QuerySet(
args,
transform=get_mnist_transforms(args=args),
id=i)
augmented_dataset = ConcatDataset([private_dataset, query_dataset])
augmented_dataloader = DataLoader(augmented_dataset,
batch_size=args.batch_size,
shuffle=True, **kwargs)
all_augmented_dataloaders.append(augmented_dataloader)
return all_augmented_dataloaders
elif args.dataset == 'svhn':
trainset = datasets.SVHN(
root=args.dataset_path,
split='train',
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.43768212, 0.44376972, 0.47280444),
(
0.19803013, 0.20101563,
0.19703615))]),
download=True)
extraset = datasets.SVHN(
root=args.dataset_path,
split='extra',
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.42997558, 0.4283771, 0.44269393),
(0.19630221, 0.1978732, 0.19947216))]),
download=True)
private_trainset_size = len(trainset) // args.num_models
private_extraset_size = len(extraset) // args.num_models
all_augmented_dataloaders = []
for i in range(args.num_querying_parties):
train_begin = i * private_trainset_size
extra_begin = i * private_extraset_size
if i == args.num_models - 1:
train_end = len(trainset)
else:
train_end = (i + 1) * private_trainset_size
if i == args.num_models - 1:
extra_end = len(extraset)
else:
extra_end = (i + 1) * private_extraset_size
train_indices = list(range(train_begin, train_end))
extra_indices = list(range(extra_begin, extra_end))
private_trainset = Subset(trainset, train_indices)
private_extraset = Subset(extraset, extra_indices)
query_dataset = QuerySet(
args,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.45242317,
0.45249586,
0.46897715),
(0.21943446,
0.22656967,
0.22850613))]),
id=i)
augmented_dataset = ConcatDataset(
[private_trainset, private_extraset, query_dataset])
augmented_dataloader = DataLoader(augmented_dataset,
batch_size=args.batch_size,
shuffle=True, **kwargs)
all_augmented_dataloaders.append(augmented_dataloader)
return all_augmented_dataloaders
elif args.dataset.startswith('cifar'):
if args.dataset == 'cifar10':
datasets_cifar = datasets.CIFAR10
elif args.dataset == 'cifar100':
datasets_cifar = datasets.CIFAR100
else:
raise Exception(args.datasets_exception)
all_private_datasets = datasets_cifar(
args.dataset_path,
train=True,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((
0.49139969,
0.48215842,
0.44653093),
(
0.24703223,
0.24348513,
0.26158784))]),
download=True)
private_dataset_size = len(all_private_datasets) // args.num_models
all_augmented_dataloaders = []
for i in range(args.num_querying_parties):
begin = i * private_dataset_size
if i == args.num_models - 1:
end = len(all_private_datasets)
else:
end = (i + 1) * private_dataset_size
indices = list(range(begin, end))
private_dataset = Subset(all_private_datasets, indices)
query_dataset = QuerySet(
args,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.49421429,
0.4851314,
0.45040911),
(0.24665252,
0.24289226,
0.26159238))]),
id=i)
augmented_dataset = ConcatDataset([private_dataset, query_dataset])
augmented_dataloader = DataLoader(augmented_dataset,
batch_size=args.batch_size,
shuffle=True, **kwargs)
all_augmented_dataloaders.append(augmented_dataloader)
return all_augmented_dataloaders
else:
raise Exception(args.datasets_exception)
def get_data_subset(args, dataset, indices):
"""
The Subset function differs between datasets, unfortunately.
:param args: program params
:param dataset: extract subset of the data from this dataset
:param indices: the indices in the dataset to be accessed
:return: the subset
"""
return Subset(dataset=dataset, indices=indices)
def save_raw_queries_targets(args, dataset, indices, name):
kwargs = get_kwargs(args=args)
query_dataset = get_data_subset(args=args, dataset=dataset, indices=indices)
queryloader = DataLoader(query_dataset, batch_size=args.batch_size,
shuffle=False, **kwargs)
all_samples = []
all_targets = []
for data, targets in queryloader:
all_samples.append(data.numpy())
all_targets.append(targets.numpy())
all_samples = np.concatenate(all_samples, axis=0).transpose(0, 2, 3, 1)
assert len(all_samples.shape) == 4 and all_samples.shape[0] == len(indices)
all_samples = (all_samples * 255).astype(np.uint8)
if ('mnist' in args.dataset):
all_samples = np.squeeze(all_samples)
shape_len = 3
else:
shape_len = 4
assert len(all_samples.shape) == shape_len
filename = get_raw_queries_filename(name=name, args=args)
filepath = os.path.join(args.ensemble_model_path, filename)
np.save(filepath, all_samples)
save_targets(name=name, args=args, targets=all_targets)
def save_targets(args, name, targets):
targets = np.concatenate(targets, axis=0)
filename = get_targets_filename(name=name, args=args)
filepath = os.path.join(args.ensemble_model_path, filename)
np.save(filepath, targets)
def save_queries(args, dataset, indices, name):
# Select the query items (data points that) given by indices.
query_dataset = get_data_subset(args=args, dataset=dataset, indices=indices)
kwargs = get_kwargs(args=args)
queryloader = DataLoader(query_dataset, batch_size=args.batch_size,
shuffle=False, **kwargs)
all_samples = []
all_targets = []
for data, targets in queryloader:
all_samples.append(data.numpy())
all_targets.append(targets.numpy())
all_samples = np.concatenate(all_samples, axis=0)
assert len(all_samples.shape) == 4 and all_samples.shape[0] == len(indices)
if 'mnist' in args.dataset:
all_samples = np.squeeze(all_samples)
shape_len = 3
else:
shape_len = 4
assert len(all_samples.shape) == shape_len
filename = get_queries_filename(name=name, args=args)
filepath = os.path.join(args.ensemble_model_path, filename)
np.save(filepath, all_samples)
save_targets(name=name, args=args, targets=all_targets)
def get_all_targets(dataloader) -> Optional[Tensor]:
dataset = dataloader.dataset
dataset_len = len(dataset)
all_targets = None
with torch.no_grad():
end = 0
for _, targets in dataloader:
batch_size = targets.shape[0]
begin = end
end = begin + batch_size
if all_targets is None:
if len(targets.shape) == 1:
all_targets = torch.zeros(dataset_len)
if len(targets.shape) == 2:
num_labels = targets.shape[1]
all_targets = torch.zeros((dataset_len, num_labels))
else:
raise Exception(f"Unknown setting with the shape of "
f"targets: {targets.shape}.")
all_targets[begin:end] += targets
return all_targets
def load_private_data(args):
"""Load labeled private data for training private models."""
kwargs = get_kwargs(args=args)
args.kwargs = kwargs
if args.dataset in ['mnist', 'fashion-mnist']:
return get_mnist_private_data(args=args)
elif args.dataset == 'svhn':
return get_svhn_private_data(args=args)
elif args.dataset.startswith('cifar'):
return get_cifar_private_data(args=args)
# return get_cxpert_debug_dataloaders(args=args)
else:
raise Exception(args.datasets_exception)
def load_ordered_unlabeled_data(args, indices, unlabeled_dataset):
"""Load unlabeled private data according to a specific order."""
args.kwargs = get_kwargs(args=args)
# A part of the original testset is loaded according to a specific order.
unlabeled_dataset = Subset(unlabeled_dataset, indices)
unlabeled_dataloader = DataLoader(
unlabeled_dataset,
batch_size=args.batch_size,
shuffle=False,
**args.kwargs)
return unlabeled_dataloader
def get_non_trained_set(args):
"""
This is a previous approach where the unlabeled and test data together
were kept together. However, it was too entangled.
:param args:
:return:
"""
if 'mnist' in args.dataset:
dataset = get_mnist_dataset(args=args, train=False)
elif args.dataset == 'svhn':
dataset = datasets.SVHN(
root=args.dataset_path,
split='test',
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.45242317, 0.45249586, 0.46897715),
(0.21943446, 0.22656967, 0.22850613))]),
download=True)
elif args.dataset.startswith('cifar'):
if args.dataset == 'cifar10':
datasets_cifar = datasets.CIFAR10
elif args.dataset == 'cifar100':
datasets_cifar = datasets.CIFAR100
else:
raise Exception(args.datasets_exception)
dataset = datasets_cifar(
root=args.dataset_path,
train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.49421429, 0.4851314, 0.45040911),
(0.24665252, 0.24289226,
0.26159238))]),
download=True)
elif args.dataset == "imagenet":
dataset = get_imagenet_dataset(args=args, split = 'val')
else:
raise Exception(args.datasets_exception)
return dataset
def get_test_set(args):
"""
Get the REAL test set. This keeps the unlabeled and test data separately.
:param args:
:return: only the test data.
"""
non_trained_set = get_non_trained_set(args=args)
if args.attacker_dataset == args.dataset:
start = args.num_unlabeled_samples
else:
# TODO: this number is temporary (for mnist victim model only)
if args.dataset == "mnist":
start = 0 # 9000
else:
start = args.num_unlabeled_samples
if args.dataset == "imagenet":
end = len(non_trained_set)
indices = random.sample(range(0, end), end-start) #Could be some overlap between indices for querying.
#indices = random.sample(range(0, end), 10000) # 10000 test elements. Use this when using training set for queries.
return Subset(dataset=non_trained_set, # Dont need test set at the moment. Querying happens from get_unlabeled_set
indices=indices)
#print("END", end) 50000
else:
end = len(non_trained_set)
assert end > start
return Subset(dataset=non_trained_set, indices=list(range(start, end)))
def get_unlabeled_set(args): # MODIFIED
"""
Get the REAL unlabeled set.
:param args:
:return: only the unlabeled data.
"""
if args.dataset == 'mnist':
end = args.num_unlabeled_samples
# print(args.num_unlabeled_samples)
dataset = get_mnist_dataset(args=args, train=True)
subset = Subset(dataset,
list(range(50000,
50000 + end))) # Querying from mnist training set.
elif args.dataset == "imagenet": # Need to randomly select because the items are in order
non_trained_set = get_non_trained_set(args=args)
start = 0
end = len(non_trained_set)
#indices = random.sample(range(start, end), args.num_unlabeled_samples)
subset = Subset(dataset=non_trained_set,
indices=list(range(start, end))) # Full test set for querying
else:
non_trained_set = get_non_trained_set(args=args)
start = 0
end = args.num_unlabeled_samples
assert end > start
subset = Subset(dataset=non_trained_set, indices=list(range(start, end)))
# print(len(subset))
assert len(subset) == args.num_unlabeled_samples
return subset
def get_attacker_dataset(args, dataset_name):
data_dir = args.data_dir
if 'mnist' in dataset_name:
dataset = get_mnist_dataset_by_name(args, dataset_name, train=False)
elif dataset_name == 'svhn':
svhn_transforms = []
if 'mnist' in args.dataset:
# Transform SVHN images from the RGB to L - gray-scale 8 bit images.
svhn_transforms.append(FromSVHNtoMNIST())
svhn_transforms.append(transforms.ToTensor())
# Normalize with the mean and std found for the new images.
# This closely corresponds to the mean and std of the standard
# values of mean and std for SVHN.
svhn_transforms.append(
transforms.Normalize((0.45771828,), (0.21816934,)))
svhn_transforms.append(transforms.RandomCrop((28, 28)))
else:
svhn_transforms.append(transforms.ToTensor())
svhn_transforms.append(transforms.Normalize(
(0.45242317, 0.45249586, 0.46897715),
(0.21943446, 0.22656967, 0.22850613)))
dataset_path = os.path.join(data_dir, 'SVHN')
dataset = datasets.SVHN(
root=dataset_path,
split='test',
transform=transforms.Compose(svhn_transforms),
download=True)
elif dataset_name.startswith('cifar'):
# if dataset_name == 'cifar10':
# datasets_cifar = datasets.CIFAR10
# dataset_path = os.path.join(args.path, 'CIFAR10')
# elif dataset_name == 'cifar100':
# datasets_cifar = datasets.CIFAR100
# dataset_path = os.path.join(args.path, 'CIFAR100')
# else:
# raise Exception(args.datasets_exception)
# dataset = datasets_cifar(
# root=dataset_path,
# train=False,
# transform=transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize(
# (0.49421429, 0.4851314, 0.45040911),
# (0.24665252, 0.24289226,
# 0.26159238))]),
# download=True)
dataset = get_cifar_dataset(args)
elif dataset_name == 'tinyimages':
from datasets.cifar.tinyimage500k import get_extra_cifar10_data_from_ti
dataset = get_extra_cifar10_data_from_ti(args=args)
elif dataset_name == 'imagenet':
dataset = get_imagenet_dataset(args=args)
else:
raise Exception(args.datasets_exception)
return dataset
def get_unlabeled_standard_indices(args):
"""
Get the indices for each querying party from the test data.
:param args: arguments
:return: indices for each querying party
"""
data_indices = [[] for _ in args.querying_parties]
num_querying_parties = len(args.querying_parties)
# Only a part of the original test set is used for the query selection.
size = args.num_unlabeled_samples // num_querying_parties
for i in range(num_querying_parties):
begin = i * size
# Is it the last querying party?
if i == num_querying_parties - 1:
end = args.num_unlabeled_samples
else:
end = (i + 1) * size
indices = list(range(begin, end))
data_indices[i] = indices
return data_indices
def get_unlabeled_indices(args, dataset):
data_indices = get_unlabeled_standard_indices(args=args)
num_querying_parties = len(args.querying_parties)
# Test correctness of the computed indices by summations.
assert sum(
[len(data_indices[i]) for i in
range(num_querying_parties)]) == args.num_unlabeled_samples
assert len(
set(np.concatenate(data_indices, axis=0))) == args.num_unlabeled_samples
return data_indices
def load_unlabeled_dataloaders(args, unlabeled_dataset=None):
"""
Load unlabeled private data for query selection.
:return: all_unlabeled_dataloaders data loaders for each querying party
"""
kwargs = get_kwargs(args=args)
all_unlabeled_dataloaders = []
if unlabeled_dataset is None:
unlabeled_dataset = get_unlabeled_set(args=args)
unlabeled_indices = get_unlabeled_indices(args=args,
dataset=unlabeled_dataset)
# Create data loaders.
for indices in unlabeled_indices:
unlabeled_dataset = Subset(unlabeled_dataset, indices)
unlabeled_dataloader = DataLoader(
unlabeled_dataset,
batch_size=args.batch_size,
shuffle=False, **kwargs)
all_unlabeled_dataloaders.append(unlabeled_dataloader)
return all_unlabeled_dataloaders
def get_kwargs(args):
kwargs = {'num_workers': args.num_workers,
'pin_memory': True} if args.cuda else {}
return kwargs
def load_training_data(args):
"""Load labeled data for training non-private baseline models."""
kwargs = get_kwargs(args=args)
if 'mnist' in args.dataset:
trainset = get_mnist_dataset(args=args, train=True)
trainloader = DataLoader(trainset, batch_size=args.batch_size,
shuffle=True, **kwargs)
elif args.dataset == 'svhn':
trainset = datasets.SVHN(root=args.dataset_path,
split='train',
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.43768212, 0.44376972, 0.47280444),
(
0.19803013, 0.20101563,
0.19703615))]),
download=True)
# extraset = datasets.SVHN(root=args.dataset_path,
# split='extra',
# transform=transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize(
# (0.42997558, 0.4283771, 0.44269393),
# (0.19630221, 0.1978732, 0.19947216))]),
# download=True)
# trainloader = DataLoader(ConcatDataset([trainset, extraset]),
# batch_size=args.batch_size, shuffle=True,
# **kwargs)
trainloader = DataLoader(trainset,
batch_size=args.batch_size, shuffle=True,
**kwargs)
elif args.dataset.startswith('cifar'):
if args.dataset == 'cifar10':
datasets_cifar = datasets.CIFAR10
elif args.dataset == 'cifar100':
datasets_cifar = datasets.CIFAR100
else:
raise Exception(args.datasets_exception)
trainset = datasets_cifar(
args.dataset_path,
train=True,
transform=transforms.Compose([
transforms.Pad(4),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(
(0.49139969,
0.48215842,
0.44653093),
(0.24703223,
0.24348513,
0.26158784))]),
download=True)
trainloader = DataLoader(trainset, batch_size=args.batch_size,
shuffle=True, **kwargs)
elif args.dataset == "imagenet":
trainset = get_imagenet_dataset(args=args, split = 'train')
end = len(trainset)
indices = random.sample(range(0, end), 10000)
#train_set = Subset(dataset=trainset, indices=list(range(end-10000, end)))
train_set = Subset(dataset=trainset,
indices=indices)
trainloader = DataLoader(train_set, batch_size=args.batch_size,
shuffle=True, **kwargs)
else:
raise Exception(args.datasets_exception)
return trainloader
def load_evaluation_dataloader(args): # Modified
"""Load labeled data for evaluation."""
kwargs = get_kwargs(args=args)
dataset = get_test_set(args=args)
evalloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False,
**kwargs)
return evalloader
def load_unlabeled_dataloader(args):
"""Load all unlabeled data."""
kwargs = get_kwargs(args=args)
dataset = get_unlabeled_set(args=args)
unlabeled_loader = DataLoader(dataset, batch_size=args.batch_size,
shuffle=False,
**kwargs)
return unlabeled_loader
def get_unlabled_last_index(
num_unlabeled_samples,
len_dataset,
len_class):
"""
For example, for CIFAR100 we have len_dataset 10000 for test data.
The number of samples per class is 1000.
If we want 9000 unlabeled samples then the ratio_unlabeled is 9/10.
The number of samples per class for the unlabeled dataset is 9/10*100=90.
If the number of samples for the final test is 1000 samples and we have 100
classes, then the number of samples per class will be 10 (only).
:param num_unlabeled_samples: number of unlabeled samples from the test set
:param len_dataset: the total number of samples in the intial test set
:param len_class: the number of samples for a given class
:return: for the array of sample indices for the class, the last index for
the unlabeled part
>>> num_unlabeled_samples = 9000
>>> len_dataset = 10000
>>> len_class = 100
>>> result = get_unlabled_last_index(num_unlabeled_samples=num_unlabeled_samples, len_dataset=len_dataset, len_class=len_class)
>>> assert result == 90
>>> # print('result: ', result)
"""
ratio_unlabeled = num_unlabeled_samples / len_dataset
last_unlabeled_index = int(ratio_unlabeled * len_class)
return last_unlabeled_index
def regularize_loss(model):
loss = 0
for param in list(model.children())[0].parameters():
loss += 2e-5 * torch.sum(torch.abs(param))
return loss
def get_loss_criterion(model, args):
"""
Get the loss criterion.
:param model: model
:param args: arguments
:return: the loss criterion (function like to be called)
"""
if args.loss_type == 'MSE':
criterion = nn.MSELoss()
elif args.loss_type == 'BCE':
criterion = nn.BCELoss()
elif args.loss_type == 'BCEWithLogits':
criterion = nn.BCEWithLogitsLoss()
elif args.loss_type == 'CE':
criterion = nn.CrossEntropyLoss()
else:
raise Exception(f"Unknown loss type: {args.loss_type}.")
return criterion
def pure_model(model):
"""
Extract the proper model if enclosed in DataParallel (distributed model
feature).
:param model: a model
:return: pure PyTorch model
"""
if hasattr(model, 'module'):
return model.module
else:
return model
def task_loss(target, output, criterion, weights):
"""
Compute the loss per task / label.
:param target: target labels
:param output: predicted labels
:param criterion: loss criterion
:param weights: the weight per task / label
:return: the computed loss
"""
loss = torch.zeros(1).to(output.device).to(torch.float32)
for task in range(target.shape[1]):
task_output = output[:, task]
task_target = target[:, task]
mask = ~torch.isnan(task_target)
task_output = task_output[mask]
task_target = task_target[mask]
if len(task_target) > 0:
task_loss = criterion(task_output.float(), task_target.float())
if weights is None:
loss += task_loss
else:
loss += weights[task] * task_loss
return loss
def compute_loss(target, output, criterion, weights, args, model, data):
"""
Compute the loss.
:param target: target labels
:param output: predicted labels
:param criterion: loss criterion
:param weights: the weight per task / label