-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
179 lines (132 loc) · 4.99 KB
/
train.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
#!/usr/bin/env python
import sys
import torch
import torch.nn
import torch.optim
from torch.nn.functional import avg_pool2d, interpolate
from torch.autograd import Variable
import numpy as np
import tqdm
import matplotlib.pyplot as plt
import config as c
import opts
opts.parse(sys.argv)
config_str = ""
config_str += "==="*30 + "\n"
config_str += "Config options:\n\n"
for v in dir(c):
if v[0]=='_': continue
s=eval('c.%s'%(v))
config_str += " {:25}\t{}\n".format(v,s)
config_str += "==="*30 + "\n"
print(config_str)
import model
import data
class dummy_loss(object):
def item(self):
return 1.
def sample_outputs(sigma):
return sigma * torch.cuda.FloatTensor(c.batch_size, c.output_dim).normal_()
def img_tile(imgs, row_col = None, transpose = False, channel_first=True, channels=3):
'''
tile a list of images to a large grid.
imgs: iterable of images to use
row_col: None (automatic), or tuple of (#rows, #columns)
transpose: Wheter to stitch the list of images row-first or column-first
channel_first: if true, assume images with CxWxH, else WxHxC
channels: 3 or 1, number of color channels
'''
if row_col == None:
sqrt = np.sqrt(len(imgs))
rows = np.floor(sqrt)
delt = sqrt - rows
cols = np.ceil(rows + 2*delt + delt**2 / rows)
rows, cols = int(rows), int(cols)
else:
rows, cols = row_col
if channel_first:
h, w = imgs[0].shape[1], imgs[0].shape[2]
else:
h, w = imgs[0].shape[0], imgs[0].shape[1]
show_im = np.zeros((rows*h, cols*w, channels))
if transpose:
def iterator():
for i in range(rows):
for j in range(cols):
yield i, j
else:
def iterator():
for j in range(cols):
for i in range(rows):
yield i, j
k = 0
for i, j in iterator():
im = imgs[k]
if channel_first:
im = np.transpose(im, (1, 2, 0))
show_im[h*i:h*i+h, w*j:w*j+w] = im
k += 1
if k == len(imgs):
break
return np.squeeze(show_im)
try:
fixed_noise = sample_outputs(1.0)
for i_epoch in range(-c.pre_low_lr, c.n_epochs):
loss_history = []
data_iter = iter(data.train_loader)
if i_epoch < 0:
for param_group in model.optim.param_groups:
param_group['lr'] = c.lr * 2e-2
for i_batch, data_tuple in tqdm.tqdm(enumerate(data_iter),
total=min(len(data.train_loader), c.n_its_per_epoch),
leave=False,
mininterval=1.,
disable=(not c.progress_bar),
ncols=83):
x, y = data_tuple
x = x.cuda()
x += c.add_image_noise * torch.cuda.FloatTensor(x.shape).normal_()
output = model.model(x)
if c.do_fwd:
zz = torch.sum(output**2, dim=1)
jac = model.model.log_jacobian(run_forward=False)
neg_log_likeli = 0.5 * zz - jac
l = torch.mean(neg_log_likeli)
l.backward(retain_graph=c.do_rev)
else:
l = dummy_loss()
if c.do_rev:
samples_noisy = sample_outputs(c.latent_noise) + output.data
x_rec = model.model(samples_noisy, rev=True)
l_rev = torch.mean((x-x_rec)**2)
l_rev.backward()
else:
l_rev = dummy_loss()
model.optim_step()
loss_history.append([l.item(), l_rev.item()])
if i_batch+1 >= c.n_its_per_epoch:
# somehow the data loader workers don't shut down automatically
try:
data_iter._shutdown_workers()
except:
pass
break
model.weight_scheduler.step()
epoch_losses = np.mean(np.array(loss_history), axis=0)
epoch_losses[0] = min(epoch_losses[0], 0)
if i_epoch > 1 - c.pre_low_lr:
print(epoch_losses, flush=True)
model.model.zero_grad()
if (i_epoch % c.checkpoint_save_interval) == 0:
model.save(c.filename + '_checkpoint_%.4i' % (i_epoch * (1-c.checkpoint_save_overwrite)))
with torch.no_grad():
rev_imgs = model.model(fixed_noise, rev=True)
rev_imgs = torch.clamp(rev_imgs, 0., 1.)
imgs = [rev_imgs[i].cpu().data.numpy() for i in range(c.batch_size)]
imgs = img_tile(imgs, (8, 8), transpose=False, channel_first=True, channels=3)
plt.imsave(F'./training_images/random_samples_{i_epoch}.png', imgs, vmin=0, vmax=1, dpi=300)
model.save(c.filename)
except:
if c.checkpoint_on_error:
model.save(c.filename + '_ABORT')
raise