train.py 13.4 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4 5
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import sys
6
import os
Y
Yibing Liu 已提交
7 8 9 10
import numpy as np
import argparse
import time

L
Luo Tao 已提交
11
import paddle.fluid as fluid
12 13 14
import data_utils.augmentor.trans_mean_variance_norm as trans_mean_variance_norm
import data_utils.augmentor.trans_add_delta as trans_add_delta
import data_utils.augmentor.trans_splice as trans_splice
Z
zhxfl 已提交
15
import data_utils.augmentor.trans_delay as trans_delay
16
import data_utils.async_data_reader as reader
17
from model_utils.model import stacked_lstmp_model
Y
Yibing Liu 已提交
18 19 20


def parse_args():
21
    parser = argparse.ArgumentParser("Training for stacked LSTMP model.")
Y
Yibing Liu 已提交
22 23 24 25
    parser.add_argument(
        '--batch_size',
        type=int,
        default=32,
Y
Yibing Liu 已提交
26 27
        help='The sequence number of a batch data. Batch size per GPU. (default: %(default)d)'
    )
28 29 30 31 32 33
    parser.add_argument(
        '--minimum_batch_size',
        type=int,
        default=1,
        help='The minimum sequence number of a batch data. '
        '(default: %(default)d)')
34 35 36
    parser.add_argument(
        '--frame_dim',
        type=int,
Z
zhxfl 已提交
37
        default=80,
38
        help='Frame dimension of feature data. (default: %(default)d)')
Y
Yibing Liu 已提交
39 40 41 42
    parser.add_argument(
        '--stacked_num',
        type=int,
        default=5,
43
        help='Number of lstmp layers to stack. (default: %(default)d)')
Y
Yibing Liu 已提交
44 45 46 47
    parser.add_argument(
        '--proj_dim',
        type=int,
        default=512,
48
        help='Project size of lstmp unit. (default: %(default)d)')
Y
Yibing Liu 已提交
49 50 51 52
    parser.add_argument(
        '--hidden_dim',
        type=int,
        default=1024,
53
        help='Hidden size of lstmp unit. (default: %(default)d)')
54 55 56
    parser.add_argument(
        '--class_num',
        type=int,
Z
zhxfl 已提交
57
        default=3040,
58
        help='Number of classes in label. (default: %(default)d)')
Y
Yibing Liu 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
    parser.add_argument(
        '--pass_num',
        type=int,
        default=100,
        help='Epoch number to train. (default: %(default)d)')
    parser.add_argument(
        '--print_per_batches',
        type=int,
        default=100,
        help='Interval to print training accuracy. (default: %(default)d)')
    parser.add_argument(
        '--learning_rate',
        type=float,
72
        default=0.00016,
Y
Yibing Liu 已提交
73 74 75 76 77 78 79
        help='Learning rate used to train. (default: %(default)f)')
    parser.add_argument(
        '--device',
        type=str,
        default='GPU',
        choices=['CPU', 'GPU'],
        help='The device type. (default: %(default)s)')
80 81
    parser.add_argument(
        '--parallel', action='store_true', help='If set, run in parallel.')
Y
Yibing Liu 已提交
82 83 84 85
    parser.add_argument(
        '--mean_var',
        type=str,
        default='data/global_mean_var_search26kHr',
Y
Yibing Liu 已提交
86 87
        help="The path for feature's global mean and variance. "
        "(default: %(default)s)")
Y
Yibing Liu 已提交
88
    parser.add_argument(
89
        '--train_feature_lst',
Y
Yibing Liu 已提交
90 91
        type=str,
        default='data/feature.lst',
Y
Yibing Liu 已提交
92
        help='The feature list path for training. (default: %(default)s)')
Y
Yibing Liu 已提交
93
    parser.add_argument(
94
        '--train_label_lst',
Y
Yibing Liu 已提交
95 96
        type=str,
        default='data/label.lst',
Y
Yibing Liu 已提交
97
        help='The label list path for training. (default: %(default)s)')
