-
Notifications
You must be signed in to change notification settings - Fork 75
/
train.py
360 lines (322 loc) · 10.4 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
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
# CometML needs to be imported first.
try:
import comet_ml
except ImportError:
pass
from model import SampleRNN, Predictor
from optim import gradient_clipping
from nn import sequence_nll_loss_bits
from trainer import Trainer
from trainer.plugins import (
TrainingLossMonitor, ValidationPlugin, AbsoluteTimeMonitor, SaverPlugin,
GeneratorPlugin, StatsPlugin
)
from dataset import FolderDataset, DataLoader
import torch
from torch.utils.trainer.plugins import Logger
from natsort import natsorted
from functools import reduce
import os
import shutil
import sys
from glob import glob
import re
import argparse
default_params = {
# model parameters
'n_rnn': 1,
'dim': 1024,
'learn_h0': True,
'q_levels': 256,
'seq_len': 1024,
'weight_norm': True,
'batch_size': 128,
'val_frac': 0.1,
'test_frac': 0.1,
# training parameters
'keep_old_checkpoints': False,
'datasets_path': 'datasets',
'results_path': 'results',
'epoch_limit': 1000,
'resume': True,
'sample_rate': 16000,
'n_samples': 1,
'sample_length': 80000,
'loss_smoothing': 0.99,
'cuda': True,
'comet_key': None
}
tag_params = [
'exp', 'frame_sizes', 'n_rnn', 'dim', 'learn_h0', 'q_levels', 'seq_len',
'batch_size', 'dataset', 'val_frac', 'test_frac'
]
def param_to_string(value):
if isinstance(value, bool):
return 'T' if value else 'F'
elif isinstance(value, list):
return ','.join(map(param_to_string, value))
else:
return str(value)
def make_tag(params):
return '-'.join(
key + ':' + param_to_string(params[key])
for key in tag_params
if key not in default_params or params[key] != default_params[key]
)
def setup_results_dir(params):
def ensure_dir_exists(path):
if not os.path.exists(path):
os.makedirs(path)
tag = make_tag(params)
results_path = os.path.abspath(params['results_path'])
ensure_dir_exists(results_path)
results_path = os.path.join(results_path, tag)
if not os.path.exists(results_path):
os.makedirs(results_path)
elif not params['resume']:
shutil.rmtree(results_path)
os.makedirs(results_path)
for subdir in ['checkpoints', 'samples']:
ensure_dir_exists(os.path.join(results_path, subdir))
return results_path
def load_last_checkpoint(checkpoints_path):
checkpoints_pattern = os.path.join(
checkpoints_path, SaverPlugin.last_pattern.format('*', '*')
)
checkpoint_paths = natsorted(glob(checkpoints_pattern))
if len(checkpoint_paths) > 0:
checkpoint_path = checkpoint_paths[-1]
checkpoint_name = os.path.basename(checkpoint_path)
match = re.match(
SaverPlugin.last_pattern.format(r'(\d+)', r'(\d+)'),
checkpoint_name
)
epoch = int(match.group(1))
iteration = int(match.group(2))
return (torch.load(checkpoint_path), epoch, iteration)
else:
return None
def tee_stdout(log_path):
log_file = open(log_path, 'a', 1)
stdout = sys.stdout
class Tee:
def write(self, string):
log_file.write(string)
stdout.write(string)
def flush(self):
log_file.flush()
stdout.flush()
sys.stdout = Tee()
def make_data_loader(overlap_len, params):
path = os.path.join(params['datasets_path'], params['dataset'])
def data_loader(split_from, split_to, eval):
dataset = FolderDataset(
path, overlap_len, params['q_levels'], split_from, split_to
)
return DataLoader(
dataset,
batch_size=params['batch_size'],
seq_len=params['seq_len'],
overlap_len=overlap_len,
shuffle=(not eval),
drop_last=(not eval)
)
return data_loader
def init_comet(params, trainer):
if params['comet_key'] is not None:
from comet_ml import Experiment
from trainer.plugins import CometPlugin
experiment = Experiment(api_key=params['comet_key'], log_code=False)
hyperparams = {
name: param_to_string(params[name]) for name in tag_params
}
experiment.log_multiple_params(hyperparams)
trainer.register_plugin(CometPlugin(
experiment, [
('training_loss', 'epoch_mean'),
'validation_loss',
'test_loss'
]
))
def main(exp, frame_sizes, dataset, **params):
params = dict(
default_params,
exp=exp, frame_sizes=frame_sizes, dataset=dataset,
**params
)
results_path = setup_results_dir(params)
tee_stdout(os.path.join(results_path, 'log'))
model = SampleRNN(
frame_sizes=params['frame_sizes'],
n_rnn=params['n_rnn'],
dim=params['dim'],
learn_h0=params['learn_h0'],
q_levels=params['q_levels'],
weight_norm=params['weight_norm']
)
predictor = Predictor(model)
if params['cuda']:
model = model.cuda()
predictor = predictor.cuda()
optimizer = gradient_clipping(torch.optim.Adam(predictor.parameters()))
data_loader = make_data_loader(model.lookback, params)
test_split = 1 - params['test_frac']
val_split = test_split - params['val_frac']
trainer = Trainer(
predictor, sequence_nll_loss_bits, optimizer,
data_loader(0, val_split, eval=False),
cuda=params['cuda']
)
checkpoints_path = os.path.join(results_path, 'checkpoints')
checkpoint_data = load_last_checkpoint(checkpoints_path)
if checkpoint_data is not None:
(state_dict, epoch, iteration) = checkpoint_data
trainer.epochs = epoch
trainer.iterations = iteration
predictor.load_state_dict(state_dict)
trainer.register_plugin(TrainingLossMonitor(
smoothing=params['loss_smoothing']
))
trainer.register_plugin(ValidationPlugin(
data_loader(val_split, test_split, eval=True),
data_loader(test_split, 1, eval=True)
))
trainer.register_plugin(AbsoluteTimeMonitor())
trainer.register_plugin(SaverPlugin(
checkpoints_path, params['keep_old_checkpoints']
))
trainer.register_plugin(GeneratorPlugin(
os.path.join(results_path, 'samples'), params['n_samples'],
params['sample_length'], params['sample_rate']
))
trainer.register_plugin(
Logger([
'training_loss',
'validation_loss',
'test_loss',
'time'
])
)
trainer.register_plugin(StatsPlugin(
results_path,
iteration_fields=[
'training_loss',
('training_loss', 'running_avg'),
'time'
],
epoch_fields=[
'validation_loss',
'test_loss',
'time'
],
plots={
'loss': {
'x': 'iteration',
'ys': [
'training_loss',
('training_loss', 'running_avg'),
'validation_loss',
'test_loss',
],
'log_y': True
}
}
))
init_comet(params, trainer)
trainer.run(params['epoch_limit'])
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
argument_default=argparse.SUPPRESS
)
def parse_bool(arg):
arg = arg.lower()
if 'true'.startswith(arg):
return True
elif 'false'.startswith(arg):
return False
else:
raise ValueError()
parser.add_argument('--exp', required=True, help='experiment name')
parser.add_argument(
'--frame_sizes', nargs='+', type=int, required=True,
help='frame sizes in terms of the number of lower tier frames, \
starting from the lowest RNN tier'
)
parser.add_argument(
'--dataset', required=True,
help='dataset name - name of a directory in the datasets path \
(settable by --datasets_path)'
)
parser.add_argument(
'--n_rnn', type=int, help='number of RNN layers in each tier'
)
parser.add_argument(
'--dim', type=int, help='number of neurons in every RNN and MLP layer'
)
parser.add_argument(
'--learn_h0', type=parse_bool,
help='whether to learn the initial states of RNNs'
)
parser.add_argument(
'--q_levels', type=int,
help='number of bins in quantization of audio samples'
)
parser.add_argument(
'--seq_len', type=int,
help='how many samples to include in each truncated BPTT pass'
)
parser.add_argument(
'--weight_norm', type=parse_bool,
help='whether to use weight normalization'
)
parser.add_argument('--batch_size', type=int, help='batch size')
parser.add_argument(
'--val_frac', type=float,
help='fraction of data to go into the validation set'
)
parser.add_argument(
'--test_frac', type=float,
help='fraction of data to go into the test set'
)
parser.add_argument(
'--keep_old_checkpoints', type=parse_bool,
help='whether to keep checkpoints from past epochs'
)
parser.add_argument(
'--datasets_path', help='path to the directory containing datasets'
)
parser.add_argument(
'--results_path', help='path to the directory to save the results to'
)
parser.add_argument('--epoch_limit', help='how many epochs to run')
parser.add_argument(
'--resume', type=parse_bool, default=True,
help='whether to resume training from the last checkpoint'
)
parser.add_argument(
'--sample_rate', type=int,
help='sample rate of the training data and generated sound'
)
parser.add_argument(
'--n_samples', type=int,
help='number of samples to generate in each epoch'
)
parser.add_argument(
'--sample_length', type=int,
help='length of each generated sample (in samples)'
)
parser.add_argument(
'--loss_smoothing', type=float,
help='smoothing parameter of the exponential moving average over \
training loss, used in the log and in the loss plot'
)
parser.add_argument(
'--cuda', type=parse_bool,
help='whether to use CUDA'
)
parser.add_argument(
'--comet_key', help='comet.ml API key'
)
parser.set_defaults(**default_params)
main(**vars(parser.parse_args()))