train.py 6.2 KB
Newer Older
X
Xinghai Sun 已提交
1 2 3 4
"""
   Trainer for a simplifed version of Baidu DeepSpeech2 model.
"""

5 6 7 8 9 10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import sys
import os
11
import argparse
12
import gzip
13
import time
14 15
import distutils.util
import paddle.v2 as paddle
X
Xinghai Sun 已提交
16
from model import deep_speech2
17
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
18

19
parser = argparse.ArgumentParser(description=__doc__)
20
parser.add_argument(
21
    "--batch_size", default=32, type=int, help="Minibatch size.")
22
parser.add_argument(
23 24 25 26
    "--num_passes",
    default=20,
    type=int,
    help="Training pass number. (default: %(default)s)")
27
parser.add_argument(
28 29 30 31
    "--num_conv_layers",
    default=2,
    type=int,
    help="Convolution layer number. (default: %(default)s)")
32
parser.add_argument(
33 34 35 36
    "--num_rnn_layers",
    default=3,
    type=int,
    help="RNN layer number. (default: %(default)s)")
37
parser.add_argument(
38 39 40 41
    "--rnn_layer_size",
    default=512,
    type=int,
    help="RNN layer cell number. (default: %(default)s)")
42
parser.add_argument(
43 44 45 46
    "--adam_learning_rate",
    default=5e-4,
    type=float,
    help="Learning rate for ADAM Optimizer. (default: %(default)s)")
47
parser.add_argument(
48 49 50 51
    "--use_gpu",
    default=True,
    type=distutils.util.strtobool,
    help="Use gpu or not. (default: %(default)s)")
52
parser.add_argument(
53
    "--use_sortagrad",
54
    default=True,
55 56 57 58 59 60 61 62
    type=distutils.util.strtobool,
    help="Use sortagrad or not. (default: %(default)s)")
parser.add_argument(
    "--trainer_count",
    default=4,
    type=int,
    help="Trainer number. (default: %(default)s)")
parser.add_argument(
63 64
    "--mean_std_filepath",
    default='mean_std.npz',
65 66 67 68
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
parser.add_argument(
    "--train_manifest_path",
69
    default='datasets/manifest.train',
70 71 72 73
    type=str,
    help="Manifest path for training. (default: %(default)s)")
parser.add_argument(
    "--dev_manifest_path",
74
    default='datasets/manifest.dev',
75 76
    type=str,
    help="Manifest path for validation. (default: %(default)s)")
77 78
parser.add_argument(
    "--vocab_filepath",
79
    default='datasets/vocab/eng_vocab.txt',
80 81
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
82 83
parser.add_argument(
    "--init_model_path",
Y
yangyaming 已提交
84
    default=None,
85
    type=str,
Y
yangyaming 已提交
86 87 88
    help="If set None, the training will start from scratch. "
    "Otherwise, the training will resume from "
    "the existing model of this path. (default: %(default)s)")
89 90 91 92 93 94
parser.add_argument(
    "--augmentation_config",
    default='{}',
    type=str,
    help="Augmentation configuration in json-format. "
    "(default: %(default)s)")
95 96 97 98
args = parser.parse_args()


def train():
X
Xinghai Sun 已提交
99 100 101
    """
    DeepSpeech2 training.
    """
102

103
    # initialize data generator
104 105 106
    def data_generator():
        return DataGenerator(
            vocab_filepath=args.vocab_filepath,
107 108
            mean_std_filepath=args.mean_std_filepath,
            augmentation_config=args.augmentation_config)
109

110 111
    train_generator = data_generator()
    test_generator = data_generator()
112

113
    # create network config
114
    # paddle.data_type.dense_array is used for variable batch input.
115 116
    # The size 161 * 161 is only an placeholder value and the real shape
    # of input batch data will be induced during training.
117
    audio_data = paddle.layer.data(
118
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
119 120
    text_data = paddle.layer.data(
        name="transcript_text",
121 122
        type=paddle.data_type.integer_value_sequence(
            train_generator.vocab_size))
123
    cost = deep_speech2(
124 125
        audio_data=audio_data,
        text_data=text_data,
126
        dict_size=train_generator.vocab_size,
127 128
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
129 130
        rnn_size=args.rnn_layer_size,
        is_inference=False)
131

132 133 134 135
    # create/load parameters and optimizer
    if args.init_model_path is None:
        parameters = paddle.parameters.create(cost)
    else:
Y
yangyaming 已提交
136 137
        if not os.path.isfile(args.init_model_path):
            raise IOError("Invalid model!")
138 139
        parameters = paddle.parameters.Parameters.from_tar(
            gzip.open(args.init_model_path))
140
    optimizer = paddle.optimizer.Adam(
141
        learning_rate=args.adam_learning_rate, gradient_clipping_threshold=400)
142 143 144
    trainer = paddle.trainer.SGD(
        cost=cost, parameters=parameters, update_equation=optimizer)

145
    # prepare data reader
146
    train_batch_reader = train_generator.batch_reader_creator(
147
        manifest_path=args.train_manifest_path,
148
        batch_size=args.batch_size,
149
        sortagrad=args.use_sortagrad if args.init_model_path is None else False,
150
        batch_shuffle=True)
151
    test_batch_reader = test_generator.batch_reader_creator(
152
        manifest_path=args.dev_manifest_path,
153
        batch_size=args.batch_size,
154
        sortagrad=False,
155
        batch_shuffle=False)
156

157 158
    # create event handler
    def event_handler(event):
159
        global start_time, cost_sum, cost_counter
160
        if isinstance(event, paddle.event.EndIteration):
161 162 163
            cost_sum += event.cost
            cost_counter += 1
            if event.batch_id % 50 == 0:
164 165
                print("\nPass: %d, Batch: %d, TrainCost: %f" %
                      (event.pass_id, event.batch_id, cost_sum / cost_counter))
166 167 168
                cost_sum, cost_counter = 0.0, 0
                with gzip.open("params.tar.gz", 'w') as f:
                    parameters.to_tar(f)
169 170 171
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
172 173
        if isinstance(event, paddle.event.BeginPass):
            start_time = time.time()
174
            cost_sum, cost_counter = 0.0, 0
175
        if isinstance(event, paddle.event.EndPass):
176 177 178 179
            result = trainer.test(
                reader=test_batch_reader, feeding=test_generator.feeding)
            print("\n------- Time: %d sec,  Pass: %d, ValidationCost: %s" %
                  (time.time() - start_time, event.pass_id, result.cost))
180 181

    # run train
182
    trainer.train(
183
        reader=train_batch_reader,
184
        event_handler=event_handler,
185
        num_passes=args.num_passes,
186
        feeding=train_generator.feeding)
187 188 189


def main():
190
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
191 192 193 194 195
    train()


if __name__ == '__main__':
    main()