train.py 7.2 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
import distutils.util
12
import multiprocessing
13
import paddle.v2 as paddle
X
Xinghai Sun 已提交
14
from model import deep_speech2
15
from data_utils.data import DataGenerator
16
import utils
X
Xinghai Sun 已提交
17

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


def train():
121
    """DeepSpeech2 training."""
122

123
    # initialize data generator
124 125 126
    def data_generator():
        return DataGenerator(
            vocab_filepath=args.vocab_filepath,
127
            mean_std_filepath=args.mean_std_filepath,
128 129 130 131
            augmentation_config=args.augmentation_config,
            max_duration=args.max_duration,
            min_duration=args.min_duration,
            num_threads=args.num_threads_data)
132

133 134
    train_generator = data_generator()
    test_generator = data_generator()
135

136
    # create network config
137
    # paddle.data_type.dense_array is used for variable batch input.
138 139
    # The size 161 * 161 is only an placeholder value and the real shape
    # of input batch data will be induced during training.
140
    audio_data = paddle.layer.data(
141
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
142 143
    text_data = paddle.layer.data(
        name="transcript_text",
144 145
        type=paddle.data_type.integer_value_sequence(
            train_generator.vocab_size))
146
    cost = deep_speech2(
147 148
        audio_data=audio_data,
        text_data=text_data,
149
        dict_size=train_generator.vocab_size,
150 151
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
152 153
        rnn_size=args.rnn_layer_size,
        is_inference=False)
154

155 156 157 158
    # create/load parameters and optimizer
    if args.init_model_path is None:
        parameters = paddle.parameters.create(cost)
    else:
Y
yangyaming 已提交
159 160
        if not os.path.isfile(args.init_model_path):
            raise IOError("Invalid model!")
161 162
        parameters = paddle.parameters.Parameters.from_tar(
            gzip.open(args.init_model_path))
163
    optimizer = paddle.optimizer.Adam(
164
        learning_rate=args.adam_learning_rate, gradient_clipping_threshold=400)
165 166 167
    trainer = paddle.trainer.SGD(
        cost=cost, parameters=parameters, update_equation=optimizer)

168
    # prepare data reader
169
    train_batch_reader = train_generator.batch_reader_creator(
170
        manifest_path=args.train_manifest_path,
171
        batch_size=args.batch_size,
172
        min_batch_size=args.trainer_count,
173
        sortagrad=args.use_sortagrad if args.init_model_path is None else False,
174
        shuffle_method=args.shuffle_method)
175
    test_batch_reader = test_generator.batch_reader_creator(
176
        manifest_path=args.dev_manifest_path,
177
        batch_size=args.batch_size,
178
        min_batch_size=1,  # must be 1, but will have errors.
179
        sortagrad=False,
180
        shuffle_method=None)
181

182 183
    # create event handler
    def event_handler(event):
184
        global start_time, cost_sum, cost_counter
185
        if isinstance(event, paddle.event.EndIteration):
186 187
            cost_sum += event.cost
            cost_counter += 1
188 189 190
            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))
191
                cost_sum, cost_counter = 0.0, 0
192
                with gzip.open("params.tar.gz", 'w') as f:
193
                    parameters.to_tar(f)
194 195 196
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
197 198
        if isinstance(event, paddle.event.BeginPass):
            start_time = time.time()
199
            cost_sum, cost_counter = 0.0, 0
200
        if isinstance(event, paddle.event.EndPass):
201 202 203 204
            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))
205 206

    # run train
207
    trainer.train(
208
        reader=train_batch_reader,
209
        event_handler=event_handler,
210
        num_passes=args.num_passes,
211
        feeding=train_generator.feeding)
212 213 214


def main():
215
    utils.print_arguments(args)
216
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
217 218 219 220 221
    train()


if __name__ == '__main__':
    main()