-
Notifications
You must be signed in to change notification settings - Fork 0
/
adversarial.py
154 lines (128 loc) · 6.1 KB
/
adversarial.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
# coding: utf-8
import torch
from my_utils import clamp
import torch.nn as nn
class FGM(nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
self.backup = {}
def attack(self, epsilon=1., emb_name="roberta.embeddings.word_embeddings"):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
self.backup[name] = param.data.clone()
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
r_at = epsilon * param.grad / norm
param.data.add_(r_at)
def restore(self, emb_name="roberta.embeddings.word_embeddings"):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
assert name in self.backup
param.data = self.backup[name]
self.backup = {}
def forward(self ,input_ids,attention_mask,labels):
out=self.model(input_ids=input_ids,attention_mask=attention_mask,labels=labels)
return self.model(input_ids=input_ids,attention_mask=attention_mask,labels=labels)
class PGD():
def __init__(self, model):
self.model = model
self.emb_backup = {}
self.grad_backup = {}
def attack(self, epsilon=1., alpha=0.3, emb_name='embedding', is_first_attack=False):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
if is_first_attack:
self.emb_backup[name] = param.data.clone()
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
r_at = alpha * param.grad / norm
param.data.add_(r_at)
param.data = self.project(name, param.data, epsilon)
def restore(self, emb_name='embedding'):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
assert name in self.emb_backup
param.data = self.emb_backup[name]
self.emb_backup = {}
def project(self, param_name, param_data, epsilon):
r = param_data - self.emb_backup[param_name]
if torch.norm(r) > epsilon:
r = epsilon * r / torch.norm(r)
return param_data + r
def backup_grad(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
self.grad_backup[name] = param.grad
def restore_grad(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
param.grad = self.grad_backup[name]
"""
class FreeAT1(): # 局部Embedding
def __init__(self, model):
self.model = model
def attack(self, epsilon=1., delta=None):
grad = delta.grad.detach()
norm = torch.norm(grad)
if norm != 0 and not torch.isnan(norm):
delta.data = clamp(delta + epsilon * grad / norm, torch.tensor((-epsilon)).cuda(),
torch.tensor((epsilon)).cuda())
return delta
class FGSM1(): # 局部Embedding
def __init__(self, model):
self.model = model
def attack(self, is_first_attack=False, delta=None):
# emb_name这个参数要换成你模型中embedding的参数名
if is_first_attack:
delta.uniform_(-1.0, 1.0)
delta.requires_grad = True
else:
grad = delta.grad.detach()
norm = torch.norm(grad)
if norm != 0 and not torch.isnan(norm):
delta.data = clamp(delta + 0.3 * grad / norm, torch.tensor((-1.0)).cuda(), torch.tensor((1.0)).cuda())
delta = delta.detach()
return delta
class FGSM2(): # 全局Embedding
def __init__(self, model):
self.model = model
self.backup = {}
def attack(self, epsilon=1., alpha=0.3, emb_name='embedding', is_first_attack=False):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
if is_first_attack:
self.backup[name] = param.data.clone()
delta = torch.zeros_like(param.data).cuda()
delta.uniform_(-epsilon, epsilon)
param.data.add_(delta)
else:
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
delta = clamp(0.3 * param.grad / norm, torch.tensor((-1.0)).cuda(), torch.tensor((1.0)).cuda())
param.data.add_(delta)
def restore(self, emb_name='embedding'):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
assert name in self.backup
param.data = self.backup[name]
self.backup = {}
class FreeAT2(): # 全局Embedding
def __init__(self, model):
self.model = model
def attack(self, epsilon=1., emb_name='embedding'):
# emb_name这个参数要换成你模型中embedding的参数名
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
r_at = clamp(epsilon * param.grad / norm, torch.tensor((-epsilon)).cuda(),
torch.tensor((epsilon)).cuda())
param.data.add_(r_at)
"""