-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethods.py
153 lines (125 loc) · 5.54 KB
/
methods.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
import os
import torch
import torch.nn as nn
from tqdm import tqdm
import torch.optim as optim
import torchvision.transforms as T
import torch.nn.functional as F
import numpy as np
from utils import compute_score
import pdb
# CW L2 attack
def cw_l2_attack(X, model, c=0.1, lr=0.01, iters=100, targeted=False):
encoder = model.vae.encode
clean_latents = encoder(X).latent_dist.mean
def f(x):
latents = encoder(x).latent_dist.mean
if targeted:
return latents.norm()
else:
return -torch.norm(latents - clean_latents.detach(), p=2, dim=-1)
w = torch.zeros_like(X, requires_grad=True).cuda()
pbar = tqdm(range(iters))
optimizer = optim.Adam([w], lr=lr)
for step in pbar:
a = 1/2*(nn.Tanh()(w) + 1)
loss1 = nn.MSELoss(reduction='sum')(a, X)
loss2 = torch.sum(c*f(a))
cost = loss1 + loss2
pbar.set_description(f"Loss: {cost.item():.5f} | loss1: {loss1.item():.5f} | loss2: {loss2.item():.5f}")
# pdb.set_trace()
optimizer.zero_grad()
cost.backward()
optimizer.step()
X_adv = 1/2*(nn.Tanh()(w) + 1)
return X_adv
# Encoder attack - Targeted / Untargeted
def encoder_attack(X, model, eps=0.03, step_size=0.01, iters=100, clamp_min=-1, clamp_max=1, targeted=False):
"""
Processing encoder attack using l_inf norm
Params:
X - image tensor we hope to protect
model - the targeted edit model
eps - attack budget
step_size - attack step size
iters - attack iterations
clamp_min - min value for the image pixels
clamp_max - max value for the image pixels
Return:
X_adv - image tensor for the protected image
"""
encoder = model.vae.encode
X_adv = torch.clamp(X.clone().detach() + (torch.rand(*X.shape)*2*eps-eps).half().cuda(), min=clamp_min, max=clamp_max)
if not targeted:
loss_fn = nn.MSELoss()
clean_latent = encoder(X).latent_dist.mean
pbar = tqdm(range(iters))
for i in pbar:
actual_step_size = step_size - (step_size - step_size / 100) / iters * i
X_adv.requires_grad_(True)
latent = encoder(X_adv).latent_dist.mean
if targeted:
loss = latent.norm()
grad, = torch.autograd.grad(loss, [X_adv])
X_adv = X_adv - grad.detach().sign() * actual_step_size
else:
loss = loss_fn(latent, clean_latent)
grad, = torch.autograd.grad(loss, [X_adv])
X_adv = X_adv + grad.detach().sign() * actual_step_size
pbar.set_description(f"[Running attack]: Loss {loss.item():.5f} | step size: {actual_step_size:.4}")
X_adv = torch.minimum(torch.maximum(X_adv, X - eps), X + eps)
X_adv.data = torch.clamp(X_adv, min=clamp_min, max=clamp_max)
X_adv.grad = None
pbar.set_postfix(norm_2=(X_adv - X).norm().item(), norm_inf=(X_adv - X).abs().max().item())
return X_adv
def vae_attack(X, model, eps=0.03, step_size=0.01, iters=100, clamp_min=-1, clamp_max=1):
"""
Processing encoder attack using l_inf norm
Params:
X - image tensor we hope to protect
model - the targeted edit model
eps - attack budget
step_size - attack step size
iters - attack iterations
clamp_min - min value for the image pixels
clamp_max - max value for the image pixels
Return:
X_adv - image tensor for the protected image
"""
vae = model.vae
X_adv = torch.clamp(X.clone().detach() + (torch.rand(*X.shape)*2*eps-eps).half().cuda(), min=clamp_min, max=clamp_max)
pbar = tqdm(range(iters))
for i in pbar:
actual_step_size = step_size - (step_size - step_size / 100) / iters * i
X_adv.requires_grad_()
image = vae(X_adv).sample
loss = (image).norm()
grad, = torch.autograd.grad(loss, [X_adv])
X_adv = X_adv - grad.detach().sign() * actual_step_size
pbar.set_description(f"[Running attack]: Loss {loss.item():.5f} | step size: {actual_step_size:.4}")
X_adv = torch.minimum(torch.maximum(X_adv, X - eps), X + eps)
X_adv.data = torch.clamp(X_adv, min=clamp_min, max=clamp_max)
X_adv.grad = None
return X_adv
def facelock(X, model, aligner, fr_model, lpips_fn, eps=0.03, step_size=0.01, iters=100, clamp_min=-1, clamp_max=1):
X_adv = torch.clamp(X.clone().detach() + (torch.rand(*X.shape)*2*eps-eps).to(X.device), min=clamp_min, max=clamp_max).half()
pbar = tqdm(range(iters))
vae = model.vae
X_adv.requires_grad_(True)
clean_latent = vae.encode(X).latent_dist.mean
for i in pbar:
# actual_step_size = step_size
actual_step_size = step_size - (step_size - step_size / 100) / iters * i
latent = vae.encode(X_adv).latent_dist.mean
image = vae.decode(latent).sample.clip(-1, 1)
loss_cvl = compute_score(image.float(), X.float(), aligner=aligner, fr_model=fr_model)
loss_encoder = F.mse_loss(latent, clean_latent)
loss_lpips = lpips_fn(image, X)
loss = -loss_cvl * (1 if i >= iters * 0.35 else 0.0) + loss_encoder * 0.2 + loss_lpips * (1 if i > iters * 0.25 else 0.0)
grad, = torch.autograd.grad(loss, [X_adv])
X_adv = X_adv + grad.detach().sign() * actual_step_size
X_adv = torch.minimum(torch.maximum(X_adv, X - eps), X + eps)
X_adv.data = torch.clamp(X_adv, min=clamp_min, max=clamp_max)
X_adv.grad = None
pbar.set_postfix(loss_cvl=loss_cvl.item(), loss_encoder=loss_encoder.item(), loss_lpips=loss_lpips.item(), loss=loss.item())
return X_adv