train.py 6.5 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
15
import utils
X
Xinghai Sun 已提交
16

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


def train():
103
    """DeepSpeech2 training."""
104

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

112 113
    train_generator = data_generator()
    test_generator = data_generator()
114

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

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

147
    # prepare data reader
148
    train_batch_reader = train_generator.batch_reader_creator(
149
        manifest_path=args.train_manifest_path,
150
        batch_size=args.batch_size,
151
        min_batch_size=args.trainer_count,
152
        sortagrad=args.use_sortagrad if args.init_model_path is None else False,
153
        shuffle_method=args.shuffle_method)
154
    test_batch_reader = test_generator.batch_reader_creator(
155
        manifest_path=args.dev_manifest_path,
156
        batch_size=args.batch_size,
157
        min_batch_size=1,  # must be 1, but will have errors.
158
        sortagrad=False,
159
        shuffle_method=None)
160

161 162
    # create event handler
    def event_handler(event):
163
        global start_time, cost_sum, cost_counter
164
        if isinstance(event, paddle.event.EndIteration):
165 166
            cost_sum += event.cost
            cost_counter += 1
167 168 169
            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))
170
                cost_sum, cost_counter = 0.0, 0
171
                with gzip.open("params.tar.gz", 'w') as f:
172
                    parameters.to_tar(f)
173 174 175
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
176 177
        if isinstance(event, paddle.event.BeginPass):
            start_time = time.time()
178
            cost_sum, cost_counter = 0.0, 0
179
        if isinstance(event, paddle.event.EndPass):
180 181 182 183
            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))
184 185

    # run train
186
    trainer.train(
187
        reader=train_batch_reader,
188
        event_handler=event_handler,
189
        num_passes=args.num_passes,
190
        feeding=train_generator.feeding)
191 192 193


def main():
194
    utils.print_arguments(args)
195
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
196 197 198 199 200
    train()


if __name__ == '__main__':
    main()