forked from AntixK/PyTorch-VAE
-
Notifications
You must be signed in to change notification settings - Fork 1
/
experiment.py
247 lines (207 loc) · 10.4 KB
/
experiment.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
import math
import torch
from torch import optim
from models import BaseVAE
from models.types_ import *
from utils import data_loader
import pytorch_lightning as pl
from torchvision import transforms
import torchvision.utils as vutils
from torchvision.datasets import CelebA, MNIST, ImageFolder
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from csdataset import CSDataset
import torch.nn as nn
import torch.nn.functional as F
class VAEXperiment(pl.LightningModule):
def __init__(self,
vae_model: BaseVAE,
params: dict) -> None:
super(VAEXperiment, self).__init__()
self.model = vae_model
total_params = sum(p.numel()
for p in self.model.parameters() if p.requires_grad)
total_params = total_params/1000000
print("Total # parameter: " + str(total_params) + "M")
self.params = params
self.curr_device = None
self.hold_graph = False
try:
self.hold_graph = self.params['retain_first_backpass']
except:
pass
def forward(self, input: Tensor, **kwargs) -> Tensor:
return self.model(input, **kwargs)
def training_step(self, batch, batch_idx, optimizer_idx = 0):
real_img, labels = batch
self.curr_device = real_img.device
# print(real_img.min(), real_img.max())
results = self.forward(real_img, labels = labels)
# print(results[0].min(), results[0].max())
# print(torch.mean(torch.sum(((results[0] - real_img) ** 2))))
train_loss = self.model.loss_function(*results,
M_N = self.params['batch_size']/self.num_train_imgs,
optimizer_idx=optimizer_idx,
batch_idx = batch_idx)
self.logger.experiment.log({key: val.item() for key, val in train_loss.items()})
return train_loss
def validation_step(self, batch, batch_idx, optimizer_idx = 0):
real_img, labels = batch
self.curr_device = real_img.device
results = self.forward(real_img, labels = labels)
val_loss = self.model.loss_function(*results,
M_N = self.num_val_imgs/self.params['batch_size'],
optimizer_idx = optimizer_idx,
batch_idx = batch_idx)
return val_loss
def validation_end(self, outputs):
avg_loss = torch.stack([x['loss'] for x in outputs]).mean()
tensorboard_logs = {'avg_val_loss': avg_loss}
self.sample_images()
return {'val_loss': avg_loss, 'log': tensorboard_logs}
def sample_images(self):
# Get sample reconstruction image
test_input, test_label = next(iter(self.sample_dataloader))
test_input = test_input.to(self.curr_device)
test_label = test_label.to(self.curr_device)
recons = self.model.generate(test_input, labels = test_label)
# fig, ax = plt.subplots(1,2)
# fig.tight_layout()
# ax[0].imshow(test_input[0, 0].detach().cpu().data)
# ax[1].imshow(recons[0, 0].detach().cpu().data)
# plt.show()
# recons = F.interpolate(recons, (64,64), mode='bilinear')
vutils.save_image(recons.data,
f"{self.logger.save_dir}{self.logger.name}/version_{self.logger.version}/"
f"recons_{self.logger.name}_{self.current_epoch}.png",
normalize=True,
nrow=12)
# vutils.save_image(test_input.data,
# f"{self.logger.save_dir}{self.logger.name}/version_{self.logger.version}/"
# f"real_img_{self.logger.name}_{self.current_epoch}.png",
# normalize=True,
# nrow=12)
try:
samples = self.model.sample(144,
self.curr_device,
labels = test_label)
# samples = F.interpolate(samples, (64,64), mode='bilinear')
vutils.save_image(samples.cpu().data,
f"{self.logger.save_dir}{self.logger.name}/version_{self.logger.version}/"
f"{self.logger.name}_{self.current_epoch}.png",
normalize=True,
nrow=12)
except:
pass
del test_input, recons #, samples
def configure_optimizers(self):
optims = []
scheds = []
optimizer = optim.Adam(self.model.parameters(),
lr=self.params['LR'],
weight_decay=self.params['weight_decay'])
optims.append(optimizer)
# Check if more than 1 optimizer is required (Used for adversarial training)
try:
if self.params['LR_2'] is not None:
optimizer2 = optim.Adam(getattr(self.model,self.params['submodel']).parameters(),
lr=self.params['LR_2'])
optims.append(optimizer2)
except:
pass
try:
if self.params['scheduler_gamma'] is not None:
scheduler = optim.lr_scheduler.ExponentialLR(optims[0],
gamma = self.params['scheduler_gamma'])
scheds.append(scheduler)
# Check if another scheduler is required for the second optimizer
try:
if self.params['scheduler_gamma_2'] is not None:
scheduler2 = optim.lr_scheduler.ExponentialLR(optims[1],
gamma = self.params['scheduler_gamma_2'])
scheds.append(scheduler2)
except:
pass
return optims, scheds
except:
return optims
@data_loader
def train_dataloader(self):
transform = self.data_transforms()
if self.params['dataset'] == 'celeba':
dataset = CelebA(root = self.params['data_path'],
split = "train",
transform=transform,
download=True)
elif self.params['dataset'] == 'mnist':
dataset = MNIST(root = self.params['data_path'],
train=True,
transform=transform,
download=True)
elif self.params['dataset'] == 'currents':
dataset = CSDataset(root_dir = self.params['data_path'] + '/training/tiles_32',
transform=transform)
else:
raise ValueError('Undefined dataset type')
self.num_train_imgs = len(dataset)
print(self.num_train_imgs)
return DataLoader(dataset,
batch_size= self.params['batch_size'],
shuffle = True,
drop_last=True)
@data_loader
def val_dataloader(self):
transform = self.data_transforms()
if self.params['dataset'] == 'celeba':
self.sample_dataloader = DataLoader(CelebA(root = self.params['data_path'],
split = "test",
transform=transform,
download=True),
batch_size= 144,
shuffle = True,
drop_last=True)
self.num_val_imgs = len(self.sample_dataloader)
elif self.params['dataset'] == 'mnist':
self.sample_dataloader = DataLoader(MNIST(root = self.params['data_path'],
train=False,
transform=transform,
download=True),
batch_size= 144,
shuffle = True,
drop_last=True)
self.num_val_imgs = len(self.sample_dataloader)
elif self.params['dataset'] == 'currents':
dataset = CSDataset(root_dir = self.params['data_path'] + '/testing/tiles_32',
transform=transform)
self.sample_dataloader = DataLoader(dataset,
batch_size= 144,
shuffle = True,
drop_last=True)
self.num_val_imgs = len(dataset)
else:
raise ValueError('Undefined dataset type')
print(self.num_val_imgs)
return self.sample_dataloader
def data_transforms(self):
SetRange = transforms.Lambda(lambda X: 2 * X - 1.)
SetScale = transforms.Lambda(lambda X: X/X.sum(0).expand_as(X))
if self.params['dataset'] == 'celeba':
transform = transforms.Compose([transforms.RandomHorizontalFlip(),
transforms.CenterCrop(148),
transforms.Resize(self.params['img_size']),
transforms.ToTensor(),
SetRange])
elif self.params['dataset'] == 'mnist':
transform = transforms.Compose([transforms.Resize(self.params['img_size']),
transforms.ToTensor(),
SetRange])
elif self.params['dataset'] == 'currents':
transform = transforms.Compose([transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.Resize(self.params['img_size']),
transforms.ToTensor(),
# SetRange])
])
else:
raise ValueError('Undefined dataset type')
return transform