-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
296 lines (246 loc) · 11.9 KB
/
model.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
import torch
import torch.nn as nn
from utils import Flatten, UnFlatten, save_animation, traversal_plotting
from disentanglement_lib import cycle_interval
import numpy as np
import torch.distributions as td
import os
import imageio
class ResidualEncoderBlock(nn.Module):
# Consider addring gated resnet block instead
# block_type is a string specifying the structure of the block, where:
# a = activation
# b = batch norm
# c = conv layer
# d = dropout.
# For example, bacd (batchnorm, activation, conv, dropout).
# TODO: ADDTT uses different number of filters in inner, should we consider that? I've only allowed same currently.
def __init__(self, c_in, c_out, nonlin=nn.ReLU(), kernel_size=3, block_type=None, dropout=None, stride=2):
super(ResidualEncoderBlock, self).__init__()
assert all(c in 'abcd' for c in block_type)
self.c_in, self.c_out = c_in, c_out
self.nonlin = nonlin
self.kernel_size = kernel_size
self.block_type = block_type
self.dropout = dropout
self.stride = stride
self.pre_conv = nn.Conv2d(c_in, c_out, kernel_size=kernel_size, padding=self.kernel_size // 2, stride=stride)
res = [] # Am considering throwing these if statements into separate function
for character in block_type:
if character == 'a':
res.append(nonlin)
elif character == 'b':
res.append(nn.BatchNorm2d(c_out))
elif character == 'c':
res.append(
nn.Conv2d(c_out, c_out, kernel_size=kernel_size, padding=self.kernel_size // 2)
)
elif character == 'd':
res.append(nn.Dropout2d(dropout))
self.res = nn.Sequential(*res)
self.post_conv = None # TODO: Ensure this should not be implemented, consult ADDTT
def forward(self, x):
x = self.pre_conv(x)
x = self.res(x) + x
if self.post_conv is not None:
x = self.post_conv(x)
return x.contiguous()
class ResidualDecoderBlock(nn.Module):
# Consider addring gated resnet block instead
# block_type is a string specifying the structure of the block, where:
# a = activation
# b = batch norm
# c = conv layer
# d = dropout.
# For example, bacd (batchnorm, activation, conv, dropout).
# TODO: ADDTT uses different number of filters in inner, should we consider that? I've only allowed same currently.
def __init__(self, c_in, c_out, nonlin=nn.ReLU(), kernel_size=3, block_type=None, dropout=None, stride=2):
super(ResidualDecoderBlock, self).__init__()
assert all(c in 'abcd' for c in block_type)
self.c_in, self.c_out = c_in, c_out
self.nonlin = nonlin
self.kernel_size = kernel_size
self.block_type = block_type
self.dropout = dropout
self.stride = stride
self.pre_conv = nn.ConvTranspose2d(
c_in, c_out, kernel_size=kernel_size, padding=self.kernel_size // 2, stride=stride, output_padding=1)
res = [] # Am considering throwing these if statements into separate function
for character in block_type:
if character == 'a':
res.append(nonlin)
elif character == 'b':
res.append(nn.BatchNorm2d(c_out))
elif character == 'c':
res.append(
nn.ConvTranspose2d(c_out, c_out, kernel_size=self.kernel_size, padding=self.kernel_size // 2)
)
elif character == 'd':
res.append(nn.Dropout2d(dropout))
self.res = nn.Sequential(*res)
self.post_conv = None # TODO: Ensure this should not be implemented, consult ADDTT
def forward(self, x):
x = self.pre_conv(x)
x = self.res(x) + x
if self.post_conv is not None:
x = self.post_conv(x)
return x.contiguous()
class BetaVAE_conv(nn.Module):
def __init__(self, filters=[32, 64, 128], latent=5, block_type='cabd', drop_rate=0.1, MNIST=False):
super(BetaVAE_conv, self).__init__()
self.filters = filters
self.latent = latent
self.img_dim = 28 if MNIST else 64
self.block_type = block_type
# Encoder
enc_layers = [ResidualEncoderBlock(1, filters[0], kernel_size=3, block_type=block_type, dropout=drop_rate)]
for i in range(len(filters) - 2):
enc_layers.append(ResidualEncoderBlock(filters[i],
filters[i + 1],
block_type=block_type,
dropout=drop_rate))
enc_layers.extend([ResidualEncoderBlock(filters[i+1], filters[i+2], block_type=block_type, dropout=drop_rate),
Flatten()])
self.encoder = nn.Sequential(*enc_layers)
# Latent
self.conv_out_dim = int((self.img_dim / 2 ** (len(filters))) ** 2 * filters[-1])
self.mu = nn.Linear(self.conv_out_dim, latent)
self.lv = nn.Linear(self.conv_out_dim, latent)
self.conv_prep = nn.Sequential(nn.Linear(latent, self.conv_out_dim), nn.ReLU())
# Decoder
dec_layers = [ResidualDecoderBlock(filters[-1], filters[-1], kernel_size=3, block_type=block_type, dropout=drop_rate)]
for i in reversed(range(1, len(filters)-1)):
dec_layers.append(ResidualDecoderBlock(filters[i],
filters[i - 1],
block_type=block_type,
dropout=drop_rate))
dec_layers.append(ResidualDecoderBlock(filters[0], 1, kernel_size=3, block_type=block_type, dropout=drop_rate))
self.decoder = nn.Sequential(*dec_layers)
def BottomUp(self, x):
out = self.encoder(x)
mu, lv = self.mu(out), self.lv(out)
return mu.contiguous(), lv.contiguous()
def reparameterize(self, mu, lv):
std = lv.mul(0.5).exp()
z = td.Normal(mu, std).rsample()
return z.contiguous()
def TopDown(self, x):
z = self.conv_prep(x)
unflatten_dim = int(np.sqrt(self.conv_out_dim / self.filters[-1]))
z = z.view(x.shape[0], self.filters[-1], unflatten_dim, unflatten_dim)
out = self.decoder(z)
return out
def forward(self, x):
mu, lv = self.BottomUp(x)
z = self.reparameterize(mu, lv)
out = self.TopDown(z)
return torch.sigmoid(out)
def calc_loss(self, x, beta):
mu, lv = self.BottomUp(x)
z = self.reparameterize(mu, lv)
out = torch.sigmoid(self.TopDown(z))
# zeros = torch.zeros_like(mu).detach()
# ones = torch.ones_like(lv).detach()
# p_x = td.Normal(loc=zeros, scale=ones)
# q_zGx = td.Normal(loc=mu, scale=lv.mul(0.5).exp())
# kl = td.kl_divergence(q_zGx, p_x).sum()# / x.shape[0]
# x = x*0.3081 + 0.1307
# nll = td.Bernoulli(logits=out).log_prob(x).sum() / x.shape[0]
# BCEWithLogitsLoss because binary_cross_entropy_with_logits will not accepts reduction = none
# nll = -nn.BCEWithLogitsLoss(reduction='none')(out, x).sum()# / x.shape[0]
nll = -nn.functional.binary_cross_entropy(out, x, reduction='sum') / x.shape[0]
kl = (-0.5 * torch.sum(1 + lv - mu.pow(2) - lv.exp()) + 1e-5) / x.shape[0]
# print(kl, nll, out.min(), out.max())
return (-nll + kl * beta).contiguous(), kl, nll
def LT_fitted_gauss_2std(self, x, num_var=6, num_traversal=5, gif_fps=5, silent=False):
# Cycle linearly through +-2 std dev of a fitted Gaussian.
mu, lv = self.BottomUp(x)
num_traversal += 1 if num_traversal % 2 == 0 else num_traversal
for i, batch_mu in enumerate(mu[:num_var]):
images = []
images.append(torch.sigmoid(self.TopDown(batch_mu.unsqueeze(0))))
for latent_var in range(batch_mu.shape[0]):
new_mu = batch_mu.unsqueeze(0).repeat([num_traversal, 1])
loc = mu[:, latent_var].mean()
total_var = lv[:, latent_var].exp().mean() + mu[:, latent_var].var()
scale = total_var.sqrt()
# gif
new_mu[:, latent_var] = cycle_interval(batch_mu[latent_var], num_traversal,
loc - 2 * scale, loc + 2 * scale)
filename = os.path.join(os.getcwd(), "figures/mu_gifs/mu%d_var%d.gif" % (i+1,latent_var+1))
save_animation(torch.sigmoid(self.TopDown(new_mu)), filename, num_traversal, fps=gif_fps) #gif
# Plot
new_mu[:, latent_var] = torch.linspace((loc - 2 * scale).item(),
(loc + 2 * scale).item(),
steps = num_traversal)
images.append(torch.sigmoid(self.TopDown(new_mu)))
img_name = os.path.join(os.getcwd(), "figures/traversals/Traversal%d.pdf" % (i+1))
traversal_plotting(images, img_name, num_traversals=num_traversal, silent=silent) # Traversal image
return images
def get_latent(self, x):
mu, _ = self.BottomUp(x)
return mu
class BetaVAE_Linear(nn.Module):
def __init__(self, n_hidden=[256, 64], latent=5):
super(BetaVAE_Linear, self).__init__()
self.n_hidden = n_hidden
self.latent = latent
# Encoder
self.encoder = nn.Sequential(
nn.Linear(784, n_hidden[0]), nn.ReLU(),
nn.Linear(n_hidden[0], n_hidden[1]), nn.ReLU(),
)
# Latent
self.mu = nn.Linear(n_hidden[-1], latent)
self.lv = nn.Linear(n_hidden[-1], latent)
# Decoder
self.decoder = nn.Sequential(
nn.Linear(latent, n_hidden[1]), nn.ReLU(),
nn.Linear(n_hidden[1], n_hidden[0]), nn.ReLU(),
nn.Linear(n_hidden[0], 784)
)
def BottomUp(self, x):
out = self.encoder(x)
mu, lv = self.mu(out), self.lv(out)
return mu, lv
def reparameterize(self, mu, lv):
std = lv.mul(0.5).exp()
z = td.Normal(mu, std).rsample()
return z
def TopDown(self, z):
out = self.decoder(z)
return out
def forward(self, x):
x = x.view(x.shape[0], -1)
mu, lv = self.BottomUp(x)
z = self.reparameterize(mu, lv)
out = self.TopDown(z)
return torch.sigmoid(out)
def calc_loss(self, x, beta):
x = x.view(x.shape[0], -1)
mu, lv = self.BottomUp(x)
z = self.reparameterize(mu, lv)
out = self.TopDown(z)
p_x = td.Normal(loc=0, scale=1)
q_zGx = td.Normal(loc=mu, scale=lv.mul(0.5).exp())
kl = td.kl_divergence(q_zGx, p_x).sum() / x.shape[0]
# x = x*0.3081 + 0.1307
nll = td.Bernoulli(logits=out).log_prob(x).sum() / x.shape[0]
# print(kl, nll)
return -nll + kl * beta, kl, nll
def LT_fitted_gauss_2std(self, x,num_var=6, num_traversal=5):
# Cycle linearly through +-2 std dev of a fitted Gaussian.
x = x.view(x.shape[0], -1)
mu, lv = self.BottomUp(x)
images = []
for i, batch_mu in enumerate(mu[:num_var]):
images.append(torch.sigmoid(self.TopDown(batch_mu)).unsqueeze(0))
for latent_var in range(batch_mu.shape[0]):
new_mu = batch_mu.unsqueeze(0).repeat([num_traversal, 1])
loc = mu[:, latent_var].mean()
total_var = lv[:, latent_var].exp().mean() + mu[:, latent_var].var()
scale = total_var.sqrt()
new_mu[:, latent_var] = cycle_interval(batch_mu[latent_var], num_traversal,
loc - 2 * scale, loc + 2 * scale)
images.append(torch.sigmoid(self.TopDown(new_mu)))
return images