-
Notifications
You must be signed in to change notification settings - Fork 22
/
trainer_mmd.py
309 lines (272 loc) · 13.1 KB
/
trainer_mmd.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
"""trainer_mmd.py"""
import math
from pathlib import Path
from tqdm import tqdm
import visdom
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.utils import make_grid, save_image
from model import WAE
from utils import DataGather
from ops import reconstruction_loss, mmd, im_kernel_sum, multistep_lr_decay, cuda
from dataset import return_data
class Trainer(object):
def __init__(self, args):
self.use_cuda = args.cuda and torch.cuda.is_available()
self.max_epoch = args.max_epoch
self.global_epoch = 0
self.global_iter = 0
self.z_dim = args.z_dim
self.z_var = args.z_var
self.z_sigma = math.sqrt(args.z_var)
self._lambda = args.reg_weight
self.lr = args.lr
self.beta1 = args.beta1
self.beta2 = args.beta2
self.lr_schedules = {30:2, 50:5, 100:10}
if args.dataset.lower() == 'celeba':
self.nc = 3
self.decoder_dist = 'gaussian'
else:
raise NotImplementedError
net = WAE
self.net = cuda(net(self.z_dim, self.nc), self.use_cuda)
self.optim = optim.Adam(self.net.parameters(), lr=self.lr,
betas=(self.beta1, self.beta2))
self.gather = DataGather()
self.viz_name = args.viz_name
self.viz_port = args.viz_port
self.viz_on = args.viz_on
if self.viz_on:
self.viz = visdom.Visdom(env=self.viz_name+'_lines', port=self.viz_port)
self.win_recon = None
self.win_mmd = None
self.win_mu = None
self.win_var = None
self.ckpt_dir = Path(args.ckpt_dir).joinpath(args.viz_name)
if not self.ckpt_dir.exists():
self.ckpt_dir.mkdir(parents=True, exist_ok=True)
self.ckpt_name = args.ckpt_name
if self.ckpt_name is not None:
self.load_checkpoint(self.ckpt_name)
self.save_output = args.save_output
self.output_dir = Path(args.output_dir).joinpath(args.viz_name)
if not self.output_dir.exists():
self.output_dir.mkdir(parents=True, exist_ok=True)
self.dset_dir = args.dset_dir
self.dataset = args.dataset
self.batch_size = args.batch_size
self.data_loader = return_data(args)
def train(self):
self.net.train()
iters_per_epoch = len(self.data_loader)
max_iter = self.max_epoch*iters_per_epoch
pbar = tqdm(total=max_iter)
with tqdm(total=max_iter) as pbar:
pbar.update(self.global_iter)
out = False
while not out:
for x in self.data_loader:
pbar.update(1)
self.global_iter += 1
if self.global_iter % iters_per_epoch == 0:
self.global_epoch += 1
self.optim = multistep_lr_decay(self.optim, self.global_epoch, self.lr_schedules)
x = Variable(cuda(x, self.use_cuda))
x_recon, z_tilde = self.net(x)
z = self.sample_z(template=z_tilde, sigma=self.z_sigma)
recon_loss = F.mse_loss(x_recon, x, size_average=False).div(self.batch_size)
mmd_loss = mmd(z_tilde, z, z_var=self.z_var)
total_loss = recon_loss + self._lambda*mmd_loss
self.optim.zero_grad()
total_loss.backward()
self.optim.step()
if self.global_iter%1000 == 0:
self.gather.insert(iter=self.global_iter,
mu=z.mean(0).data, var=z.var(0).data,
recon_loss=recon_loss.data, mmd_loss=mmd_loss.data,)
if self.global_iter%5000 == 0:
self.gather.insert(images=x.data)
self.gather.insert(images=x_recon.data)
self.viz_reconstruction()
self.viz_lines()
self.sample_x_from_z(n_sample=100)
self.gather.flush()
self.save_checkpoint('last')
pbar.write('[{}] total_loss:{:.3f} recon_loss:{:.3f} mmd_loss:{:.3f}'.format(
self.global_iter, total_loss.data[0], recon_loss.data[0], mmd_loss.data[0]))
if self.global_iter%20000 == 0:
self.save_checkpoint(str(self.global_iter))
if self.global_iter >= max_iter:
out = True
break
pbar.write("[Training Finished]")
def viz_reconstruction(self):
self.net.eval()
x = self.gather.data['images'][0][:100]
x = make_grid(x, normalize=True, nrow=10)
x_recon = F.sigmoid(self.gather.data['images'][1][:100])
x_recon = make_grid(x_recon, normalize=True, nrow=10)
images = torch.stack([x, x_recon], dim=0).cpu()
self.viz.images(images, env=self.viz_name+'_reconstruction',
opts=dict(title=str(self.global_iter)), nrow=2)
self.net.train()
def viz_lines(self):
self.net.eval()
recon_losses = torch.stack(self.gather.data['recon_loss']).cpu()
mmd_losses = torch.stack(self.gather.data['mmd_loss']).cpu()
mus = torch.stack(self.gather.data['mu']).cpu()
vars = torch.stack(self.gather.data['var']).cpu()
iters = torch.Tensor(self.gather.data['iter'])
legend = []
for z_j in range(self.z_dim):
legend.append('z_{}'.format(z_j))
if self.win_recon is None:
self.win_recon = self.viz.line(
X=iters,
Y=recon_losses,
env=self.viz_name+'_lines',
opts=dict(
width=400,
height=400,
xlabel='iteration',
title='reconsturction loss',))
else:
self.win_recon = self.viz.line(
X=iters,
Y=recon_losses,
env=self.viz_name+'_lines',
win=self.win_recon,
update='append',
opts=dict(
width=400,
height=400,
xlabel='iteration',
title='reconsturction loss',))
if self.win_mmd is None:
self.win_mmd = self.viz.line(
X=iters,
Y=mmd_losses,
env=self.viz_name+'_lines',
opts=dict(
width=400,
height=400,
xlabel='iteration',
title='maximum mean discrepancy',))
else:
self.win_mmd = self.viz.line(
X=iters,
Y=mmd_losses,
env=self.viz_name+'_lines',
win=self.win_mmd,
update='append',
opts=dict(
width=400,
height=400,
xlabel='iteration',
title='maximum mean discrepancy',))
if self.win_mu is None:
self.win_mu = self.viz.line(
X=iters,
Y=mus,
env=self.viz_name+'_lines',
opts=dict(
width=400,
height=400,
legend=legend,
xlabel='iteration',
title='posterior mean',))
else:
self.win_mu = self.viz.line(
X=iters,
Y=vars,
env=self.viz_name+'_lines',
win=self.win_mu,
update='append',
opts=dict(
width=400,
height=400,
legend=legend,
xlabel='iteration',
title='posterior mean',))
if self.win_var is None:
self.win_var = self.viz.line(
X=iters,
Y=vars,
env=self.viz_name+'_lines',
opts=dict(
width=400,
height=400,
legend=legend,
xlabel='iteration',
title='posterior variance',))
else:
self.win_var = self.viz.line(
X=iters,
Y=vars,
env=self.viz_name+'_lines',
win=self.win_var,
update='append',
opts=dict(
width=400,
height=400,
legend=legend,
xlabel='iteration',
title='posterior variance',))
self.net.train()
def sample_z(self, n_sample=None, dim=None, sigma=None, template=None):
if n_sample is None:
n_sample = self.batch_size
if dim is None:
dim = self.z_dim
if sigma is None:
sigma = self.z_sigma
if template is not None:
z = sigma*Variable(template.data.new(template.size()).normal_())
else:
z = sigma*torch.randn(n_sample, dim)
z = Variable(cuda(z, self.use_cuda))
return z
def sample_x_from_z(self, n_sample):
self.net.eval()
z = self.sample_z(n_sample=n_sample, sigma=self.z_sigma)
x_gen = F.sigmoid(self.net._decode(z)[:100]).data.cpu()
x_gen = make_grid(x_gen, normalize=True, nrow=10)
self.viz.images(x_gen, env=self.viz_name+'_sampling_from_random_z',
opts=dict(title=str(self.global_iter)))
self.net.train()
def save_checkpoint(self, filename, silent=True):
model_states = {'net':self.net.state_dict(),}
optim_states = {'optim':self.optim.state_dict(),}
win_states = {'recon':self.win_recon,
'mmd':self.win_mmd,
'mu':self.win_mu,
'var':self.win_var,}
states = {'iter':self.global_iter,
'epoch':self.global_epoch,
'win_states':win_states,
'model_states':model_states,
'optim_states':optim_states}
file_path = self.ckpt_dir.joinpath(filename)
torch.save(states, file_path.open('wb+'))
if not silent:
print("=> saved checkpoint '{}' (iter {})".format(file_path, self.global_iter))
def load_checkpoint(self, filename, silent=False):
file_path = self.ckpt_dir.joinpath(filename)
if file_path.is_file():
checkpoint = torch.load(file_path.open('rb'))
self.global_iter = checkpoint['iter']
self.global_epoch = checkpoint['epoch']
self.win_recon = checkpoint['win_states']['recon']
self.win_mmd = checkpoint['win_states']['mmd']
self.win_var = checkpoint['win_states']['var']
self.win_mu = checkpoint['win_states']['mu']
self.net.load_state_dict(checkpoint['model_states']['net'])
self.optim.load_state_dict(checkpoint['optim_states']['optim'])
if not silent:
print("=> loaded checkpoint '{} (iter {})'".format(file_path, self.global_iter))
else:
if not silent:
print("=> no checkpoint found at '{}'".format(file_path))