-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvat.py
55 lines (43 loc) · 1.82 KB
/
vat.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
import torch
import torch.nn as nn
import torch.nn.functional as F
from myargs import args
class ConditionalEntropyLoss(torch.nn.Module):
def __init__(self):
super(ConditionalEntropyLoss, self).__init__()
def forward(self, x):
b = F.softmax(x, dim=1) * F.log_softmax(x, dim=1)
b = b.sum(dim=1)
return -1.0 * b.mean(dim=0)
class VAT(nn.Module):
def __init__(self, model):
super(VAT, self).__init__()
self.n_power = args.n_power
self.XI = 1e-6
self.model = model
self.epsilon = args.radius
def forward(self, X, logit):
vat_loss = self.virtual_adversarial_loss(X, logit)
return vat_loss
def generate_virtual_adversarial_perturbation(self, x, logit):
d = torch.randn_like(x, device='cuda')
for _ in range(self.n_power):
d = self.XI * self.get_normalized_vector(d).requires_grad_()
_, logit_m = self.model(x + d)
dist = self.kl_divergence_with_logit(logit, logit_m)
grad = torch.autograd.grad(dist, [d])[0]
d = grad.detach()
return self.epsilon * self.get_normalized_vector(d)
def kl_divergence_with_logit(self, q_logit, p_logit):
q = F.softmax(q_logit, dim=1)
qlogq = torch.mean(torch.sum(q * F.log_softmax(q_logit, dim=1), dim=1))
qlogp = torch.mean(torch.sum(q * F.log_softmax(p_logit, dim=1), dim=1))
return qlogq - qlogp
def get_normalized_vector(self, d):
return F.normalize(d.view(d.size(0), -1), p=2, dim=1).reshape(d.size())
def virtual_adversarial_loss(self, x, logit):
r_vadv = self.generate_virtual_adversarial_perturbation(x, logit)
logit_p = logit.detach()
_, logit_m = self.model(x + r_vadv)
loss = self.kl_divergence_with_logit(logit_p, logit_m)
return loss