-
Notifications
You must be signed in to change notification settings - Fork 4
/
run.py
411 lines (303 loc) · 13.8 KB
/
run.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# Copyright (c) 2018-present, Borealis AI.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Author: Yanshuai Cao
import sys
import time
import os
import theano
import lasagne
import numpy as np
import subprocess
from collections import OrderedDict, defaultdict
import gc
# os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
# theano.config.profile = True
# theano.config.profile_memory = True
from utils.datasets import gen_cifar10, gen_celeba
import lasagne.layers as ll
from joblib import dump, load
from utils import batch, registery_factory, \
dump_params, set_default, dict2hash, find_last_saved, \
lin_anneal, get_network_str, tile_and_save_samples
from models import GanModel
import logging
sys.setrecursionlimit(10000)
floatX = np.float32
FORCE_NO_RELOAD = 1
############################################################
def config_logging(filename='example.log', format="%(message)s"):
logging.basicConfig(
filename=filename,
format=format,
level=logging.DEBUG)
root = logging.getLogger()
root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
root.addHandler(ch)
def parse_config():
cml_kwargs = dict([tuple(kv.split(':')) for kv in sys.argv[1:]])
kwargs = defaultdict(bool)
# Default settings
set_default(kwargs, 'name_str', 'gan')
set_default(kwargs, 'data_name', 'cifar10')
set_default(kwargs, 'batch_size', '64')
set_default(kwargs, 'z_dim', '100')
set_default(kwargs, 'gan_mode', 'js-gan')
set_default(kwargs, 'bre_w', '1.')
set_default(kwargs, 'bre_on_fake', '1')
set_default(kwargs, 'bre_on_interp', '1')
set_default(kwargs, 'bre_on_real', '0')
set_default(kwargs, 'bre_loc_mode', 'lfl1')
set_default(kwargs, 'gp_weight', '0.')
set_default(kwargs, 'gp_slope', '1.')
set_default(kwargs, 'model_func', 'dcgan')
set_default(kwargs, 'g_bn', 'bn')
set_default(kwargs, 'd_bn', 'bn')
set_default(kwargs, 'd_dp', '0')
set_default(kwargs, 'g_dp', '0')
set_default(kwargs, 'g_width_factor', '4')
set_default(kwargs, 'g_depth_factor', '4')
set_default(kwargs, 'd_width_factor', '4')
set_default(kwargs, 'd_depth_factor', '4')
set_default(kwargs, 'd_wdecay', '1e-4')
set_default(kwargs, 'g_wdecay', '1e-4')
set_default(kwargs, 'binarizer', 'softsign')
set_default(kwargs, 'g_lr', '.0002')
set_default(kwargs, 'd_lr', '.0002')
set_default(kwargs, 'min_g_lr', str(1e-6))
set_default(kwargs, 'min_d_lr', str(1e-6))
set_default(kwargs, 'max_iteration', '40000')
set_default(kwargs, 'd_beta1', '.5')
set_default(kwargs, 'g_beta1', '.5')
set_default(kwargs, 'beta2', '.999')
set_default(kwargs, 'n_d_steps', '1')
set_default(kwargs, 'n_g_steps', '1')
set_default(kwargs, 'eval_iter', '1000')
set_default(kwargs, 'save_iter', '1000')
set_default(kwargs, 'outdir', './results/')
set_default(kwargs, 'data_dir', './data/')
set_default(kwargs, 'monitor', '1')
for k in cml_kwargs:
if k not in kwargs:
raise ValueError('option {} not recognized'.format(k))
kwargs.update(cml_kwargs)
#kwargs = cml_kwargs
try:
label = subprocess.check_output(
["git", "describe", "--always"]).strip()
except:
label = None
kwargs['git_label'] = label
setting_hash_code = dict2hash(kwargs)
return kwargs, setting_hash_code
##############################################################
if __name__ == '__main__':
kwargs, setting_hash_code = parse_config()
fname = '{}_{}_{}'.format(kwargs['name_str'],
kwargs['data_name'],
setting_hash_code)
data_dir = os.path.expanduser(kwargs['data_dir'])
outdir = os.path.expanduser(kwargs['outdir'])
params_outdir = outdir
if not os.path.exists(outdir):
os.mkdir(outdir)
config_logging(filename=os.path.join(outdir, fname + '.log'))
logging.info('====================================')
for k in sorted(kwargs.keys()):
logging.info('%s %s' % (k, kwargs[k]))
logging.info('====================================')
with open(os.path.join(outdir, fname + '_settings.txt'), 'w') as wf:
wf.write(' '.join([k+':'+str(kwargs[k])
for k in sorted(kwargs.keys())]))
logging.info(fname)
##############################################################
# find out if reload
if FORCE_NO_RELOAD:
g_saved_path = d_saved_path = last_iter = None
else:
if 'reload_hash_code' in kwargs:
reload_hash_code = kwargs['reload_hash_code'].strip()
else:
reload_hash_code = setting_hash_code
logging.info('reloading from ' + reload_hash_code)
g_saved_path, d_saved_path, last_iter = find_last_saved(
reload_hash_code, params_outdir)
##############################################################
data_name = kwargs['data_name']
batch_size = int(kwargs['batch_size'])
z_dim = int(kwargs['z_dim'])
gan_mode = kwargs['gan_mode']
n_d_steps = int(kwargs['n_d_steps'])
n_g_steps = int(kwargs['n_g_steps'])
max_iteration = int(kwargs['max_iteration'])
all_data = locals()['gen_'+data_name](data_dir=data_dir)
img_size = all_data.shape[-1]
logging.info("total train data: %s", len(all_data))
##############################################################
gan_model = GanModel(kwargs['model_func'], img_size=img_size, z_dim=z_dim,
batch_size=batch_size, gan_mode=gan_mode,
d_bn=kwargs['d_bn'], g_bn=kwargs['g_bn'],
d_dp=kwargs['d_dp'], g_dp=kwargs['g_dp'],
g_wf=floatX(kwargs['g_width_factor']),
d_wf=floatX(kwargs['d_width_factor']),
g_df=int(kwargs['g_depth_factor']),
d_df=int(kwargs['d_depth_factor']),
bre_loc_mode=kwargs['bre_loc_mode'],
opt_kwargs=kwargs,
logging=logging)
all_g_layers = ll.get_all_layers(gan_model.g_layers.values())
all_d_layers = ll.get_all_layers(gan_model.d_layers.values())
glayer2name = defaultdict(str)
dlayer2name = defaultdict(str)
logging.info('~~~~~~~~~~~~~ G model ~~~~~~~~~~~~~~~~~~~~~~')
glayer2name.update({v: k for k, v in gan_model.g_layers.iteritems()})
logging.info(get_network_str(all_g_layers, get_network=False,
incomings=True, outgoings=True,
layer2name=glayer2name))
dlayer2name.update(({v: k for k, v in gan_model.d_layers.iteritems()}))
logging.info('G total trainable params: %g' %
(ll.count_params(gan_model.l_out_g, trainable=True)))
logging.info('~~~~~~~~~~~~~ D model ~~~~~~~~~~~~~~~~~~~~~~')
logging.info(get_network_str(all_d_layers, get_network=False,
incomings=True, outgoings=True,
layer2name=dlayer2name))
logging.info('D total trainable params: %g' %
(ll.count_params(gan_model.l_out_d, trainable=True)))
##############################################################
gan_model.build_funcs()
data_itr = batch(all_data, batch_size)
tic = None
hist = defaultdict(list)
plot_data = []
d_train_outs_dict = defaultdict(list)
g_train_outs_dict = defaultdict(list)
start_iteration = 0 # will start at -1, which shows G at initialization
for iteration in xrange(start_iteration-1, max_iteration):
lin_anneal(gan_model.g_sh_lr, floatX(kwargs['g_lr']),
max_iteration, min_var=floatX(kwargs['min_g_lr']))
lin_anneal(gan_model.d_sh_lr, floatX(kwargs['d_lr']),
max_iteration, min_var=floatX(kwargs['min_d_lr']))
if iteration >= 0:
for _ in xrange(n_d_steps):
try:
real_data_batch = next(data_itr)
except StopIteration:
np.random.shuffle(all_data)
all_data = np.ascontiguousarray(all_data)
data_itr = batch(all_data, batch_size)
real_data_batch = next(data_itr)
d_cost_values = gan_model.d_train_func(real_data_batch)
d_cost_v = d_cost_values[0]
for k, v in zip(gan_model.d_outs, d_cost_values):
d_train_outs_dict[gan_model.out_var2name[k]].append(v)
for _ in xrange(n_g_steps):
if len(gan_model.g_inputs):
g_cost_values = gan_model.g_train_func(real_data_batch)
else:
g_cost_values = gan_model.g_train_func()
g_cost_v = g_cost_values[0]
for k, v in zip(gan_model.g_outs, g_cost_values):
g_train_outs_dict[gan_model.out_var2name[k]].append(v)
else:
real_data_batch = next(data_itr)
d_cost_v = np.nan
g_cost_v = np.nan
##############################################################
# monitoring
if (iteration < 0 or
iteration % int(kwargs['eval_iter']) == 0 or
iteration == max_iteration-1):
logging.info(
'~~~~~~~~~~~~ Iteration %s ~~~~~~~~~~~~~~~~', iteration)
logging.info(fname)
logging.info('epoch %s', iteration * batch_size *
n_d_steps // len(all_data))
logging.info('g lr: %s', gan_model.g_sh_lr.get_value())
logging.info('d lr: %s', gan_model.d_sh_lr.get_value())
if int(kwargs.get('monitor', '0')) >= 1:
gm_outs = gan_model.monitor_func(real_data_batch)
assert len(gan_model.monitor_stats) == len(gm_outs)
for k, v in zip(gan_model.monitor_stats.keys(), gm_outs):
hist[k].append(v)
if tic:
elapsed_time = time.time() - tic
else:
elapsed_time = 0.
hist['elapsed_time'].append(elapsed_time)
hist['epoch'].append(iteration)
hist['g_cost'].append(g_cost_v)
hist['d_cost'].append(d_cost_v)
for k in sorted(hist.keys()):
if isinstance(hist[k][-1], np.ndarray) and hist[k][-1].size > 1:
logging.info('%s_avg %s', k, '%5.3f' %
(hist[k][-1]).mean())
else:
logging.info('%s %s', k, '%5.3f' % hist[k][-1])
logging.info('')
tic = time.time()
# ~~~~~~~~~~~~~~~~~~~~~~~ sampling and save images
g_samples = gan_model.g_sample(1024)
g_samples_cz_v = gan_model.g_sample_cz_func()
if int(kwargs.get('do_save', '1')):
_path = os.path.join(
outdir, '{}_iter_{}.png'.format(fname, iteration))
tile_and_save_samples(_path, g_samples)
_path = os.path.join(
outdir, '{}_cz_iter_{}.png'.format(fname, iteration))
tile_and_save_samples(_path, g_samples_cz_v)
##############################################################
# snapshot
if (iteration % int(kwargs['save_iter']) == 0
and int(kwargs.get('do_save', '1'))):
dump_params(gan_model.all_d_params,
os.path.join(params_outdir,
'{}_dparams_iter{}.pkl'.format(fname, iteration)))
dump_params(gan_model.all_g_params,
os.path.join(params_outdir,
'{}_gparams_iter{}.pkl'.format(fname, iteration)))
dump(hist, os.path.join(outdir, '{}_hist.pkl'.format(fname)),
compress=('gzip', 9))
dump({'g_outs': g_train_outs_dict,
'd_outs': d_train_outs_dict},
os.path.join(outdir, '{}_outs_dict.pkl'.format(fname)),
compress=('gzip', 9))
gc.collect()
if int(kwargs.get('do_save', '1')):
dump_params(gan_model.all_d_params,
os.path.join(params_outdir,
'{}_dparams.pkl'.format(fname)))
dump_params(gan_model.all_g_params,
os.path.join(params_outdir,
'{}_gparams.pkl'.format(fname)))
g_samples = (gan_model.g_sample(len(all_data)) * 255).astype(np.uint8)
sample_path = os.path.join(outdir,
'{}_iter_{}_N_{}.npz'.format(fname,
iteration,
len(all_data)))
np.savez_compressed(sample_path, g_samples)
logging.info(
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
logging.info('final G generated data:' + sample_path)
del all_data
if data_name == 'cifar10':
gc.collect()
inception_score_code_output = subprocess.check_output(
["python2", "utils/inc_score_wrapper.py",
"data_file:" + sample_path]).strip()
logging.info('Inception score:')
logging.info(inception_score_code_output)
logging.info(
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
gc.collect()
fid_score_code_output = subprocess.check_output(
["python2", "utils/fid_score_wrapper.py",
"data_file:"+sample_path]).strip()
logging.info('FID score:')
logging.info(fid_score_code_output)
logging.info(
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
logging.info(setting_hash_code)
logging.info('COMPLETED!!!')