-
Notifications
You must be signed in to change notification settings - Fork 7
/
attack_utils.py
83 lines (68 loc) · 2.23 KB
/
attack_utils.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
import torch
import torch.nn as nn
from torch import Tensor
from tqdm import trange
def e2e_attack(
model: nn.Module,
vc_src: Tensor,
vc_tgt: Tensor,
adv_tgt: Tensor,
eps: float,
n_iters,
) -> Tensor:
ptb = torch.zeros_like(vc_tgt).normal_(0, 1).requires_grad_(True)
opt = torch.optim.Adam([ptb])
criterion = nn.MSELoss()
pbar = trange(n_iters)
with torch.no_grad():
org_out = model.inference(vc_src, vc_tgt)
tgt_out = model.inference(vc_src, adv_tgt)
for _ in pbar:
adv_inp = vc_tgt + eps * ptb.tanh()
adv_out = model.inference(vc_src, adv_inp)
loss = criterion(adv_out, tgt_out) - 0.1 * criterion(adv_out, org_out)
opt.zero_grad()
loss.backward()
opt.step()
return vc_tgt + eps * ptb.tanh()
def emb_attack(
model: nn.Module, vc_tgt: Tensor, adv_tgt: Tensor, eps: float, n_iters: int
) -> Tensor:
ptb = torch.zeros_like(vc_tgt).normal_(0, 1).requires_grad_(True)
opt = torch.optim.Adam([ptb])
criterion = nn.MSELoss()
pbar = trange(n_iters)
with torch.no_grad():
org_emb = model.speaker_encoder(vc_tgt)
tgt_emb = model.speaker_encoder(adv_tgt)
for _ in pbar:
adv_inp = vc_tgt + eps * ptb.tanh()
adv_emb = model.speaker_encoder(adv_inp)
loss = criterion(adv_emb, tgt_emb) - 0.1 * criterion(adv_emb, org_emb)
opt.zero_grad()
loss.backward()
opt.step()
return vc_tgt + eps * ptb.tanh()
def fb_attack(
model: nn.Module,
vc_src: Tensor,
vc_tgt: Tensor,
adv_tgt: Tensor,
eps: float,
n_iters: int,
) -> Tensor:
ptb = torch.zeros_like(vc_tgt).normal_(0, 1).requires_grad_(True)
opt = torch.optim.Adam([ptb])
criterion = nn.MSELoss()
pbar = trange(n_iters)
with torch.no_grad():
org_emb = model.speaker_encoder(model.inference(vc_src, vc_tgt))
tgt_emb = model.speaker_encoder(adv_tgt)
for _ in pbar:
adv_inp = vc_tgt + eps * ptb.tanh()
adv_emb = model.speaker_encoder(model.inference(vc_src, adv_inp))
loss = criterion(adv_emb, tgt_emb) - 0.1 * criterion(adv_emb, org_emb)
opt.zero_grad()
loss.backward()
opt.step()
return vc_tgt + eps * ptb.tanh()