-
Notifications
You must be signed in to change notification settings - Fork 2
/
vae.py
314 lines (259 loc) · 11.7 KB
/
vae.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
Train Variational Autoencoder (CNN)
Code taken from "@PyTorchLightning/pytorch-lightning-bolts"
"""
import os
from argparse import ArgumentParser
import torch
from torch import optim
from torch import distributions
from torch.nn import functional as F
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers import MLFlowLogger
from pythor.datamodules import MNISTDataLoaders
from pythor.Networks.Convolutional.Autoencoder.vae_components import Encoder, Decoder
from pythor.bots.botCallback import TelegramBotCallback
from pythor.bots.dl_bot import DLBot
from pythor.bots.config import telegram_config
optimizers = {
'adam': optim.Adam,
'adamax': optim.Adamax,
'rmsprop': optim.RMSprop,
}
class VAE(LightningModule):
def __init__(
self,
hparams=None,
):
"""
Convolutional Variational Autoencoder
Parameters to be included in hparams
-----------
input_width: int
input image width for image (must be even)
Default: 28
input_height: int
input image height for image (must be even)
Default: 28
hidden_dim: int
hidden layer dimension
Default: 128
latent_dim: int
latent layer dimension
Default: 32
batch_size: int
Batch Size for training
Default: 32
opt : str
One of 'adam' or 'adamax' or 'rmsprop'.
Default : 'adam'
lr: float
Learning rate for optimizer.
Default : 0.001
weight_decay: float
Weight decay in optimizer.
Default : 0
"""
super().__init__()
# attach hparams to log hparams to the loggers (like tensorboard)
self.__check_hparams(hparams)
self.hparams = hparams
# NOTE Change dataloaders appropriately
self.dataloaders = MNISTDataLoaders(save_path=os.getcwd())
self.telegrad_logs = {} # log everything you want to be reported via telegram here
self.encoder = self.init_encoder(self.hidden_dim, self.latent_dim,
self.input_width, self.input_height)
self.decoder = self.init_decoder(self.hidden_dim, self.latent_dim,
self.input_width, self.input_height)
def __check_hparams(self, hparams):
self.hidden_dim = hparams.hidden_dim if hasattr(hparams, 'hidden_dim') else 128
self.latent_dim = hparams.latent_dim if hasattr(hparams, 'latent_dim') else 32
self.input_width = hparams.input_width if hasattr(hparams, 'input_width') else 28
self.input_height = hparams.input_height if hasattr(hparams, 'input_height') else 28
self.opt = hparams.opt if hasattr(hparams,'opt') else 'adam'
self.batch_size = hparams.batch_size if hasattr(hparams,'batch_size') else 32
self.lr = hparams.lr if hasattr(hparams,'lr') else 0.001
self.weight_decay = hparams.weight_decay if hasattr(hparams,'weight_decay') else 0
def init_encoder(self, hidden_dim, latent_dim, input_width, input_height):
encoder = Encoder(hidden_dim, latent_dim, input_width, input_height)
return encoder
def init_decoder(self, hidden_dim, latent_dim, input_width, input_height):
decoder = Decoder(hidden_dim, latent_dim, input_width, input_height)
return decoder
def get_prior(self, z_mu, z_std):
# Prior ~ Normal(0,1)
P = distributions.normal.Normal(loc=torch.zeros_like(z_mu), scale=torch.ones_like(z_std))
return P
def get_approx_posterior(self, z_mu, z_std):
# Approx Posterior ~ Normal(mu, sigma)
Q = distributions.normal.Normal(loc=z_mu, scale=z_std)
return Q
def elbo_loss(self, x, P, Q):
# Reconstruction loss
z = Q.rsample()
pxz = self(z)
recon_loss = F.binary_cross_entropy(pxz, x, reduction='none')
# sum across dimensions because sum of log probabilities of iid univariate gaussians is the same as
# multivariate gaussian
recon_loss = recon_loss.sum(dim=-1)
# KL divergence loss
log_qz = Q.log_prob(z)
log_pz = P.log_prob(z)
kl_div = (log_qz - log_pz).sum(dim=1)
# ELBO = reconstruction + KL
loss = recon_loss + kl_div
# average over batch
loss = loss.mean()
recon_loss = recon_loss.mean()
kl_div = kl_div.mean()
return loss, recon_loss, kl_div, pxz
def forward(self, z):
return self.decoder(z)
def _run_step(self, batch):
x, _ = batch
z_mu, z_log_var = self.encoder(x)
z_std = torch.exp(z_log_var / 2)
P = self.get_prior(z_mu, z_std)
Q = self.get_approx_posterior(z_mu, z_std)
x = x.view(x.size(0), -1)
loss, recon_loss, kl_div, pxz = self.elbo_loss(x, P, Q)
return loss, recon_loss, kl_div, pxz
def training_step(self, batch, batch_idx):
loss, recon_loss, kl_div, pxz = self._run_step(batch)
logs = {
'train_elbo_loss': loss,
'train_recon_loss': recon_loss,
'train_kl_loss': kl_div
}
return {'loss': loss, 'log': logs}
def training_epoch_end(self, outputs):
avg_loss = torch.stack([x['train_elbo_loss'] for x in outputs]).mean()
recon_loss = torch.stack([x['train_recon_loss'] for x in outputs]).mean()
kl_loss = torch.stack([x['train_kl_loss'] for x in outputs]).mean()
logs = {'train_elbo_loss_epoch': avg_loss,
'val_recon_loss_epoch': recon_loss,
'val_kl_loss_epoch': kl_loss}
self.telegrad_logs['lr'] = self.lr # for telegram bot
self.telegrad_logs['trainer_loss_epoch'] = avg_loss.item() # for telegram bot
self.telegrad_logs['train_recon_loss_epoch'] = recon_loss.item() # for telegram bot
self.telegrad_logs['train_kl_loss_epoch'] = kl_loss.item() # for telegram bot
self.logger.log_metrics({'learning_rate':self.lr}) # if lr is changed by telegram bot
return {
'avg_train_loss': avg_loss,
'log': logs
}
def validation_step(self, batch, batch_idx):
loss, recon_loss, kl_div, pxz = self._run_step(batch)
return {
'val_loss': loss,
'val_recon_loss': recon_loss,
'val_kl_div': kl_div,
'pxz': pxz
}
def validation_epoch_end(self, outputs):
avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
recon_loss = torch.stack([x['val_recon_loss'] for x in outputs]).mean()
kl_loss = torch.stack([x['val_kl_div'] for x in outputs]).mean()
logs = {'val_elbo_loss': avg_loss,
'val_recon_loss': recon_loss,
'val_kl_loss': kl_loss}
self.telegrad_logs['val_loss_epoch'] = avg_loss.item() # for telegram bot
self.telegrad_logs['val_recon_loss_epoch'] = recon_loss.item() # for telegram bot
self.telegrad_logs['val__kl_loss_epoch'] = kl_loss.item() # for telegram bot
return {
'avg_val_loss': avg_loss,
'log': logs
}
def test_step(self, batch, batch_idx):
loss, recon_loss, kl_div, pxz = self._run_step(batch)
return {
'test_loss': loss,
'test_recon_loss': recon_loss,
'test_kl_div': kl_div,
'pxz': pxz
}
def test_epoch_end(self, outputs):
avg_loss = torch.stack([x['test_loss'] for x in outputs]).mean()
recon_loss = torch.stack([x['test_recon_loss'] for x in outputs]).mean()
kl_loss = torch.stack([x['test_kl_div'] for x in outputs]).mean()
logs = {'test_elbo_loss': avg_loss,
'test_recon_loss': recon_loss,
'test_kl_loss': kl_loss}
return {
'avg_test_loss': avg_loss,
'log': logs
}
def configure_optimizers(self):
return optimizers[self.opt](self.parameters(), lr=self.lr, weight_decay=self.weight_decay)
def prepare_data(self):
self.dataloaders.prepare_data()
def train_dataloader(self):
return self.dataloaders.train_dataloader(self.batch_size)
def val_dataloader(self):
return self.dataloaders.val_dataloader(self.batch_size)
def test_dataloader(self):
return self.dataloaders.test_dataloader(self.batch_size)
@staticmethod
def add_model_specific_args(parent_parser):
parser = ArgumentParser(parents=[parent_parser], add_help=False)
parser.add_argument('--hidden_dim', type=int, default=128,
help='itermediate layers dimension before embedding for default encoder/decoder')
parser.add_argument('--latent_dim', type=int, default=32,
help='dimension of latent variables z')
parser.add_argument('--input_width', type=int, default=28,
help='input image width - 28 for MNIST (must be even)')
parser.add_argument('--input_height', type=int, default=28,
help='input image height - 28 for MNIST (must be even)')
parser.add_argument('--batch_size', type=int, default=32,
help='input vector shape for MNIST')
# optimizer
parser.add_argument('--opt', type=str, default='adam', choices=['adam', 'adamax', 'rmsprop'],
help='optimizer type for optimization')
parser.add_argument('--lr', type=float, default=0.001,
help='learning rate')
parser.add_argument('--weight_decay', type=float, default=0,
help='weight decay in optimizer')
return parser
def main():
parser = ArgumentParser()
# using this will log all params in mlflow board automatically
parser = Trainer.add_argparse_args(parser)
parser = VAE.add_model_specific_args(parser)
args = parser.parse_args()
experiment_name = 'ConvVAE'
# tb_logger = loggers.TensorBoardLogger('logs')
mlf_logger = MLFlowLogger(
experiment_name=experiment_name,
tracking_uri="file:./mlruns"
)
save_folder = 'model_weights/' + experiment_name + '/'
if not os.path.exists(save_folder):
os.mkdir(save_folder)
save_folder = save_folder + mlf_logger.run_id + '/'
if not os.path.exists(save_folder):
os.mkdir(save_folder)
early_stopping = EarlyStopping('avg_val_loss')
# saves checkpoints to 'save_folder' whenever 'val_loss' has a new min
checkpoint_callback = ModelCheckpoint(
filepath=save_folder+'/model_{epoch:02d}-{val_loss:.2f}')
# telegram
token = telegram_config['token']
user_id = telegram_config['user_id']
bot = DLBot(token=token, user_id=user_id)
telegramCallback = TelegramBotCallback(bot)
model = VAE(args)
trainer = Trainer(checkpoint_callback=checkpoint_callback,
early_stop_callback=early_stopping,
fast_dev_run=False, # make this as True only to check for bugs
max_epochs=1000,
resume_from_checkpoint=None, # change this to model_path
logger=mlf_logger, # mlflow logger
callbacks=[telegramCallback], # telegrad
)
trainer.fit(model)
trainer.test()
if __name__ == "__main__":
main()