-
Notifications
You must be signed in to change notification settings - Fork 0
/
deletion_batch_v4_recuperacion.py
506 lines (411 loc) · 18.2 KB
/
deletion_batch_v4_recuperacion.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
import argparse
import os
import random
import shutil
import time
import sys
import warnings
from srblib import abs_path
from PIL import ImageFilter, Image
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm, trange
import skimage
# Fixing for deterministic results
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# bibliotecas inpainter
sys.path.insert(0, './generativeimptorch')
from utils.tools import get_config, get_model_list
from model.networks import Generator
imagenet_val_xml_path = './val_bb'
imagenet_val_path = './val/'
base_img_dir = abs_path(imagenet_val_path)
input_dir_path = 'images_list.txt'
text_file = abs_path(input_dir_path)
imagenet_class_mappings = './imagenet_class_mappings'
torch.manual_seed(0)
learning_rate = 0.1 * 0.8 # orig (0.3) 0.1 (preservation sparser) 0.3 (preservation dense)
max_iterations = 228 # 130 *2
l1_coeff = 0.01e-5 * 2 # *2 *4 *0.5 (robusto)
size = 224
tv_beta = 3
tv_coeff = 1e-2
factorTV = 1 * 0.5 * 0.005 # 1(dense) o 0.5 (sparser/sharp) #0.5 (preservation)
def inpainter(img, mask):
config = get_config('./generativeimptorch/configs/config.yaml')
checkpoint_path = os.path.join('./generativeimptorch/checkpoints',
config['dataset_name'],
config['mask_type'] + '_' + config['expname'])
cuda = config['cuda']
device_ids = config['gpu_ids']
with torch.no_grad(): # enter no grad context
# Test a single masked image with a given mask
x = img
# denormaliza imagenet y se normaliza a inpainter [-1,1] mean=0.5, std=0.5
x = transforms.Normalize(mean=[0.015 / 0.229, 0.044 / 0.224, 0.094 / 0.225],
std=[0.5 / 0.229, 0.5 / 0.224, 0.5 / 0.225])(x)
x = x * (mask)
# Define the trainer
netG = Generator(config['netG'], cuda, device_ids)
# Resume weight
last_model_name = get_model_list(checkpoint_path, "gen", iteration=0)
netG.load_state_dict(torch.load(last_model_name))
# netG = torch.nn.parallel.DataParallel(netG, device_ids=[0, 1])
netG.cuda()
# Inference
x1, x2, offset_flow = netG(x, (1. - mask))
return x2
def tv_norm(input, tv_beta):
img = input[:, 0, :]
row_grad = torch.abs((img[:, :-1, :] - img[:, 1:, :])).pow(tv_beta).sum(dim=(1, 2))
col_grad = torch.abs((img[:, :, :-1] - img[:, :, 1:])).pow(tv_beta).sum(dim=(1, 2))
return row_grad + col_grad
torch.cuda.set_device(1) # especificar cual gpu 0 o 1
model = models.googlenet(pretrained=True)
# model = models.resnet50(pretrained=True)
# model = models.vgg16(pretrained=True)
# model = models.alexnet(pretrained=True)
model.cuda()
model.eval()
for param in model.parameters():
param.requires_grad = False
print('GPU 0 Metod. Recuperacion ver 4')
def imagenet_label_mappings():
fileName = os.path.join(imagenet_class_mappings, 'imagenet_label_mapping')
with open(fileName, 'r') as f:
image_label_mapping = {int(x.split(":")[0]): x.split(":")[1].strip()
for x in f.readlines() if len(x.strip()) > 0}
return image_label_mapping
im_label_map = imagenet_label_mappings()
transform_val = transforms.Compose([
transforms.Resize((256, 256)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
# Plots image from tensor
def tensor_imshow(inp, title=None, **kwargs):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
# Mean and std for ImageNet
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp, **kwargs)
if title is not None:
plt.title(title)
plt.show()
list_of_layers = ['conv1',
'conv2',
'conv3',
'inception3a',
'inception3b',
'inception4a',
'inception4b',
'inception4c',
'inception4d',
'inception4e',
'inception5a',
'inception5b',
'fc'
]
# capas para resnet50
# list_of_layers = ['relu',
# 'layer1.0',
# 'layer1.1',
# 'layer1.2',
# 'layer2.0',
# 'layer2.1',
# 'layer2.2',
# 'layer2.3',
# 'layer3.0',
# 'layer3.1',
# 'layer3.2',
# 'layer3.3',
# 'layer3.4',
# 'layer3.5',
# 'layer4.0',
# 'layer4.1',
# 'layer4.2',
# ]
# capas para vgg16
# list_of_layers = ['features.1',
# 'features.3',
# 'features.6',
# 'features.8',
# 'features.11',
# 'features.13',
# 'features.15',
# 'features.18',
# 'features.20',
# 'features.22',
# 'features.25',
# 'features.27',
# 'features.29'
# ]
# capas para alexnet
# list_of_layers = ['features.1',
# 'features.4',
# 'features.7',
# 'features.9',
# 'features.11',
# 'classifier.2',
# 'classifier.5'
# ]
activation_orig = {}
def get_activation_orig(name):
def hook(model, input, output):
activation_orig[name] = output
return hook
def get_activation_mask(name):
def hook(model, input, output):
act_mask = output
# print(act_mask.shape). #debug
# print(activation_orig[name].shape) #debug
limite_sup = (act_mask <= torch.fmax(torch.tensor(0), activation_orig[name]))
limite_inf = (act_mask >= torch.fmin(torch.tensor(0), activation_orig[name]))
oper = limite_sup * limite_inf
# print('oper shape=',oper.shape). #debug
act_mask.requires_grad_(True)
act_mask.retain_grad()
h = act_mask.register_hook(lambda grad: grad * oper)
# x.register_hook(update_gradients(2))
# activation[name]=act_mask
# h.remove()
return hook
def my_explanation(img_batch, max_iterations, gt_category):
F_hook = []
exp_hook = []
#
# for module_name, module in model.named_modules():
# if module_name in list_of_layers:
# F_hook.append(module.register_forward_hook(get_activation_orig(module_name)))
for name, layer in model.named_children():
if name in list_of_layers:
F_hook.append(layer.register_forward_hook(get_activation_orig(name)))
# se calculan las activaciones para el batch de imágenes y se almacenan en la lista activation_orig
# la funcion "feed forward" registra los hook
org_softmax = torch.nn.Softmax(dim=1)(model(img_batch))
# se borran los hook registrados en Feed Forward
for fh in F_hook:
fh.remove()
#
# for module_name, module in model.named_modules():
# if module_name in list_of_layers:
# exp_hook.append(module.register_forward_hook(get_activation_mask(module_name)))
for name, layer in model.named_children():
if name in list_of_layers:
exp_hook.append(layer.register_forward_hook(get_activation_mask(name)))
for param in model.parameters():
param.requires_grad = False
np.random.seed(seed=0)
mask = torch.from_numpy(np.float32(np.random.uniform(0, 0.01, size=(1, 1, 224, 224))))
mask = mask.expand(img_batch.size(0), 1, 224, 224)
mask = mask.cuda()
mask.requires_grad = True
# null_img = torch.zeros(img_batch.size(0), 3, 224, 224).cuda()
# null_img_blur = transforms.GaussianBlur(kernel_size=223, sigma=10)(img_batch)
# null_img_blur.requires_grad = False
# null_img = null_img_blur.cuda()
optimizer = torch.optim.Adam([mask], lr=learning_rate)
for i in trange(max_iterations):
extended_mask = mask.expand(img_batch.size(0), 3, 224, 224)
img_inpainted = inpainter(img_batch, mask)
img_inpainted = transforms.Normalize(mean=-1, std=2)(img_inpainted)
img_inpainted = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])(img_inpainted)
perturbated_input = img_batch.mul(extended_mask) + img_inpainted.mul(1 - extended_mask)
# perturbated_input = perturbated_input.to(torch.float32)
optimizer.zero_grad()
outputs = torch.nn.Softmax(dim=1)(model(perturbated_input)) # (3,1000)
preds = outputs[torch.arange(0, img_batch.size(0)).tolist(), gt_category.tolist()]
loss = l1_coeff * torch.sum(torch.abs(1 - mask), dim=(1, 2, 3)) + preds + \
factorTV * tv_coeff * tv_norm(mask, tv_beta)
loss.backward(gradient=torch.ones_like(loss).cuda())
optimizer.step()
mask.data.clamp_(0, 1)
for eh in exp_hook:
eh.remove()
# Para visualizar las máscaras
mask_np = (mask.cpu().detach().numpy())
for i in range(mask_np.shape[0]):
fig = plt.figure()
fig.subplots_adjust(left=0.03, bottom=0, right=0.97, top=1, wspace=0.1, hspace=0.1)
fig.set_size_inches(12, 5)
ax = fig.add_subplot(1, 3, 1)
inp = img_batch[i].cpu().numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
ax.imshow(inp)
ax.set_xticks([])
ax.set_yticks([])
ax = fig.add_subplot(1, 3, 2)
mask_rz = mask_np[i, 0, :, :]
ax.imshow(mask_rz)
ax.set_xticks([])
ax.set_yticks([])
ax = fig.add_subplot(1, 3, 3)
img_masked = np.multiply(inp, np.repeat(np.expand_dims(mask_rz, axis=2), 3, axis=2))
ax.imshow(img_masked)
ax.set_xticks([])
ax.set_yticks([])
# fig.tight_layout()
plt.show()
return mask
init_time = time.time()
########## Se carga el batch de imágenes adversarias ############
imgs_adv = np.load('adv_im_MRC_strong.npy')
adv_batch = torch.from_numpy(imgs_adv)
adv_batch = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])(adv_batch)
# preds_adv = torch.nn.Softmax(dim=1)(model(adv_batch)) # tensor(200,1000)
# probs_adv, labels_adv = torch.max(preds_adv, 1) # Top 1 predicciones adversarias (200, 1)
##################################################################
# orig_labels = np.load('adv_orig_labels.npy') # (200,)
img_name_list = []
with open(text_file, 'r') as f:
for line in f:
img_name_list.append(line.split('\n')[0])
class DataProcessing:
def __init__(self, data_path, transform, img_idxs=[0, 1], if_noise=0, noise_var=0.0):
self.data_path = data_path
self.transform = transform
self.if_noise = if_noise
self.noise_mean = 0
self.noise_var = noise_var
self.img_idxs = img_idxs
img_list = img_name_list[img_idxs[0]:img_idxs[1]]
self.img_filenames = [os.path.join(data_path, f'{i}.JPEG') for i in img_list]
# self.img_filenames.sort()
def __getitem__(self, index):
img = Image.open(os.path.join(self.data_path, self.img_filenames[index])).convert('RGB')
target = self.get_image_class(os.path.join(self.data_path, self.img_filenames[index]))
img_adv = adv_batch[index + self.img_idxs[0]]
if self.if_noise == 1:
img = skimage.util.random_noise(np.asarray(img), mode='gaussian',
mean=self.noise_mean, var=self.noise_var,
) # numpy, dtype=float64,range (0, 1)
img = Image.fromarray(np.uint8(img * 255))
img = self.transform(img)
return img, img_adv, target, os.path.join(self.data_path, self.img_filenames[index])
# return img, target
def __len__(self):
return len(self.img_filenames)
def get_image_class(self, filepath):
# ImageNet 2012 validation set images?
with open(os.path.join(imagenet_class_mappings, "ground_truth_val2012")) as f:
ground_truth_val2012 = {x.split()[0]: int(x.split()[1])
for x in f.readlines() if len(x.strip()) > 0}
def get_class(f):
ret = ground_truth_val2012.get(f, None)
return ret
image_class = get_class(filepath.split('/')[-1])
return image_class
transform_val = transforms.Compose([
transforms.Resize((256, 256)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
val_dataset = DataProcessing(base_img_dir, transform_val, img_idxs=[0, 200], if_noise=0, noise_var=0.0)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=25, shuffle=False, num_workers=10,
pin_memory=True)
iterator = tqdm(enumerate(val_loader), total=len(val_loader), desc='batch')
recov_top_cnt_full = []
pertb_top_cnt_full = []
pertb_radio = []
recov_radio = []
for i, (images, imgs_adv, target, file_names) in iterator:
imgs_adv.requires_grad = False
images_orig = images.cuda()
imgs_adv = imgs_adv.cuda()
# predicciones originales para comparar
preds_orig = torch.nn.Softmax(dim=1)(model(images_orig))
probs_orig, labels_orig = torch.topk(preds_orig, 10) # Top 10 predicciones originales
preds_adv = torch.nn.Softmax(dim=1)(model(imgs_adv)) # tensor(n_batch,1000)
probs_adv, labels_adv = torch.topk(preds_adv, 1000) # Top 1 predicciones adversarias
_, labels_adv_top = torch.max(preds_adv, 1)
# obtención de explicaciones para imágenes adversarias
_, orig_labels = torch.max(preds_orig, 1) # labels originales para generar las explicaciones
mask = my_explanation(imgs_adv, max_iterations, labels_adv_top)
# reenmascaramiento de img adv con explicación
adv_masked = imgs_adv.mul(mask)
adv_masked = adv_masked.to(torch.float32)
# prediccion reenmascaramiento
preds_masked = torch.nn.Softmax(dim=1)(model(adv_masked)) # tensor(n_batch,1000)
probs_masked, labels_masked = torch.topk(preds_masked, 1000) # predicciones recuperadas y ordenadas (n_batch, 1000)
for i in range(val_loader.batch_size): # se itera en el tamaño del batch
prob_orig = probs_orig.cpu().detach()[i] # (10, ) topk = 10
label_orig = labels_orig.cpu().detach()[i] # (10, ) topk = 10
prob_masked = probs_masked.cpu().detach()[i] # (1000,)
label_masked = labels_masked.cpu().detach()[i] # (1000,)
label_adv = labels_adv.cpu().detach()[i]
prob_adv = probs_adv.cpu().detach()[i]
# se buscan donde estan las etiquetas originales dentro de las perturbadas
pertub_pos_list = [torch.where(label_adv == label_orig_item)[0].item() for label_orig_item in label_orig]
pertub_pos_list_tensor = torch.tensor(pertub_pos_list)
pertb_radio.append(pertub_pos_list_tensor)
pertb_top_cnt = [torch.where(pertub_pos_list_tensor <= i)[0].nelement() >= 1 for i in range(10)]
pertb_top_cnt_full.append(torch.tensor(pertb_top_cnt))
# se buscan donde estan las etiquetas originales dentro de las recuperadas
recov_pos_list = [torch.where(label_masked == label_orig_item)[0].item() for label_orig_item in label_orig]
recov_pos_list_tensor = torch.tensor(recov_pos_list)
recov_radio.append(recov_pos_list_tensor)
# el indice de pos_list_tensor determina el rango de predicciones a incluir en el top 10
# por ejemplo pos_list_tensor[0] analiza el top 10 de la primera prediccion original en el grupo de recuperados
# pos_list_tensor[0:4] analiza el top 10 del grupo de las 3 primeras predicciones originales en el grupo recup
recov_top_cnt = [torch.where(recov_pos_list_tensor <= i)[0].nelement() >= 1 for i in range(10)]
recov_top_cnt_full.append(torch.tensor(recov_top_cnt))
print('muestra ', file_names[i].split('/')[-1].split('.JPEG')[0])
print('top 10 muestra original: ', label_orig.tolist())
print('top 10 muestra original (decod): ', [im_label_map.get(label) for label in label_orig.tolist()])
print('top 10 prob muestra original (%): ', [round(num * 100, 2) for num in prob_orig.tolist()])
print('lista top 10 recuperados acum ', recov_top_cnt)
print('top 10 perturbados ', label_adv[0:10].tolist())
print('top 10 perturbados (decod) ', [im_label_map.get(label) for label in label_adv[0:10].tolist()])
print('top 10 prob muestra pertb (%)', [round(num * 100, 2) for num in prob_adv[0:10].tolist()])
print('pos orig en perturbado ', pertub_pos_list)
print('top 10 recuperados ', label_masked[0:10].tolist())
print('top 10 recuperados (decod) ', [im_label_map.get(label) for label in label_masked[0:10].tolist()])
print('top 10 prob muestra recup (%)', [round(num * 100, 2) for num in prob_masked[0:10].tolist()])
print('pos orig en recuperado ', recov_pos_list)
print('')
recov_table = torch.stack(recov_top_cnt_full)
recov_stats = recov_table.sum(0) / (val_loader.batch_size * len(val_loader))
pertb_table = torch.stack(pertb_top_cnt_full)
pertb_stats = pertb_table.sum(0) / (val_loader.batch_size * len(val_loader))
print('estado despues de perturbar')
print(pertb_stats)
print('')
print('estado despues de recuperar')
print(recov_stats)
print('')
pr = torch.stack(pertb_radio).float()
print('radio perturbacion')
print(pr)
print('promedio')
print(pr.mean(0))
print('')
rr = torch.stack(recov_radio).float()
print('radio recuperacion')
print(rr)
print('promedio')
print(rr.mean(0))
print('')
print('Time taken: {:.3f}'.format(time.time() - init_time))