forked from SCLBD/BackdoorBench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blind.py
1677 lines (1364 loc) · 58.7 KB
/
blind.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
'''
Blind Backdoors in Deep Learning Models
this script is for blind attack
from https://github.com/ebagdasa/backdoors101
@inproceedings {bagdasaryan2020blind,
author = {Eugene Bagdasaryan and Vitaly Shmatikov},
title = {Blind Backdoors in Deep Learning Models},
booktitle = {30th {USENIX} Security Symposium ({USENIX} Security 21)},
year = {2021},
isbn = {978-1-939133-24-3},
pages = {1505--1521},
url = {https://www.usenix.org/conference/usenixsecurity21/presentation/bagdasaryan},
publisher = {{USENIX} Association},
month = aug,
}
basic structure:
1. config args, save_path, fix random seed
2. set the clean train data and clean test data
3. set the attack img transform and label transform
4. set the backdoor attack data and backdoor test data
5. set the device, model, criterion, optimizer, training schedule.
6. use the designed blind_loss to train a poisoned model
7. save the attack result for defense
Original code file license is as the end of this script
Note that for fairness issue, we apply the same total training epochs as all other attack methods. But for Blind, it may not be the best choice.
'''
import os
import sys
sys.path = ["./"] + sys.path
import numpy as np
import logging
import torch
import argparse
import time
import random
from tqdm import tqdm
from shutil import copyfile
from typing import *
from collections import defaultdict
from dataclasses import asdict
from typing import Dict
from dataclasses import dataclass
from typing import List
from torch import optim, nn
from torch.nn import Module
from torchvision.transforms import transforms, functional
import torchvision.transforms as transforms
from typing import Union
from attack.badnet import BadNet
from utils.backdoor_generate_poison_index import generate_poison_index_from_label_transform
from utils.aggregate_block.bd_attack_generate import bd_attack_label_trans_generate
from copy import deepcopy
from utils.aggregate_block.model_trainer_generate import generate_cls_model
from utils.aggregate_block.train_settings_generate import argparser_opt_scheduler, argparser_criterion
from utils.save_load_attack import save_attack_result
from utils.trainer_cls import all_acc, given_dataloader_test, \
plot_loss, plot_acc_like_metric, Metric_Aggregator, test_given_dataloader_on_mix
from utils.bd_dataset_v2 import prepro_cls_DatasetBD_v2, dataset_wrapper_with_transform
from torch.utils.data.dataloader import DataLoader
from utils.aggregate_block.bd_attack_generate import general_compose
from utils.aggregate_block.dataset_and_transform_generate import dataset_and_transform_generate
transform_to_image = transforms.ToPILImage()
transform_to_tensor = transforms.ToTensor()
ALL_TASKS = ['backdoor', 'normal', 'sentinet_evasion', # 'spectral_evasion',
'neural_cleanse', 'mask_norm', 'sums', 'neural_cleanse_part1']
class Params:
def __init__(
self,
**kwargs,
):
# Corresponds to the class module: tasks.mnist_task.MNISTTask
# See other tasks in the task folder.
self.task: str = 'MNIST'
self.current_time: Optional[str] = None
self.name: Optional[str] = None
self.commit: Optional[float] = None
self.random_seedOptional: Optional[int] = None
# training params
self.start_epoch: int = 1
self.epochs: Optional[int] = None
self.log_interval: int = 1000
# model arch is usually defined by the task
self.pretrained: bool = False
self.resume_model: Optional[str] = None
self.lr: Optional[float] = None
self.decay: Optional[float] = None
self.momentum: Optional[float] = None
self.optimizer: Optional[str] = None
self.scheduler: bool = False
self.scheduler_milestonesOptional: [List[int]] = None
# data
self.data_path: str = '.data/'
self.batch_size: int = 64
self.test_batch_size: int = 100
self.transform_train: bool = True
"Do not apply transformations to the training images."
self.max_batch_id: Optional[int] = None
"For large datasets stop training earlier."
self.input_shape = None
"No need to set, updated by the Task class."
# gradient shaping/DP params
self.dp: Optional[bool] = None
self.dp_clip: Optional[float] = None
self.dp_sigma: Optional[float] = None
# attack params
self.backdoor: bool = False
self.backdoor_label: int = 8
self.poisoning_proportion: float = 1.0 # backdoors proportion in backdoor loss
self.synthesizer: str = 'pattern'
self.backdoor_dynamic_position: bool = False
# losses to balance: `normal`, `backdoor`, `neural_cleanse`, `sentinet`,
# `backdoor_multi`.
self.loss_tasks: Optional[List[str]] = None
self.loss_balance: str = 'MGDA'
"loss_balancing: `fixed` or `MGDA`"
self.loss_threshold: Optional[float] = None
# approaches to balance losses with MGDA: `none`, `loss`,
# `loss+`, `l2`
self.mgda_normalize: Optional[str] = None
self.fixed_scales: Optional[Dict[str, float]] = None
# relabel images with poison_number
self.poison_images: Optional[List[int]] = None
self.poison_images_test: Optional[List[int]] = None
# optimizations:
self.alternating_attack: Optional[float] = None
self.clip_batch: Optional[float] = None
# Disable BatchNorm and Dropout
self.switch_to_eval: Optional[float] = None
# nc evasion
self.nc_p_norm: int = 1
# spectral evasion
self.spectral_similarity: 'str' = 'norm'
# logging
self.report_train_loss: bool = True
self.log: bool = False
self.tb: bool = False
self.save_model: Optional[bool] = None
self.save_on_epochs: Optional[List[int]] = None
self.save_scale_values: bool = False
self.print_memory_consumption: bool = False
self.save_timing: bool = False
self.timing_data = None
# Temporary storage for running values
self.running_losses = None
self.running_scales = None
# FL params
self.fl: bool = False
self.fl_no_models: int = 100
self.fl_local_epochs: int = 2
self.fl_total_participants: int = 80000
self.fl_eta: int = 1
self.fl_sample_dirichlet: bool = False
self.fl_dirichlet_alpha: Optional[float] = None
self.fl_diff_privacy: bool = False
self.fl_dp_clip: Optional[float] = None
self.fl_dp_noise: Optional[float] = None
# FL attack details. Set no adversaries to perform the attack:
self.fl_number_of_adversaries: int = 0
self.fl_single_epoch_attack: Optional[int] = None
self.fl_weight_scale: int = 1
self.__dict__.update(kwargs)
# enable logging anyways when saving statistics
if self.save_model or self.tb or self.save_timing or \
self.print_memory_consumption:
self.log = True
if self.log:
self.folder_path = f'saved_models/model_' \
f'{self.task}_{self.current_time}_{self.name}'
self.running_losses = defaultdict(list)
self.running_scales = defaultdict(list)
self.timing_data = defaultdict(list)
for t in self.loss_tasks:
if t not in ALL_TASKS:
raise ValueError(f'Task {t} is not part of the supported '
f'tasks: {ALL_TASKS}.')
def to_dict(self):
return asdict(self)
class Metric:
name: str
train: bool
plottable: bool = True
running_metric = None
main_metric_name = None
def __init__(self, name, train=False):
self.train = train
self.name = name
self.running_metric = defaultdict(list)
def __repr__(self):
metrics = self.get_value()
text = [f'{key}: {val:.2f}' for key, val in metrics.items()]
return f'{self.name}: ' + ','.join(text)
def compute_metric(self, outputs, labels) -> Dict[str, Any]:
raise NotImplemented
def accumulate_on_batch(self, outputs=None, labels=None):
current_metrics = self.compute_metric(outputs, labels)
for key, value in current_metrics.items():
self.running_metric[key].append(value)
def get_value(self) -> Dict[str, np.ndarray]:
metrics = dict()
for key, value in self.running_metric.items():
metrics[key] = np.mean(value)
return metrics
def get_main_metric_value(self):
if not self.main_metric_name:
raise ValueError(f'For metric {self.name} define '
f'attribute main_metric_name.')
metrics = self.get_value()
return metrics[self.main_metric_name]
def reset_metric(self):
self.running_metric = defaultdict(list)
def plot(self, tb_writer, step, tb_prefix=''):
if tb_writer is not None and self.plottable:
metrics = self.get_value()
for key, value in metrics.items():
tb_writer.add_scalar(tag=f'{tb_prefix}/{self.name}_{key}',
scalar_value=value,
global_step=step)
tb_writer.flush()
else:
return False
class AccuracyMetric(Metric):
def __init__(self, top_k=(1,)):
self.top_k = top_k
self.main_metric_name = 'Top-1'
super().__init__(name='Accuracy', train=False)
def compute_metric(self, outputs: torch.Tensor,
labels: torch.Tensor):
"""Computes the precision@k for the specified values of k"""
max_k = max(self.top_k)
batch_size = labels.shape[0]
_, pred = outputs.topk(max_k, 1, True, True)
pred = pred.t()
correct = pred.eq(labels.view(1, -1).expand_as(pred))
res = dict()
for k in self.top_k:
correct_k = correct[:k].view(-1).float().sum(0)
res[f'Top-{k}'] = (correct_k.mul_(100.0 / batch_size)).item()
return res
class TestLossMetric(Metric):
def __init__(self, criterion, train=False):
self.criterion = criterion
self.main_metric_name = 'value'
super().__init__(name='Loss', train=False)
def compute_metric(self, outputs: torch.Tensor,
labels: torch.Tensor, top_k=(1,)):
"""Computes the precision@k for the specified values of k"""
loss = self.criterion(outputs, labels)
return {'value': loss.mean().item()}
@dataclass
class Batch:
batch_id: int
inputs: torch.Tensor
labels: torch.Tensor
# For PIPA experiment we use this field to store identity label.
aux: torch.Tensor = None
def __post_init__(self):
self.batch_size = self.inputs.shape[0]
def to(self, device):
inputs = self.inputs.to(device)
labels = self.labels.to(device)
if self.aux is not None:
aux = self.aux.to(device)
else:
aux = None
return Batch(self.batch_id, inputs, labels, aux)
def clone(self):
inputs = self.inputs.clone()
labels = self.labels.clone()
if self.aux is not None:
aux = self.aux.clone()
else:
aux = None
return Batch(self.batch_id, inputs, labels, aux)
def clip(self, batch_size):
if batch_size is None:
return self
inputs = self.inputs[:batch_size]
labels = self.labels[:batch_size]
if self.aux is None:
aux = None
else:
aux = self.aux[:batch_size]
return Batch(self.batch_id, inputs, labels, aux)
class Task:
params: Params = None
train_dataset = None
test_dataset = None
train_loader = None
test_loader = None
classes = None
model: Module = None
optimizer: optim.Optimizer = None
criterion: Module = None
metrics: List[Metric] = None
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
"Generic normalization for input data."
input_shape: torch.Size = None
def __init__(self, params: Params):
self.params = params
self.init_task()
def init_task(self):
self.load_data()
self.model = self.build_model()
self.resume_model()
self.model = self.model.to(self.params.device)
self.optimizer, self.scheduler = argparser_opt_scheduler(self.model, self.params)
self.criterion = self.make_criterion()
self.metrics = [AccuracyMetric(), TestLossMetric(self.criterion)]
self.set_input_shape()
def load_data(self) -> None:
raise NotImplemented
def build_model(self) -> Module:
raise NotImplemented
def make_criterion(self) -> Module:
"""Initialize with Cross Entropy by default.
We use reduction `none` to support gradient shaping defense.
:return:
"""
return nn.CrossEntropyLoss(reduction='none')
def resume_model(self):
if self.params.resume_model:
logging.info(f'Resuming training from- {self.params.resume_model}')
loaded_params = torch.load(f"saved_models/"
f"{self.params.resume_model}",
map_location=torch.device('cpu'))
self.model.load_state_dict(loaded_params['state_dict'])
self.params.start_epoch = loaded_params['epoch']
self.params.lr = loaded_params.get('lr', self.params.lr)
logging.warning(f"Loaded parameters from- saved model: LR is"
f" {self.params.lr} and current epoch is"
f" {self.params.start_epoch}")
def set_input_shape(self):
inp = self.train_dataset[0][0]
self.params.input_shape = inp.shape
def get_batch(self, batch_id, data) -> Batch:
"""Process data into a batch.
Specific for different datasets and data loaders this method unifies
the output by returning the object of class Batch.
:param batch_id: id of the batch
:param data: object returned by the Loader.
:return:
"""
inputs, labels = data
batch = Batch(batch_id, inputs, labels)
return batch.to(self.params.device)
def accumulate_metrics(self, outputs, labels):
for metric in self.metrics:
metric.accumulate_on_batch(outputs, labels)
def reset_metrics(self):
for metric in self.metrics:
metric.reset_metric()
def report_metrics(self, step, prefix='',
tb_writer=None, tb_prefix='Metric/'):
metric_text = []
for metric in self.metrics:
metric_text.append(str(metric))
metric.plot(tb_writer, step, tb_prefix=tb_prefix)
logging.warning(f'{prefix} {step:4d}. {" | ".join(metric_text)}')
return self.metrics[0].get_main_metric_value()
@staticmethod
def get_batch_accuracy(outputs, labels, top_k=(1,)):
"""Computes the precision@k for the specified values of k"""
max_k = max(top_k)
batch_size = labels.size(0)
_, pred = outputs.topk(max_k, 1, True, True)
pred = pred.t()
correct = pred.eq(labels.view(1, -1).expand_as(pred))
res = []
for k in top_k:
correct_k = correct[:k].view(-1).float().sum(0)
res.append((correct_k.mul_(100.0 / batch_size)).item())
if len(res) == 1:
res = res[0]
return res
class Synthesizer:
params: Params
task: Task
def __init__(self, task: Task):
self.task = task
self.params = task.params
def make_backdoor_batch(self, batch: Batch, test=False, attack=True) -> Batch:
# Don't attack if only normal loss task.
if (not attack) or (self.params.loss_tasks == ['normal'] and not test):
return batch
if test:
attack_portion = batch.batch_size
else:
attack_portion = round(
batch.batch_size * self.params.poisoning_proportion)
backdoored_batch = batch.clone()
self.apply_backdoor(backdoored_batch, attack_portion)
return backdoored_batch
def apply_backdoor(self, batch, attack_portion):
"""
Modifies only a portion of the batch (represents batch poisoning).
:param batch:
:return:
"""
self.synthesize_inputs(batch=batch, attack_portion=attack_portion)
self.synthesize_labels(batch=batch, attack_portion=attack_portion)
return
def synthesize_inputs(self, batch, attack_portion=None):
raise NotImplemented
def synthesize_labels(self, batch, attack_portion=None):
raise NotImplemented
def record_time(params: Params, t=None, name=None):
if t and name and params.save_timing == name or params.save_timing is True:
torch.cuda.synchronize()
params.timing_data[name].append(round(1000 * (time.perf_counter() - t)))
def compute_normal_loss(params, model, criterion, inputs,
labels, grads):
t = time.perf_counter()
outputs = model(inputs)
record_time(params, t, 'forward')
loss = criterion(outputs, labels)
if not params.dp:
loss = loss.mean()
if grads:
t = time.perf_counter()
grads = list(torch.autograd.grad(loss.mean(),
[x for x in model.parameters() if
x.requires_grad],
retain_graph=True))
record_time(params, t, 'backward')
return loss, grads
def get_grads(params, model, loss):
t = time.perf_counter()
grads = list(torch.autograd.grad(loss.mean(),
[x for x in model.parameters() if
x.requires_grad],
retain_graph=True))
record_time(params, t, 'backward')
return grads
def th(vector):
return torch.tanh(vector) / 2 + 0.5
def norm_loss(params, model, grads=None):
if params.nc_p_norm == 1:
norm = torch.sum(th(model.mask))
elif params.nc_p_norm == 2:
norm = torch.norm(th(model.mask))
else:
raise ValueError('Not support mask norm.')
if grads:
grads = get_grads(params, model, norm)
model.zero_grad()
return norm, grads
def compute_backdoor_loss(params, model, criterion, inputs_back,
labels_back, grads=None):
t = time.perf_counter()
outputs = model(inputs_back)
record_time(params, t, 'forward')
loss = criterion(outputs, labels_back)
if params.task == 'Pipa':
loss[labels_back == 0] *= 0.001
if labels_back.sum().item() == 0.0:
loss[:] = 0.0
if not params.dp:
loss = loss.mean()
if grads:
grads = get_grads(params, model, loss)
return loss, grads
def compute_all_losses_and_grads(loss_tasks, attack, model, criterion,
batch, batch_back,
compute_grad=None):
grads = {}
loss_values = {}
for t in loss_tasks:
# if compute_grad:
# model.zero_grad()
if t == 'normal':
loss_values[t], grads[t] = compute_normal_loss(attack.params,
model,
criterion,
batch.inputs,
batch.labels,
grads=compute_grad)
elif t == 'backdoor':
loss_values[t], grads[t] = compute_backdoor_loss(attack.params,
model,
criterion,
batch_back.inputs,
batch_back.labels,
grads=compute_grad)
elif t == 'mask_norm':
loss_values[t], grads[t] = norm_loss(attack.params, attack.nc_model,
grads=compute_grad)
elif t == 'neural_cleanse_part1':
loss_values[t], grads[t] = compute_normal_loss(attack.params,
model,
criterion,
batch.inputs,
batch_back.labels,
grads=compute_grad,
)
return loss_values, grads
class Model(nn.Module):
"""
Base class for models with added support for GradCam activation map
and a SentiNet defense. The GradCam design is taken from:
https://medium.com/@stepanulyanin/implementing-grad-cam-in-pytorch-ea0937c31e82
If you are not planning to utilize SentiNet defense just import any model
you like for your tasks.
"""
def __init__(self):
super().__init__()
self.gradient = None
def activations_hook(self, grad):
self.gradient = grad
def get_gradient(self):
return self.gradient
def get_activations(self, x):
return self.features(x)
def switch_grads(self, enable=True):
for i, n in self.named_parameters():
n.requires_grad_(enable)
def features(self, x):
"""
Get latent representation, eg logit layer.
:param x:
:return:
"""
raise NotImplemented
def forward(self, x, latent=False):
raise NotImplemented
class Attack:
params: Params
synthesizer: Synthesizer
nc_model: Model
nc_optim: torch.optim.Optimizer
loss_hist = list()
# fixed_model: Model
def __init__(self, params, synthesizer):
self.params = params
self.synthesizer = synthesizer
def compute_blind_loss(self, model, criterion, batch, attack):
"""
:param model:
:param criterion:
:param batch:
:param attack: Do not attack at all. Ignore all the parameters
:return:
"""
batch = batch.clip(self.params.clip_batch)
loss_tasks = self.params.loss_tasks.copy() if attack else ['normal']
batch_back = self.synthesizer.make_backdoor_batch(batch, attack=attack)
scale = dict()
if self.params.loss_threshold and (np.mean(self.loss_hist) >= self.params.loss_threshold
or len(self.loss_hist) < self.params.batch_history_len):
loss_tasks = ['normal']
if len(loss_tasks) == 1:
loss_values, grads = compute_all_losses_and_grads(
loss_tasks,
self, model, criterion, batch, batch_back, compute_grad=False
)
elif self.params.loss_balance == 'MGDA':
loss_values, grads = compute_all_losses_and_grads(
loss_tasks,
self, model, criterion, batch, batch_back, compute_grad=True)
if len(loss_tasks) > 1:
scale = MGDASolver.get_scales(grads, loss_values,
self.params.mgda_normalize,
loss_tasks)
elif self.params.loss_balance == 'fixed':
loss_values, grads = compute_all_losses_and_grads(
loss_tasks,
self, model, criterion, batch, batch_back, compute_grad=False)
for t in loss_tasks:
scale[t] = self.params.fixed_scales[t]
else:
raise ValueError(f'Please choose between `MGDA` and `fixed`.')
if len(loss_tasks) == 1:
scale = {loss_tasks[0]: 1.0}
self.loss_hist.append(loss_values['normal'].item())
self.loss_hist = self.loss_hist[-1000:]
blind_loss = self.scale_losses(loss_tasks, loss_values, scale)
return blind_loss
def scale_losses(self, loss_tasks, loss_values, scale):
blind_loss = 0
for it, t in enumerate(loss_tasks):
self.params.running_losses[t].append(loss_values[t].item())
self.params.running_scales[t].append(scale[t])
if it == 0:
blind_loss = scale[t] * loss_values[t]
else:
blind_loss += scale[t] * loss_values[t]
self.params.running_losses['total'].append(blind_loss.item())
return blind_loss
# Credits to Ozan Sener
# https://github.com/intel-isl/MultiObjectiveOptimization
class MGDASolver:
MAX_ITER = 250
STOP_CRIT = 1e-5
@staticmethod
def _min_norm_element_from2(v1v1, v1v2, v2v2):
"""
Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2
d is the distance (objective) optimzed
v1v1 = <x1,x1>
v1v2 = <x1,x2>
v2v2 = <x2,x2>
"""
if v1v2 >= v1v1:
# Case: Fig 1, third column
gamma = 0.999
cost = v1v1
return gamma, cost
if v1v2 >= v2v2:
# Case: Fig 1, first column
gamma = 0.001
cost = v2v2
return gamma, cost
# Case: Fig 1, second column
gamma = -1.0 * ((v1v2 - v2v2) / (v1v1 + v2v2 - 2 * v1v2))
cost = v2v2 + gamma * (v1v2 - v2v2)
return gamma, cost
@staticmethod
def _min_norm_2d(vecs: list, dps):
"""
Find the minimum norm solution as combination of two points
This is correct only in 2D
ie. min_c |\sum c_i x_i|_2^2 st. \sum c_i = 1 , 1 >= c_1 >= 0
for all i, c_i + c_j = 1.0 for some i, j
"""
dmin = 1e8
sol = 0
for i in range(len(vecs)):
for j in range(i + 1, len(vecs)):
if (i, j) not in dps:
dps[(i, j)] = 0.0
for k in range(len(vecs[i])):
dps[(i, j)] += torch.dot(vecs[i][k].view(-1),
vecs[j][k].view(-1)).detach()
dps[(j, i)] = dps[(i, j)]
if (i, i) not in dps:
dps[(i, i)] = 0.0
for k in range(len(vecs[i])):
dps[(i, i)] += torch.dot(vecs[i][k].view(-1),
vecs[i][k].view(-1)).detach()
if (j, j) not in dps:
dps[(j, j)] = 0.0
for k in range(len(vecs[i])):
dps[(j, j)] += torch.dot(vecs[j][k].view(-1),
vecs[j][k].view(-1)).detach()
c, d = MGDASolver._min_norm_element_from2(dps[(i, i)],
dps[(i, j)],
dps[(j, j)])
if d < dmin:
dmin = d
sol = [(i, j), c, d]
return sol, dps
@staticmethod
def _projection2simplex(y):
"""
Given y, it solves argmin_z |y-z|_2 st \sum z = 1 , 1 >= z_i >= 0 for all i
"""
m = len(y)
sorted_y = np.flip(np.sort(y), axis=0)
tmpsum = 0.0
tmax_f = (np.sum(y) - 1.0) / m
for i in range(m - 1):
tmpsum += sorted_y[i]
tmax = (tmpsum - 1) / (i + 1.0)
if tmax > sorted_y[i + 1]:
tmax_f = tmax
break
return np.maximum(y - tmax_f, np.zeros(y.shape))
@staticmethod
def _next_point(cur_val, grad, n):
proj_grad = grad - (np.sum(grad) / n)
tm1 = -1.0 * cur_val[proj_grad < 0] / proj_grad[proj_grad < 0]
tm2 = (1.0 - cur_val[proj_grad > 0]) / (proj_grad[proj_grad > 0])
skippers = np.sum(tm1 < 1e-7) + np.sum(tm2 < 1e-7)
t = 1
if len(tm1[tm1 > 1e-7]) > 0:
t = np.min(tm1[tm1 > 1e-7])
if len(tm2[tm2 > 1e-7]) > 0:
t = min(t, np.min(tm2[tm2 > 1e-7]))
next_point = proj_grad * t + cur_val
next_point = MGDASolver._projection2simplex(next_point)
return next_point
@staticmethod
def find_min_norm_element(vecs: list):
"""
Given a list of vectors (vecs), this method finds the minimum norm
element in the convex hull as min |u|_2 st. u = \sum c_i vecs[i]
and \sum c_i = 1. It is quite geometric, and the main idea is the
fact that if d_{ij} = min |u|_2 st u = c x_i + (1-c) x_j; the solution
lies in (0, d_{i,j})Hence, we find the best 2-task solution , and
then run the projected gradient descent until convergence
"""
# Solution lying at the combination of two points
dps = {}
init_sol, dps = MGDASolver._min_norm_2d(vecs, dps)
n = len(vecs)
sol_vec = np.zeros(n)
sol_vec[init_sol[0][0]] = init_sol[1]
sol_vec[init_sol[0][1]] = 1 - init_sol[1]
if n < 3:
# This is optimal for n=2, so return the solution
return sol_vec, init_sol[2]
iter_count = 0
grad_mat = np.zeros((n, n))
for i in range(n):
for j in range(n):
grad_mat[i, j] = dps[(i, j)]
while iter_count < MGDASolver.MAX_ITER:
grad_dir = -1.0 * np.dot(grad_mat, sol_vec)
new_point = MGDASolver._next_point(sol_vec, grad_dir, n)
# Re-compute the inner products for line search
v1v1 = 0.0
v1v2 = 0.0
v2v2 = 0.0
for i in range(n):
for j in range(n):
v1v1 += sol_vec[i] * sol_vec[j] * dps[(i, j)]
v1v2 += sol_vec[i] * new_point[j] * dps[(i, j)]
v2v2 += new_point[i] * new_point[j] * dps[(i, j)]
nc, nd = MGDASolver._min_norm_element_from2(v1v1.item(),
v1v2.item(),
v2v2.item())
# try:
new_sol_vec = nc * sol_vec + (1 - nc) * new_point
# except AttributeError:
# logging.debug(sol_vec)
change = new_sol_vec - sol_vec
if np.sum(np.abs(change)) < MGDASolver.STOP_CRIT:
return sol_vec, nd
sol_vec = new_sol_vec
@staticmethod
def find_min_norm_element_FW(vecs):
"""
Given a list of vectors (vecs), this method finds the minimum norm
element in the convex hull
as min |u|_2 st. u = \sum c_i vecs[i] and \sum c_i = 1.
It is quite geometric, and the main idea is the fact that if
d_{ij} = min |u|_2 st u = c x_i + (1-c) x_j; the solution lies
in (0, d_{i,j})Hence, we find the best 2-task solution, and then
run the Frank Wolfe until convergence
"""
# Solution lying at the combination of two points
dps = {}
init_sol, dps = MGDASolver._min_norm_2d(vecs, dps)
n = len(vecs)
sol_vec = np.zeros(n)
sol_vec[init_sol[0][0]] = init_sol[1]
sol_vec[init_sol[0][1]] = 1 - init_sol[1]
if n < 3:
# This is optimal for n=2, so return the solution
return sol_vec, init_sol[2]
iter_count = 0
grad_mat = np.zeros((n, n))
for i in range(n):
for j in range(n):
grad_mat[i, j] = dps[(i, j)]
while iter_count < MGDASolver.MAX_ITER:
t_iter = np.argmin(np.dot(grad_mat, sol_vec))
v1v1 = np.dot(sol_vec, np.dot(grad_mat, sol_vec))
v1v2 = np.dot(sol_vec, grad_mat[:, t_iter])
v2v2 = grad_mat[t_iter, t_iter]
nc, nd = MGDASolver._min_norm_element_from2(v1v1, v1v2, v2v2)
new_sol_vec = nc * sol_vec
new_sol_vec[t_iter] += 1 - nc
change = new_sol_vec - sol_vec
if np.sum(np.abs(change)) < MGDASolver.STOP_CRIT:
return sol_vec, nd
sol_vec = new_sol_vec
@classmethod
def get_scales(cls, grads, losses, normalization_type, tasks):
scale = {}
gn = gradient_normalizers(grads, losses, normalization_type)
for t in tasks:
for gr_i in range(len(grads[t])):
grads[t][gr_i] = grads[t][gr_i] / (gn[t] + 1e-5)
sol, min_norm = cls.find_min_norm_element([grads[t] for t in tasks])
for zi, t in enumerate(tasks):
scale[t] = float(sol[zi])
return scale
def create_table(params: dict):
data = "| name | value | \n |-----|-----|"
for key, value in params.items():
data += '\n' + f"| {key} | {value} |"
return data
class PatternSynthesizer(Synthesizer):
pattern_tensor: torch.Tensor = torch.tensor([
[1., 0., 1.],
[-10., 1., -10.],
[-10., -10., 0.],
[-10., 1., -10.],
[1., 0., 1.]
])
"Just some random 2D pattern."
x_top = 3
"X coordinate to put the backdoor into."
y_top = 23
"Y coordinate to put the backdoor into."
mask_value = -10
"A tensor coordinate with this value won't be applied to the image."
resize_scale = (5, 10)
"If the pattern is dynamically placed, resize the pattern."
mask: torch.Tensor = None
"A mask used to combine backdoor pattern with the original image."
pattern: torch.Tensor = None
"A tensor of the `input.shape` filled with `mask_value` except backdoor."
def __init__(self, task: Task):
super().__init__(task)
self.make_pattern(self.pattern_tensor, self.x_top, self.y_top)
def make_pattern(self, pattern_tensor, x_top, y_top):
full_image = torch.zeros(self.params.input_shape)
full_image.fill_(self.mask_value)
x_bot = x_top + pattern_tensor.shape[0]
y_bot = y_top + pattern_tensor.shape[1]