training.py
20.3 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#!/u/parcollt/anaconda2/bin/python
# -*- coding: utf-8 -*-
# Authors: Parcollet Titouan,
# Imports
import editdistance
import h5py
import datasets.timit
from datasets.timit import Timit
from datasets.utils import construct_conv_stream, phone_to_phoneme_dict
import complexnn
from complexnn import *
import h5py as H
import keras
from keras.callbacks import Callback, ModelCheckpoint, LearningRateScheduler
from keras.datasets import cifar10, cifar100
from keras.initializers import Orthogonal
from keras.layers import Layer, Dropout, AveragePooling1D, AveragePooling2D, AveragePooling3D, add, Add, concatenate, Concatenate, Input, Flatten, Dense, Convolution2D, BatchNormalization, Activation, Reshape, ConvLSTM2D, Conv2D, Lambda
from keras.models import Model, load_model, save_model
from keras.optimizers import SGD, Adam, RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras.utils.np_utils import to_categorical
import keras.backend as K
import keras.models as KM
from keras.utils.training_utils import multi_gpu_model
import logging as L
import numpy as np
import os, pdb, socket, sys, time
import theano as T
from keras.backend.tensorflow_backend import set_session
from models_cifar import getCifarResnetModel2D
from models_timit import getTimitResnetModel2D,ctc_lambda_func
from models_decoda import *
import tensorflow as tf
import itertools
import random
#
# Generator wrapper for timit
#
def timitGenerator(stream):
while True:
#dataset = Timit(stream)
#seed = random.randint(0,100)
#rng=np.random.RandomState(seed)
#data_stream_dev = construct_conv_stream(dataset, rng, 200, 10000, quaternion=False)
for data in stream.get_epoch_iterator():
yield data
#
# Custom metrics
#
class EditDistance(Callback):
def __init__(self, func, dataset, quaternion, save_prefix):
self.func = func
if(dataset in ['train','test','dev']):
self.dataset_type = dataset
self.save_prefix = save_prefix
self.dataset = Timit(str(dataset))
self.full_phonemes_dict = self.dataset.get_phoneme_dict()
self.ind_phonemes_dict = self.dataset.get_phoneme_ind_dict()
self.rng = np.random.RandomState(123)
self.data_stream = construct_conv_stream(self.dataset, self.rng, 200, 10000,quaternion)
else:
raise ValueError("Unknown dataset for edit distance "+dataset)
def labels_to_text(self,labels):
ret = []
for c in labels:
if c == len(self.full_phonemes_dict) - 2:
ret.append("")
else:
c_ = self.full_phonemes_dict[c + 1]
ret.append(phone_to_phoneme_dict.get(c_, c_))
ret = [k for k, g in itertools.groupby(ret)]
return list(filter(lambda c: c != "", ret))
def decode_batch(self, out, mask):
ret = []
for j in range(out.shape[0]):
out_best = list(np.argmax(out[j], 1))[:int(mask[j])]
out_best = [k for k, g in itertools.groupby(out_best)]
# map from 61-d to 39-d
outstr = self.labels_to_text(out_best)
ret.append(outstr)
return ret
def on_epoch_end(self, epoch, logs={}):
mean_norm_ed = 0.
num = 0
for data in self.data_stream.get_epoch_iterator():
x, y = data
y_pred = self.func([x[0]])[0]
decoded_y_pred = self.decode_batch(y_pred, x[1])
decoded_gt = []
for i in range(x[2].shape[0]):
decoded_gt.append(self.labels_to_text(x[2][i][:int(x[3][i])]))
num += len(decoded_y_pred)
for i, (_pred, _gt) in enumerate(zip(decoded_y_pred, decoded_gt)):
#print _pred
#print _gt
#print "######"
edit_dist = editdistance.eval(_pred, _gt)
mean_norm_ed += float(edit_dist) / x[3][i]
mean_norm_ed = mean_norm_ed / num
# Dump To File Logs at every epoch for clusters sbatch
f=open(str(self.save_prefix)+"_"+str(self.dataset_type)+"_PER.txt",'ab')
np.savetxt(f,mean_norm_ed)
f.close()
L.getLogger("train").info("PER on "+str(self.dataset_type)+" : "+str(mean_norm_ed)+" at epoch "+str(epoch))
#
# Callbacks:
#
class TrainLoss(Callback):
def __init__(self, savedir):
self.savedir = savedir
def on_epoch_end(self, epoch, logs={}):
f=open(str(self.savedir)+"_train_loss.txt",'ab')
f2=open(str(self.savedir)+"_dev_loss.txt",'ab')
value = float(logs['loss'])
np.savetxt(f,np.array([value]))
f.close()
value = float(logs['val_loss'])
np.savetxt(f2,np.array([value]))
f2.close()
#
# Print a newline after each epoch, because Keras doesn't. Grumble.
#
class PrintNewlineAfterEpochCallback(Callback):
def on_epoch_end(self, epoch, logs={}):
sys.stdout.write("\n")
#
# Save checkpoints.
#
class SaveLastModel(Callback):
def __init__(self, workdir, save_prefix, model_mono,period=10):
self.workdir = workdir
self.model_mono = model_mono
self.chkptsdir = os.path.join(self.workdir, "chkpts")
self.save_prefix = save_prefix
if not os.path.isdir(self.chkptsdir):
os.mkdir(self.chkptsdir)
self.period_of_epochs = period
self.linkFilename = os.path.join(self.chkptsdir, str(save_prefix)+"ModelChkpt.hdf5")
self.linkFilename_weight = os.path.join(self.chkptsdir, str(save_prefix)+"ModelChkpt_weight.hdf5")
def on_epoch_end(self, epoch, logs={}):
if (epoch + 1) % self.period_of_epochs == 0:
# Filenames
baseHDF5Filename = str(self.save_prefix)+"ModelChkpt{:06d}.hdf5".format(epoch+1)
baseHDF5Filename_weight = str(self.save_prefix)+"ModelChkpt{:06d}_weight.hdf5".format(epoch+1)
baseYAMLFilename = str(self.save_prefix)+"ModelChkpt{:06d}.yaml".format(epoch+1)
hdf5Filename = os.path.join(self.chkptsdir, baseHDF5Filename)
hdf5Filename_weight = os.path.join(self.chkptsdir, baseHDF5Filename_weight)
yamlFilename = os.path.join(self.chkptsdir, baseYAMLFilename)
# YAML
yamlModel = self.model_mono.to_yaml()
with open(yamlFilename, "w") as yamlFile:
yamlFile.write(yamlModel)
# HDF5
KM.save_model(self.model_mono, hdf5Filename)
self.model_mono.save_weights(hdf5Filename_weight)
with H.File(hdf5Filename, "r+") as f:
f.require_dataset("initialEpoch", (), "uint64", True)[...] = int(epoch+1)
f.flush()
with H.File(hdf5Filename_weight, "r+") as f:
f.require_dataset("initialEpoch", (), "uint64", True)[...] = int(epoch+1)
f.flush()
# Symlink to new HDF5 file, then atomically rename and replace.
os.symlink(baseHDF5Filename_weight, self.linkFilename_weight+".rename")
os.rename (self.linkFilename_weight+".rename",
self.linkFilename_weight)
# Symlink to new HDF5 file, then atomically rename and replace.
os.symlink(baseHDF5Filename, self.linkFilename+".rename")
os.rename (self.linkFilename+".rename",
self.linkFilename)
# Print
L.getLogger("train").info("Saved checkpoint to {:s} at epoch {:5d}".format(hdf5Filename, epoch+1))
def q_normalize(x,size):
for line in range(0,len(x)):
for data in range(0,size/4):
norm = np.sqrt(pow(x[line][data][0],2)+ pow(x[line][data][1],2)+ \
pow(x[line][data][2],2)+ pow(x[line][data][3],2))
x[line][data][0] /= norm
x[line][data][1] /= norm
x[line][data][2] /= norm
x[line][data][3] /= norm
return x
#
# Summarize environment variable.
#
def summarizeEnvvar(var):
if var in os.environ: return var+"="+os.environ.get(var)
else: return var+" unset"
#
# TRAINING PROCESS
#
def train(d):
#
#
# Log important data about how we were invoked.
#
L.getLogger("entry").info("INVOCATION: "+" ".join(sys.argv))
L.getLogger("entry").info("HOSTNAME: "+socket.gethostname())
L.getLogger("entry").info("PWD: "+os.getcwd())
L.getLogger("entry").info("CUDA DEVICE: "+str(d.device))
os.environ["CUDA_VISIBLE_DEVICES"]=str(d.device)
#
# Setup GPUs
#
config = tf.ConfigProto()
# Don't pre-allocate memory; allocate as-needed
config.gpu_options.allow_growth = True
# Only allow a total of half the GPU memory to be allocated
config.gpu_options.per_process_gpu_memory_fraction = d.memory
# Create a session with the above options specified.
K.tensorflow_backend.set_session(tf.Session(config=config))
summary = "\n"
summary += "Environment:\n"
summary += summarizeEnvvar("THEANO_FLAGS")+"\n"
summary += "\n"
summary += "Software Versions:\n"
summary += "Theano: "+T.__version__+"\n"
summary += "Keras: "+keras.__version__+"\n"
summary += "\n"
summary += "Arguments:\n"
summary += "Path to Datasets: "+str(d.datadir)+"\n"
summary += "Number of GPUs: "+str(d.datadir)+"\n"
summary += "Path to Workspace: "+str(d.workdir)+"\n"
summary += "Model: "+str(d.model)+"\n"
summary += "Dataset: "+str(d.dataset)+"\n"
summary += "Number of Epochs: "+str(d.num_epochs)+"\n"
summary += "Batch Size: "+str(d.batch_size)+"\n"
summary += "Number of Start Filters: "+str(d.start_filter)+"\n"
summary += "Number of Blocks/Stage: "+str(d.num_blocks)+"\n"
summary += "Optimizer: "+str(d.optimizer)+"\n"
summary += "Learning Rate: "+str(d.lr)+"\n"
summary += "Learning Rate Decay: "+str(d.decay)+"\n"
summary += "Learning Rate Schedule: "+str(d.schedule)+"\n"
summary += "Clipping Norm: "+str(d.clipnorm)+"\n"
summary += "Clipping Value: "+str(d.clipval)+"\n"
summary += "Dropout Probability: "+str(d.dropout)+"\n"
if d.optimizer in ["adam"]:
summary += "Beta 1: "+str(d.beta1)+"\n"
summary += "Beta 2: "+str(d.beta2)+"\n"
else:
summary += "Momentum: "+str(d.momentum)+"\n"
summary += "Save Prefix: "+str(d.save_prefix)+"\n"
if d.model == "quaternion":
summary += "Quat. Segmentation: "+str(d.seg)+"\n"
L.getLogger("entry").info(summary[:-1])
#
# Load dataset
#
L.getLogger("entry").info("Loading dataset {:s} ...".format(d.dataset))
np.random.seed(d.seed % 2**32)
if d.dataset == "timit":
#
# Create training data generator
#
dataset = Timit('train')
rng=np.random.RandomState(123)
if d.model =="quaternion":
data_stream_train = construct_conv_stream(dataset, rng, 200, 10000, quaternion=True)
else:
data_stream_train = construct_conv_stream(dataset, rng, 200, 10000, quaternion=False)
#
# Create dev data generator
#
dataset = Timit('dev')
rng=np.random.RandomState(123)
if d.model =="quaternion":
data_stream_dev = construct_conv_stream(dataset, rng, 200, 10000, quaternion=True)
else:
data_stream_dev = construct_conv_stream(dataset, rng, 200, 10000, quaternion=False)
L.getLogger("entry").info("Training set length: "+str(Timit('train').num_examples))
L.getLogger("entry").info("Validation set length: "+str(Timit('dev').num_examples))
L.getLogger("entry").info("Test set length: "+str(Timit('test').num_examples))
L.getLogger("entry").info("Loaded dataset {:s}.".format(d.dataset))
# Optimizer
if d.optimizer in ["sgd", "nag"]:
opt = SGD (lr = d.lr,
momentum = d.momentum,
decay = d.decay,
nesterov = (d.optimizer=="nag"),
clipnorm = d.clipnorm)
elif d.optimizer == "rmsprop":
opt = RMSProp(lr = d.lr,
decay = d.decay,
clipnorm = d.clipnorm)
elif d.optimizer == "adam":
opt = Adam (lr = d.lr,
beta_1 = d.beta1,
beta_2 = d.beta2,
decay = d.decay,
clipnorm = d.clipnorm)
else:
raise ValueError("Unknown optimizer "+d.optimizer)
#
# Initial Entry or Resume?
#
initialEpoch = 0
chkptFilename = os.path.join(d.workdir, "chkpts", str(d.save_prefix)+"ModelChkpt.hdf5")
chkptFilename_weight = os.path.join(d.workdir, "chkpts", str(d.save_prefix)+"ModelChkpt_weight.hdf5")
isResuming = os.path.isfile(chkptFilename)
isResuming_weight = os.path.isfile(chkptFilename_weight)
#### HAVE TO BE EXTEND TO WORK WITH QUATERNION SAVES
if isResuming or isResuming_weight:
# Reload Model and Optimizer
if d.dataset == "timit":
L.getLogger("entry").info("Re-Creating the model from scratch.")
model_mono,test_func = getTimitResnetModel2D(d)
model_mono.load_weights(chkptFilename_weight)
with H.File(chkptFilename_weight, "r") as f:
initialEpoch = int(f["initialEpoch"][...])
L.getLogger("entry").info("Training will restart at epoch {:5d}.".format(initialEpoch+1))
L.getLogger("entry").info("Compilation Started.")
else:
L.getLogger("entry").info("Reloading a model from "+chkptFilename+" ...")
np.random.seed(d.seed % 2**32)
model = KM.load_model(chkptFilename, custom_objects={
"ComplexConv2D": ComplexConv2D,
"QuaternionConv2D": QuaternionConv2D,
"QuaternionConv1D": QuaternionConv1D,
"ComplexBatchNormalization": ComplexBN,
"QuaternionBatchNormalization": QuaternionBN,
"GetReal": GetReal,
"GetImag": GetImag,
"GetIFirst": GetIFirst,
"GetJFirst": GetJFirst,
"GetKFirst": GetKFirst,
"GetRFirst": GetRFirst,
"ComplexConv2D": ComplexConv2D,
"ComplexBatchNormalization": ComplexBN,
})
L.getLogger("entry").info("... reloading complete.")
with H.File(chkptFilename, "r") as f:
initialEpoch = int(f["initialEpoch"][...])
L.getLogger("entry").info("Training will restart at epoch {:5d}.".format(initialEpoch+1))
L.getLogger("entry").info("Compilation Started.")
else:
# Model
L.getLogger("entry").info("Creating new model from scratch.")
np.random.seed(d.seed % 2**32)
if d.dataset == "decoda":
model_mono = getModel1D(d)
#model = getResnetModel1D(d)
elif d.dataset == "timit":
model_mono,test_func = getTimitResnetModel2D(d)
else:
model_mono = getCifarResnetModel2D(d)
L.getLogger("entry").info("Compilation Started.")
#
# Multi GPU: Can only save the model_mono because of keras bug
#
if d.gpus >1:
model = multi_gpu_model(model_mono, gpus=d.gpus)
else:
model = model_mono
if d.dataset == "timit":
model.compile(opt, loss={'ctc': lambda y_true, y_pred: y_pred}) #,metrics=[ctc_accuracy])
else:
model.compile(opt, 'categorical_crossentropy', metrics=['accuracy'])
print model.summary()
#
# Precompile several backend functions
#
if d.summary:
model.summary()
L.getLogger("entry").info("# of Parameters: {:10d}".format(model.count_params()))
L.getLogger("entry").info("Compiling Train Function...")
t =- time.time()
model._make_train_function()
t += time.time()
L.getLogger("entry").info(" {:10.3f}s".format(t))
L.getLogger("entry").info("Compiling Predict Function...")
t =- time.time()
model._make_predict_function()
t += time.time()
L.getLogger("entry").info(" {:10.3f}s".format(t))
L.getLogger("entry").info("Compiling Test Function...")
t =- time.time()
model._make_test_function()
t += time.time()
L.getLogger("entry").info(" {:10.3f}s".format(t))
L.getLogger("entry").info("Compilation Ended.")
#
# Create Callbacks
#
newLineCb = PrintNewlineAfterEpochCallback()
saveLastCb = SaveLastModel(d.workdir, d.save_prefix, model_mono,period=3)
#saveBestCb = SaveBestModel(d.save_prefix, d.workdir, d.output_type, model_mono)
#trainValHistCb = TrainValHistory(d.output_type)
callbacks = []
callbacks += [newLineCb]
if d.dataset == "timit":
if d.model=="quaternion":
quaternion = True
else:
quaternion = False
savedir = d.workdir+"/LOGS/"+d.save_prefix
trainLoss = TrainLoss(savedir)
editDistValCb = EditDistance(test_func,'dev',quaternion, savedir)
editDistTestCb = EditDistance(test_func,'test',quaternion, savedir)
callbacks += [trainLoss]
callbacks += [editDistValCb]
callbacks += [editDistTestCb]
else:
testErrCb = TestErrorCallback((X_test, Y_test), d.output_type)
callbacks += [testErrCb]
callbacks += [trainValHistCb]
callbacks += [saveBestCb]
callbacks += [newLineCb]
callbacks += [saveLastCb]
#
# Enter training loop.
#
L .getLogger("entry").info("**********************************************")
if isResuming: L.getLogger("entry").info("*** Reentering Training Loop @ Epoch {:5d} ***".format(initialEpoch+1))
else: L.getLogger("entry").info("*** Entering Training Loop @ First Epoch ***")
L .getLogger("entry").info("**********************************************")
if d.dataset == "timit":
model.fit_generator(generator = timitGenerator(data_stream_train),
steps_per_epoch = 188,
epochs = d.num_epochs,
verbose = 1,
validation_data = timitGenerator(data_stream_dev),
validation_steps = 20,
callbacks = callbacks,
initial_epoch = initialEpoch)
else:
#
# Create training data generator
#
datagen = ImageDataGenerator(height_shift_range = 0.125,
width_shift_range = 0.125,
horizontal_flip = True)
model.fit_generator(generator = datagen.flow(X_train, Y_train, batch_size=d.batch_size),
steps_per_epoch = (len(X_train)+d.batch_size-1) // d.batch_size,
epochs = d.num_epochs,
verbose = 1,
callbacks = callbacks,
validation_data = (X_val, Y_val),
initial_epoch = initialEpoch)
#
# Dump histories.
#
np.savetxt(os.path.join(d.workdir, 'test_loss.txt'), np.asarray(testErrCb.loss_history))
np.savetxt(os.path.join(d.workdir, 'test_acc.txt'), np.asarray(testErrCb.acc_history))
np.savetxt(os.path.join(d.workdir, 'train_loss.txt'), np.asarray(trainValHistCb.train_loss))
np.savetxt(os.path.join(d.workdir, 'train_acc.txt'), np.asarray(trainValHistCb.train_acc))
np.savetxt(os.path.join(d.workdir, 'val_loss.txt'), np.asarray(trainValHistCb.val_loss))
np.savetxt(os.path.join(d.workdir, 'val_acc.txt'), np.asarray(trainValHistCb.val_acc))
# CIFAR-10:
# - Baseline
# - Baseline but with complex parametrization
# - Baseline but with spectral pooling