98 99 100 101
    parser.add_argument(
        '--val_feature_lst',
        type=str,
        default='data/val_feature.lst',
Y
Yibing Liu 已提交
102
        help='The feature list path for validation. (default: %(default)s)')
103 104 105 106
    parser.add_argument(
        '--val_label_lst',
        type=str,
        default='data/val_label.lst',
Y
Yibing Liu 已提交
107
        help='The label list path for validation. (default: %(default)s)')
Y
Yibing Liu 已提交
108
    parser.add_argument(
109 110 111
        '--init_model_path',
        type=str,
        default=None,
112 113
        help="The model (checkpoint) path which the training resumes from. "
        "If None, train the model from scratch. (default: %(default)s)")
114 115
    parser.add_argument(
        '--checkpoints',
Y
Yibing Liu 已提交
116 117
        type=str,
        default='./checkpoints',
118 119 120 121 122 123 124 125
        help="The directory for saving checkpoints. Do not save checkpoints "
        "if set to ''. (default: %(default)s)")
    parser.add_argument(
        '--infer_models',
        type=str,
        default='./infer_models',
        help="The directory for saving inference models. Do not save inference "
        "models if set to ''. (default: %(default)s)")
Y
Yibing Liu 已提交
126 127 128 129
    args = parser.parse_args()
    return args


130 131 132 133 134 135 136
def print_arguments(args):
    print('-----------  Configuration Arguments -----------')
    for arg, value in sorted(vars(args).iteritems()):
        print('%s: %s' % (arg, value))
    print('------------------------------------------------')


Y
Yibing Liu 已提交
137
def train(args):
Y
Yibing Liu 已提交
138 139
    """train in loop.
    """
Y
Yibing Liu 已提交
140

141 142 143 144 145 146 147 148 149
    # paths check
    if args.init_model_path is not None and \
            not os.path.exists(args.init_model_path):
        raise IOError("Invalid initial model path!")
    if args.checkpoints != '' and not os.path.exists(args.checkpoints):
        os.mkdir(args.checkpoints)
    if args.infer_models != '' and not os.path.exists(args.infer_models):
        os.mkdir(args.infer_models)

Y
Yibing Liu 已提交
150 151
    train_program = fluid.Program()
    train_startup = fluid.Program()
152

Y
Yibing Liu 已提交
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
    with fluid.program_guard(train_program, train_startup):
        with fluid.unique_name.guard():
            py_train_reader = fluid.layers.py_reader(
                capacity=10,
                shapes=([-1, 3, 11, args.frame_dim], [-1, 1]),
                dtypes=['float32', 'int64'],
                lod_levels=[1, 1],
                name='train_reader')
            feature, label = fluid.layers.read_file(py_train_reader)
            prediction, avg_cost, accuracy = stacked_lstmp_model(
                feature=feature,
                label=label,
                hidden_dim=args.hidden_dim,
                proj_dim=args.proj_dim,
                stacked_num=args.stacked_num,
                class_num=args.class_num)
            # optimizer = fluid.optimizer.Momentum(learning_rate=args.learning_rate, momentum=0.9)
            optimizer = fluid.optimizer.Adam(
                learning_rate=fluid.layers.exponential_decay(
                    learning_rate=args.learning_rate,
                    decay_steps=1879,
                    decay_rate=1 / 1.2,
                    staircase=True))
            optimizer.minimize(avg_cost)

    test_program = fluid.Program()
    test_startup = fluid.Program()
    with fluid.program_guard(test_program, test_startup):
        with fluid.unique_name.guard():
            py_test_reader = fluid.layers.py_reader(
                capacity=10,
                shapes=([-1, 3, 11, args.frame_dim], [-1, 1]),
                dtypes=['float32', 'int64'],
                lod_levels=[1, 1],
                name='test_reader')
            feature, label = fluid.layers.read_file(py_test_reader)
            prediction, avg_cost, accuracy = stacked_lstmp_model(
                feature=feature,
                label=label,
                hidden_dim=args.hidden_dim,
                proj_dim=args.proj_dim,
                stacked_num=args.stacked_num,
                class_num=args.class_num)
    test_program = test_program.clone(for_test=True)
