forked from chj1330/emotionalVC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvawgan.py
202 lines (159 loc) · 5.81 KB
/
vawgan.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
'''
VAE-WGAN with convolution and gradient penalty
'''
import torch
import torch.nn as nn
from math import ceil
def _sanity_check(outputs, kernels, strides):
assert len(outputs) == len(kernels) == len(strides) > 2
def convblock(c_in, c_out, kernel, stride, pad=True, L=0, transpose=False,
activation=nn.LeakyReLU(), batchnorm=True):
if pad:
# tensorflow SAME padding
need = -L % stride + kernel - stride
pad = ceil(need / 2)
else:
pad = 0
layers = []
if transpose:
layers.append(nn.ConvTranspose1d(c_in, c_out, kernel, stride, pad))
else:
layers.append(nn.Conv1d(c_in, c_out, kernel, stride, pad))
layers.append(activation)
if batchnorm:
layers.append(nn.BatchNorm1d(c_out))
return nn.Sequential(*layers)
## MODEL ##
class Encoder(nn.Module):
'''
len_in, z_dim: int
outputs, kernels, strides: list of int
IN: tensor (batch, len_in)
OUT: mean, logvar tensors (batch, z_dim)
'''
def __init__(self, len_in, z_dim, outputs, kernels, strides):
super().__init__()
_sanity_check(outputs, kernels, strides)
# convs
blocks = []
cur_len, cur_out = len_in, 1
for o, k, s in zip(outputs, kernels, strides):
blocks.append(convblock(cur_out, o, k, s, L=cur_len))
cur_len, cur_out = ceil(cur_len / s), o
self.blocks = nn.Sequential(*blocks)
# Gaussian stats
self.fc_mean = nn.Linear(cur_len * cur_out, z_dim)
self.fc_logvar = nn.Linear(cur_len * cur_out, z_dim)
def forward(self, x):
x = x.unsqueeze(1) # N, 1, L
x = self.blocks(x) # N, C, L
x = x.view(x.shape[0], -1) # N, L*C
return self.fc_mean(x), self.fc_logvar(x)
class Generator(nn.Module):
'''
len_out, z_dim, y_dim, merge_dim, init_c: int
outputs, kernels, strides: list of int
IN: tensor (batch, z_dim), condition tensor (batch,)
OUT: tensor (batch, len_out)
'''
def __init__(self, len_out, z_dim, y_dim, merge_dim, init_c,
outputs, kernels, strides):
super().__init__()
_sanity_check(outputs, kernels, strides)
# embed, merge condition
self.y = nn.Embedding(y_dim, merge_dim)
self.fc_z = nn.Linear(z_dim, merge_dim)
# init reshape
self.init_l = len_out
for s in strides:
self.init_l //= s
self.init_c = init_c
self.fc_reshape = nn.Sequential(
nn.Linear(2*merge_dim, self.init_l * self.init_c),
nn.LeakyReLU(),
nn.BatchNorm1d(self.init_l * self.init_c)
)
# transpose convs
blocks = []
cur_out = init_c
for o, k, s in zip(outputs[:-1], kernels[:-1], strides[:-1]):
blocks.append(convblock(cur_out, o, k, s, transpose=True))
cur_out = o
# no batchnorm, use tanh before output
blocks.append(convblock(cur_out, outputs[-1], kernels[-1], strides[-1],
transpose=True, activation=nn.Tanh(), batchnorm=False))
self.blocks = nn.Sequential(*blocks)
def forward(self, z, condition):
out = torch.cat([self.fc_z(z), self.y(condition)], 1)
out = nn.functional.leaky_relu(out)
out = self.fc_reshape(out) # N, L*C
out = out.view(-1, self.init_c, self.init_l) # N, C, L
out = self.blocks(out) # N, 1, L
return out.squeeze(1)
class Discriminator(nn.Module):
'''
len_in, y_dim: int
outputs, kernels, strides: list of int
IN: tensor (batch, len_in), condition tensor (batch,)
OUT: tensor (batch,)
'''
def __init__(self, len_in, y_dim, outputs, kernels, strides):
super().__init__()
_sanity_check(outputs, kernels, strides)
# embed condition
self.y = nn.Embedding(y_dim, len_in)
# convs
blocks = []
cur_len, cur_out = len_in, 2
for o, k, s in zip(outputs, kernels, strides):
# no batchnorm for WGAN-GP
blocks.append(convblock(cur_out, o, k, s, L=cur_len, batchnorm=False))
cur_len, cur_out = ceil(cur_len / s), o
self.blocks = nn.Sequential(*blocks)
# output score
self.fc_score = nn.Linear(cur_len * cur_out, 1)
def forward(self, x, condition):
x = x.unsqueeze(1)
y = self.y(condition).unsqueeze(1)
out = torch.cat([x, y], 1) # N, 2, L
out = self.blocks(out) # N, C, L
out = out.view(x.shape[0], -1) # N, L*C
out = self.fc_score(out) # N, 1
return out.squeeze(1)
## VAE ##
def reparameterize(mean, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mean + eps * std
def forward_VAE(E, G, x, cond):
'''
VAE forward pass
E: Encoder
G: Generator
x: FloatTensor (batch, L)
cond: LongTensor (batch,)
Returns: xh FloatTensor (batch, L)
(mean, logvar) of z
'''
mean, logvar = E(x)
z = reparameterize(mean, logvar)
xh = G(z, cond)
return xh, (mean, logvar)
## LOSS FUNCTIONS ##
def recon_loss(real, fake):
return nn.functional.mse_loss(fake, real)
def kld_loss(mean, logvar):
var = logvar.exp()
return 0.5 * torch.mean(var + mean.pow(2) - logvar - 1)
def wgan_loss(D, real, fake, cond):
return torch.mean(D(real, cond) - D(fake, cond))
def gradient_penalty(D, real, fake, cond):
# random point between real, fake
a = torch.rand_like(real[:, 0]).unsqueeze(1)
interpolates = (a * real.data + (1-a) * fake.data).requires_grad_(True)
d_interpolates = D(interpolates, cond.data)
init = torch.ones_like(d_interpolates)
grads = torch.autograd.grad(d_interpolates, interpolates, grad_outputs=init,
create_graph=True, retain_graph=True)[0]
gp = ((grads.norm(2, dim=1) - 1) ** 2).mean()
return gp