forked from anishmadan23/adversarial-attacks-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cw_l2.py
357 lines (278 loc) · 13.5 KB
/
cw_l2.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
# -*- coding: utf-8 -*-
"""CW_L2.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/10y6b-sKFhUawdPyKBEdi-7N2P8q8cjHO
"""
# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse
# !apt-get install -y -qq software-properties-common python-software-properties module-init-tools
# !add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
# !apt-get update -qq 2>&1 > /dev/null
# !apt-get -y install -qq google-drive-ocamlfuse fuse
# # Generate auth tokens for Colab
# from google.colab import auth
# auth.authenticate_user()
# # Generate creds for the Drive FUSE library.
# from oauth2client.client import GoogleCredentials
# creds = GoogleCredentials.get_application_default()
# import getpass
# !google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
# vcode = getpass.getpass()
# !echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
# !mkdir -p My Drive
# !google-drive-ocamlfuse My Drive
# # import os
# # # os.chdir('/Drive/ML_Project/data/leftImg8bit_orig/train/')
# # path = os.listdir('Drive/ML_Project/data/leftImg8bit_orig/val/')
# # len(path)
# import os
# os.chdir('Drive/BTP/adversarial-attacks-pytorch')
# # !cd Drive/Colab\ Notebooks/vgg_tinyimagenet
# !pip3 install --no-cache-dir -I pillow
# # from PIL import Image
# # def register_extension(id, extension): Image.EXTENSION[extension.lower()] = id.upper()
# # Image.register_extension = register_extension
# # def register_extensions(id, extensions):
# # for extension in extensions: register_extension(id, extension)
# # Image.register_extensions = register_extensions
# # http://pytorch.org/
# from os import path
# from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
# platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
# accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi') else 'cpu'
# !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.0-{platform}-linux_x86_64.whl torchvision
# import torch
# torch.__version__
# ! nvidia-smi
import torch
import torch.nn as nn
import os
import argparse
from torchvision import datasets, transforms
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.optim as optim
import torchvision
import torch.nn.functional as F
import sys
from PIL import Image
import requests
from io import BytesIO
import urllib.request as url_req
import pickle
from Model import get_model
from utils import *
import json
from model_and_data import Data
from visualize import visualise
from visualize import visualise
device = torch.device('cuda')
model = get_model(device) # loads a pretrained vgg11 model
model.eval()
class CarliniWagnerL2():
# https://github.com/rwightman/pytorch-nips2017-attack-example/blob/master/attacks/attack_carlini_wagner_l2.py
def __init__(self, orig_img, model, target, initial_constt, clip_min, clip_max, confidence_param,
binary_search_steps, max_steps):
self.model = model
self.clip_min = clip_min
self.clip_max = clip_max
self.confidence= confidence_param
self.bsearch_steps = binary_search_steps
self.num_classes = 1000
self.target = target # tensor
self.initial_constt = initial_constt
self.repeat = binary_search_steps >= 10
self.orig_img = orig_img
self.max_steps = max_steps
def _compare(self, output, target):
if not isinstance(output, (float, int, np.int64)):
output = np.copy(output)
output[target] -= self.confidence
output = np.argmax(output)
return output == target
def _loss(self,output, target, dist, scale_constt):
# compute probability of the label class versus the maximum other
real = (target * output).sum(1)
other = ((1 - target) * output - target*10000).max(1)[0] # target is one-hot encoded and
# gives max{Z(x')<subs>i where i!=t (t is target class)}
loss1 = torch.clamp(other - real + self.confidence, min = 0.)
loss1 = torch.sum(scale_constt*loss1)
loss2 = dist.sum()
loss = loss1+loss2
return loss
def _optimize(self, optimizer, model, input_var, modifier_var, target_var, scale_const_var, input_orig=None):
input_adv = tanh_rescale(modifier_var+input_var, self.clip_min,self.clip_max)
output = model(input_adv)
if input_orig is None:
dist = l2_dist(input_adv, input_var,keepdim=False)
else:
dist = l2_dist(input_adv, input_orig, keepdim=False)
loss = self._loss(output, target_var, dist, scale_const_var)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
loss_np = loss.data[0]
dist_np = dist.data.cpu().numpy()
output_np = output.data.cpu().numpy()
input_adv_np = input_adv.data.permute(0, 2, 3, 1).cpu().numpy() # back to BHWC for numpy consumption
return loss_np, dist_np, output_np, input_adv_np
def run(self, model, inputs,target, batch_idx=0):
batch_size = inputs.size(0)
# set the lower and upper bounds accordingly
lower_bound = np.zeros(batch_size)
scale_const = np.ones(batch_size) * self.initial_constt
upper_bound = np.ones(batch_size) * 1e10
# python/numpy placeholders for the overall best l2, label score, and adversarial image
o_best_l2 = [1e10] * batch_size
o_best_score = [-1] * batch_size
o_best_attack = inputs.permute(0, 2, 3, 1).cpu().detach().numpy()
# input_var = torch.tensor(torch_arctanh(inputs),requires_grad=False)
input_var=inputs
input_orig = tanh_rescale(input_var, self.clip_min, self.clip_max)
target_onehot = torch.zeros(target.size() + (self.num_classes,))
target_onehot = target_onehot.cuda()
target_onehot.scatter_(1, target.unsqueeze(1), 1.)
target_var = torch.tensor(target_onehot, requires_grad=False)
modifier = torch.zeros(input_var.size()).float()
modifier = torch.normal(mean=modifier, std = 1e-3)
modifier = modifier.cuda()
modifier_var = torch.tensor(modifier, requires_grad=True)
optimizer = optim.Adam([modifier_var], lr=5e-4)
for search_step in range(self.bsearch_steps):
for i, x in enumerate(scale_const):
print(i, x)
best_l2 = [1e10] * batch_size
best_score = [-1] * batch_size
if self.repeat and search_step == self.binary_search_steps - 1:
scale_const = upper_bound
scale_const_tensor = torch.from_numpy(scale_const).float()
scale_const_tensor = scale_const_tensor.cuda()
scale_const_var = torch.tensor(scale_const_tensor,requires_grad=False)
prev_loss = 1e6
for step in range(self.max_steps):
loss, dist, output, adv_img = self._optimize(
optimizer,
model,
input_var,
modifier_var,
target_var,
scale_const_var,
input_orig)
if step % 100 == 0 or step == self.max_steps - 1:
print('Step: {0:>4}, loss: {1:6.4f}, dist: {2:8.5f}, modifier mean: {3:.5e}'.format(
step, loss, dist.mean(), modifier_var.data.mean()))
# update best result found
for i in range(batch_size):
target_label = target[i]
output_logits = output[i]
output_label = np.argmax(output_logits)
di = dist[i]
if step % 100 == 0:
print('{0:>2} dist: {1:.5f}, output: {2:>3}, {3:5.3}, target {4:>3}'.format(
i, di, output_label, output_logits[output_label], target_label))
if di < best_l2[i] and self._compare(output_logits, target_label):
best_l2[i] = di
best_score[i] = output_label
if di < o_best_l2[i] and self._compare(output_logits, target_label):
o_best_l2[i] = di
o_best_score[i] = output_label
o_best_attack[i] = adv_img[i]
batch_failure = 0
batch_success = 0
for i in range(batch_size):
if self._compare(best_score[i], target[i]) and best_score[i] != -1:
# successful, do binary search and divide const by two
upper_bound[i] = min(upper_bound[i], scale_const[i])
if upper_bound[i] < 1e9:
scale_const[i] = (lower_bound[i] + upper_bound[i]) / 2
# if self.debug:
# print('{0:>2} successful attack, lowering const to {1:.3f}'.format(
# i, scale_const[i]))
else:
# failure, multiply by 10 if no solution found
# or do binary search with the known upper bound
lower_bound[i] = max(lower_bound[i], scale_const[i])
if upper_bound[i] < 1e9:
scale_const[i] = (lower_bound[i] + upper_bound[i]) / 2
else:
scale_const[i] *= 10
if self._compare(o_best_score[i], target[i]) and o_best_score[i] != -1:
batch_success += 1
else:
batch_failure += 1
print('Num failures: {0:2d}, num successes: {1:2d}\n'.format(batch_failure, batch_success))
sys.stdout.flush()
# end outer search loop
return o_best_attack
imgs = os.listdir('imagenet_imgs/')
misclassifn_top1 = 0
misclassifn_top5 = 0
targ_misclassifn_top1 = 0
targ_misclassifn_top5 = 0
batch_size = len(os.listdir('imagenet_imgs/'))
for idx,img_name in enumerate(imgs):
print(idx)
img_path = os.path.join('imagenet_imgs/',img_name)
data = Data(model,device, None,None)
img_tsor = data.preprocess_data(Image.open(img_path))
# imshow(img_tsor,'dgs')
img_tsor = img_tsor.cuda()
img_tsor.unsqueeze_(0)
print(img_tsor.size())
# img_tsor = img_tsor.to(device)
img_tsor.requires_grad_(True)
label = img_name.split('_')[0]
label = torch.tensor([int(label)],requires_grad=False)
label = label.to(device)
#
print(label.shape)
# criterion = nn.CrossEntropyLoss()
############ Unperturbed Model ######################
unpert_output,unpert_pred, unpert_op_probs, unpert_pred_prob = getPredictionInfo(model,img_tsor)
targetLabel = torch.tensor([468],requires_grad=False).to(device)
print('hi')
wagner = CarliniWagnerL2(img_tsor, model, targetLabel, 0.1, -1, 1, 0, 4,800)
wagner_attack = wagner.run(model,img_tsor,targetLabel)
adv_img_np = wagner_attack.reshape((wagner_attack.shape[1],wagner_attack.shape[2],wagner_attack.shape[3]))
to_tens_transform = transforms.ToTensor()
adv_img_tsor = to_tens_transform(adv_img_np)
adv_img_tsor.unsqueeze_(0)
adv_img_tsor = adv_img_tsor.to(device)
adv_output,adv_pred, adv_op_probs, adv_pred_prob = getPredictionInfo(model,adv_img_tsor)
perturbation = torch.abs(adv_img_tsor.detach().cpu().data-img_tsor.detach().cpu().data)
top_probs,top_labels = predict_top_five(model,adv_img_tsor,k=5)
targ_misclassifn_top1 = checkMatchingLabels(targetLabel,adv_pred,targ_misclassifn_top1)
targ_misclassifn_top5 = checkMatchingLabelsTop_five(targetLabel,top_labels,targ_misclassifn_top5)
misclassifn_top1 = checkMatchingLabels(unpert_pred,adv_pred,misclassifn_top1)
misclassifn_top5 = checkMatchingLabelsTop_five(unpert_pred,top_labels,misclassifn_top5)
print(targ_misclassifn_top1)
print(targ_misclassifn_top5)
print(misclassifn_top1)
print(misclassifn_top5)
# visualise(img_tsor,None,adv_img_tsor,label,label,unpert_pred_prob,adv_pred,adv_pred_prob,1,topkProb=top_probs,topkLabel=top_labels)
# print(torch.abs(adv_img_tsor.data-img_tsor.data))
# perturbation = torch.abs(adv_img_tsor.detach().cpu().data-img_tsor.detach().cpu().data)
# top_probs,top_labels = predict_top_five(model,adv_img_tsor,k=5)
# visualise(img_tsor,None,adv_img_tsor,label,label,unpert_pred_prob,adv_pred,adv_pred_prob,1,topkProb=top_probs,topkLabel=top_labels)
# print(torch.abs(adv_img_tsor.data-img_tsor.data))
def imshow_noTranspose(img,title=None):
print(img.shape)
img = img.reshape((img.shape[1],img.shape[2],img.shape[3]))
mean=np.array([0.485, 0.456, 0.406])
std=np.array([0.229, 0.224, 0.225])
img = img*std+mean
# img = np.clip(img,0,1)
plt.imshow(img)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
imshow_noTranspose(wagner_attack)
# img = img.squeeze(0)
# imshow(img)
# img.unsqueeze_(0)
# img_np = img.cpu().detach().numpy()
# wag_np = wag.transpose((0,3,1,2))
# print(np.linalg.norm(img_np-wag_np))
# !nvidia-smi