Y
Yibing Liu 已提交
197 198
    place = fluid.CPUPlace() if args.device == 'CPU' else fluid.CUDAPlace(0)
    exe = fluid.Executor(place)
Y
Yibing Liu 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    exe.run(train_startup)
    exe.run(test_startup)

    if args.parallel:
        exec_strategy = fluid.ExecutionStrategy()
        exec_strategy.num_iteration_per_drop_scope = 10
        train_exe = fluid.ParallelExecutor(
            use_cuda=(args.device == 'GPU'),
            loss_name=avg_cost.name,
            exec_strategy=exec_strategy,
            main_program=train_program)
        test_exe = fluid.ParallelExecutor(
            use_cuda=(args.device == 'GPU'),
            main_program=test_program,
            exec_strategy=exec_strategy,
            share_vars_from=train_exe)
Y
Yibing Liu 已提交
215

216 217 218 219
    # resume training if initial model provided.
    if args.init_model_path is not None:
        fluid.io.load_persistables(exe, args.init_model_path)

Y
Yibing Liu 已提交
220 221 222
    ltrans = [
        trans_add_delta.TransAddDelta(2, 2),
        trans_mean_variance_norm.TransMeanVarianceNorm(args.mean_var),
Z
zhxfl 已提交
223
        trans_splice.TransSplice(5, 5), trans_delay.TransDelay(5)
Y
Yibing Liu 已提交
224 225
    ]

Y
Yibing Liu 已提交
226 227 228 229 230 231
    # bind train_reader
    train_data_reader = reader.AsyncDataReader(
        args.train_feature_lst,
        args.train_label_lst,
        -1,
        split_sentence_threshold=1024)
232

Y
Yibing Liu 已提交
233 234 235 236 237 238 239 240 241 242 243
    train_data_reader.set_transformers(ltrans)

    def train_data_provider():
        for data in train_data_reader.batch_iterator(args.batch_size,
                                                     args.minimum_batch_size):
            yield batch_data_to_lod_tensors(args, data, fluid.CPUPlace())

    py_train_reader.decorate_tensor_provider(train_data_provider)

    if (os.path.exists(args.val_feature_lst) and
            os.path.exists(args.val_label_lst)):
244
        # test data reader
245 246 247 248 249
        test_data_reader = reader.AsyncDataReader(
            args.val_feature_lst,
            args.val_label_lst,
            -1,
            split_sentence_threshold=1024)
250 251
        test_data_reader.set_transformers(ltrans)

Y
Yibing Liu 已提交
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
        def test_data_provider():
            for data in test_data_reader.batch_iterator(
                    args.batch_size, args.minimum_batch_size):
                yield batch_data_to_lod_tensors(args, data, fluid.CPUPlace())

        py_test_reader.decorate_tensor_provider(test_data_provider)

    # validation
    def test(exe):
        # If test data not found, return invalid cost and accuracy
        if not (os.path.exists(args.val_feature_lst) and
                os.path.exists(args.val_label_lst)):
            return -1.0, -1.0
        batch_id = 0
        test_costs = []
        test_accs = []
        while True:
            if batch_id == 0:
                py_test_reader.start()
            try:
                if args.parallel:
                    cost, acc = exe.run(
                        fetch_list=[avg_cost.name, accuracy.name],
                        return_numpy=False)
                else:
                    cost, acc = exe.run(program=test_program,
                                        fetch_list=[avg_cost, accuracy],
                                        return_numpy=False)
                sys.stdout.write('.')
                sys.stdout.flush()
                test_costs.append(np.array(cost)[0])
                test_accs.append(np.array(acc)[0])
                batch_id += 1
            except fluid.core.EOFException:
                py_test_reader.reset()
                break
        return np.mean(test_costs), np.mean(test_accs)
