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 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 61 62 63 64 65 66
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)")
67 68 69 70 71 72
parser.add_argument(
    "--shuffle_method",
    default='instance_shuffle',
    type=str,
    help="Shuffle method: 'instance_shuffle', 'batch_shuffle', "
    "'batch_shuffle_batch'. (default: %(default)s)")
73 74 75 76 77
parser.add_argument(
    "--trainer_count",
    default=4,
    type=int,
    help="Trainer number. (default: %(default)s)")
78 79 80 81 82
parser.add_argument(
    "--num_threads_data",
    default=12,
    type=int,
    help="Number of cpu threads for preprocessing data. (default: %(default)s)")
83
parser.add_argument(
84 85
    "--mean_std_filepath",
    default='mean_std.npz',
86 87 88 89
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
parser.add_argument(
    "--train_manifest_path",
90
    default='datasets/manifest.train',
91 92 93 94
    type=str,
    help="Manifest path for training. (default: %(default)s)")
parser.add_argument(
    "--dev_manifest_path",
95
    default='datasets/manifest.dev',
96 97
    type=str,
    help="Manifest path for validation. (default: %(default)s)")
98 99
parser.add_argument(
    "--vocab_filepath",
100
    default='datasets/vocab/eng_vocab.txt',
101 102
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
103 104
parser.add_argument(
    "--init_model_path",
Y
yangyaming 已提交
105
    default=None,
106
    type=str,
Y
yangyaming 已提交
107 108 109
    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)")
110 111 112 113 114 115
parser.add_argument(
    "--augmentation_config",
    default='{}',
    type=str,
    help="Augmentation configuration in json-format. "
    "(default: %(default)s)")
116 117 118 119
args = parser.parse_args()


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

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

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

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

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

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

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

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


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


if __name__ == '__main__':
    main()