-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathworker.py
197 lines (146 loc) · 4.99 KB
/
worker.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
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from scipy.stats import entropy
from numpy.linalg import norm
import os
import copy
def to_img(x):
x = x.clamp(0, 1)
return x
class AEDetector:
def __init__(self, model, device, path, p=1):
"""
Error based detector.
Marks examples for filtering decisions.
model : pytorch model class
device : torch.device
path: Path to the autoencoder used.
p: Distance measure to use.
"""
self.model = model
self.model.load_state_dict(torch.load(path))
self.path = path
self.p = p
self.device = device
self.model = self.model.to(self.device)
self.model.eval()
def mark(self, X):
if torch.is_tensor(X):
X_torch = X
else :
X_torch = torch.from_numpy(X)
diff = torch.abs(X_torch -
self.model(X_torch.to(self.device)).detach().cpu())
marks = torch.mean(torch.pow(diff, self.p), dim = (1,2,3))
return marks
def print(self):
return "AEDetector:" + self.path.split("/")[-1]
class IdReformer:
def __init__(self, path="IdentityFunction"):
"""
Identity reformer.
Reforms an example to itself.
"""
self.path = path
self.heal = lambda X: X
def print(self):
return "IdReformer:" + self.path
class SimpleReformer:
def __init__(self, model, device, path):
"""
Reformer.
Reforms examples with autoencoder. Action of reforming is called heal.
path: Path to the autoencoder used.
"""
self.model = model
self.model.load_state_dict(torch.load(path))
#self.model = load_model(path)
self.path = path
self.device = device
self.model = self.model.to(self.device)
self.model.eval()
def heal(self, X):
#X = self.model.predict(X)
#return np.clip(X, 0.0, 1.0)
if torch.is_tensor(X):
X_torch = X
else :
X_torch = torch.from_numpy(X)
X = self.model(X_torch.to(self.device)).detach().cpu()
return torch.clamp(X, 0.0, 1.0)
def print(self):
return "SimpleReformer:" + self.path.split("/")[-1]
class Classifier:
def __init__(self, model, device, classifier_path, device_ids = [0]):
"""
Keras classifier wrapper.
Note that the wrapped classifier should spit logits as output.
model : pytorch model class
device : torch.device
classifier_path: Path to Keras classifier file.
"""
self.path = classifier_path
self.model = model
self.model.load_state_dict(torch.load(classifier_path))
self.softmax = nn.Softmax(dim = 1)
self.device = device
if len(device_ids) > 1 :
self.model = nn.DataParallel(self.model, device_ids = device_ids)
self.model = self.model.to(self.device)
self.model.eval()
def classify(self, X, option="logit", T=1):
if torch.is_tensor(X):
X_torch = X
else :
X_torch = torch.from_numpy(X)
X_torch = X_torch.to(self.device)
if option == "logit":
return self.model(X_torch).detach().cpu()
if option == "prob":
logits = self.model(X_torch) / T
logits = self.softmax(logits)
return logits.detach().cpu()
def print(self):
return "Classifier:"+self.path.split("/")[-1]
class AttackData:
def __init__(self, examples, labels, name=""):
"""
Input data wrapper. May be normal or adversarial.
examples: object of input examples.
labels: Ground truth labels.
"""
self.data = examples
self.labels = labels
self.name = name
def print(self):
return "Attack:"+self.name
def operate(reformer, classifier, inputs, filtered = True):
X = inputs
if not torch.is_tensor(X):
X = torch.from_numpy(X)
if filtered :
X_prime = reformer.heal(X)
Y_prime = classifier.classify(X_prime)
else :
Y_prime = classifier.classify(X)
return Y_prime
def filters(detector, data, thrs):
"""
untrusted_obj: Untrusted input to test against.
thrs: Thresholds.
return:
all_pass: Index of examples that passed all detectors.
collector: Number of examples that escaped each detector.
"""
collector = []
all_pass = np.array(range(10000))
marks = detector.mark(data)
np_marks = marks.numpy()
np_thrs = thrs.numpy()
idx_pass = np.argwhere(np_marks < np_thrs)
collector.append(len(idx_pass))
all_pass = np.intersect1d(all_pass, idx_pass)
all_pass = torch.from_numpy(all_pass)
return all_pass, collector