train.py 6.3 KB
Newer Older
1
"""Trainer for DeepSpeech2 model."""
2 3 4 5 6 7
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

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

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


def train():
X
Xinghai Sun 已提交
96 97 98
    """
    DeepSpeech2 training.
    """
99

100
    # initialize data generator
101 102 103
    def data_generator():
        return DataGenerator(
            vocab_filepath=args.vocab_filepath,
104 105
            mean_std_filepath=args.mean_std_filepath,
            augmentation_config=args.augmentation_config)
106

107 108
    train_generator = data_generator()
    test_generator = data_generator()
109

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

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

142
    # prepare data reader
143
    train_batch_reader = train_generator.batch_reader_creator(
144
        manifest_path=args.train_manifest_path,
145
        batch_size=args.batch_size,
146
        min_batch_size=args.trainer_count,
147
        sortagrad=args.use_sortagrad if args.init_model_path is None else False,
148
        batch_shuffle=True)
149
    test_batch_reader = test_generator.batch_reader_creator(
150
        manifest_path=args.dev_manifest_path,
151
        batch_size=args.batch_size,
152
        min_batch_size=1,  # must be 1, but will have errors.
153
        sortagrad=False,
154
        batch_shuffle=False)
155

156 157
    # create event handler
    def event_handler(event):
158
        global start_time, cost_sum, cost_counter
159
        if isinstance(event, paddle.event.EndIteration):
160 161
            cost_sum += event.cost
            cost_counter += 1
162 163 164
            if (event.batch_id + 1) % 100 == 0:
                print("\nPass: %d, Batch: %d, TrainCost: %f" % (
                    event.pass_id, event.batch_id + 1, cost_sum / cost_counter))
165
                cost_sum, cost_counter = 0.0, 0
166
                with gzip.open("params.tar.gz", 'w') as f:
167
                    parameters.to_tar(f)
168 169 170
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
171 172
        if isinstance(event, paddle.event.BeginPass):
            start_time = time.time()
173
            cost_sum, cost_counter = 0.0, 0
174
        if isinstance(event, paddle.event.EndPass):
175 176 177 178
            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))
179 180

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


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


if __name__ == '__main__':
    main()