Z
zhxfl 已提交
289

290
    # train
Y
Yibing Liu 已提交
291 292
    for pass_id in xrange(args.pass_num):
        pass_start_time = time.time()
Y
Yibing Liu 已提交
293 294 295 296
        batch_id = 0
        while True:
            if batch_id == 0:
                py_train_reader.start()
Y
Yibing Liu 已提交
297
            to_print = batch_id > 0 and (batch_id % args.print_per_batches == 0)
Y
Yibing Liu 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311
            try:
                if args.parallel:
                    outs = train_exe.run(
                        fetch_list=[avg_cost.name, accuracy.name]
                        if to_print else [],
                        return_numpy=False)
                else:
                    outs = exe.run(program=train_program,
                                   fetch_list=[avg_cost, accuracy]
                                   if to_print else [],
                                   return_numpy=False)
            except fluid.core.EOFException:
                py_train_reader.reset()
                break
Y
Yibing Liu 已提交
312 313

            if to_print:
Y
Yibing Liu 已提交
314 315 316 317 318 319
                if args.parallel:
                    print("\nBatch %d, train cost: %f, train acc: %f" %
                          (batch_id, np.mean(outs[0]), np.mean(outs[1])))
                else:
                    print("\nBatch %d, train cost: %f, train acc: %f" % (
                        batch_id, np.array(outs[0])[0], np.array(outs[1])[0]))
320
                # save the latest checkpoint
321 322 323
                if args.checkpoints != '':
                    model_path = os.path.join(args.checkpoints,
                                              "deep_asr.latest.checkpoint")
Y
Yibing Liu 已提交
324
                    fluid.io.save_persistables(exe, model_path, train_program)
Y
Yibing Liu 已提交
325 326 327
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
Y
Yibing Liu 已提交
328 329

            batch_id += 1
Y
Yibing Liu 已提交
330
        # run test
Y
Yibing Liu 已提交
331
        val_cost, val_acc = test(test_exe if args.parallel else exe)
332 333 334

        # save checkpoint per pass
        if args.checkpoints != '':
Y
Yibing Liu 已提交
335
            model_path = os.path.join(
336 337
                args.checkpoints,
                "deep_asr.pass_" + str(pass_id) + ".checkpoint")
Y
Yibing Liu 已提交
338
            fluid.io.save_persistables(exe, model_path, train_program)
339 340 341 342 343
        # save inference model
        if args.infer_models != '':
            model_path = os.path.join(
                args.infer_models,
                "deep_asr.pass_" + str(pass_id) + ".infer.model")
Y
Yibing Liu 已提交
344
            fluid.io.save_inference_model(model_path, ["feature"],
Y
Yibing Liu 已提交
345
                                          [prediction], exe, train_program)
Y
Yibing Liu 已提交
346 347 348 349
        # cal pass time
        pass_end_time = time.time()
        time_consumed = pass_end_time - pass_start_time
        # print info at pass end
350 351
        print("\nPass %d, time consumed: %f s, val cost: %f, val acc: %f\n" %
              (pass_id, time_consumed, val_cost, val_acc))
Y
Yibing Liu 已提交
352 353


Y
Yibing Liu 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366
def batch_data_to_lod_tensors(args, batch_data, place):
    features, labels, lod, name_lst = batch_data
    features = np.reshape(features, (-1, 11, 3, args.frame_dim))
    features = np.transpose(features, (0, 2, 1, 3))
    feature_t = fluid.LoDTensor()
    label_t = fluid.LoDTensor()
    feature_t.set(features, place)
    feature_t.set_lod([lod])
    label_t.set(labels, place)
    label_t.set_lod([lod])
    return feature_t, label_t


Y
Yibing Liu 已提交
367 368 369 370 371
if __name__ == '__main__':
    args = parse_args()
    print_arguments(args)

    train(args)