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

5
import paddle.v2 as paddle
6
import distutils.util
7
import argparse
8
import gzip
9
import time
X
Xinghai Sun 已提交
10 11
import sys
from model import deep_speech2
12 13
from audio_data_utils import DataGenerator
import numpy as np
14
import os
X
Xinghai Sun 已提交
15 16

#TODO: add WER metric
17 18

parser = argparse.ArgumentParser(
X
Xinghai Sun 已提交
19
    description='Simplified version of DeepSpeech2 trainer.')
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 54 55 56 57 58 59 60 61 62 63
    "--use_sortagrad",
    default=False,
    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(
    "--normalizer_manifest_path",
64
    default='data/manifest.libri.train-clean-100',
65 66 67 68
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
parser.add_argument(
    "--train_manifest_path",
69
    default='data/manifest.libri.train-clean-100',
70 71 72 73
    type=str,
    help="Manifest path for training. (default: %(default)s)")
parser.add_argument(
    "--dev_manifest_path",
74
    default='data/manifest.libri.dev-clean',
75 76
    type=str,
    help="Manifest path for validation. (default: %(default)s)")
77 78 79 80 81
parser.add_argument(
    "--vocab_filepath",
    default='data/eng_vocab.txt',
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
82 83 84 85 86
parser.add_argument(
    "--init_model_path",
    default='models/params.tar.gz',
    type=str,
    help="Model path for initialization. (default: %(default)s)")
87 88 89 90
args = parser.parse_args()


def train():
X
Xinghai Sun 已提交
91 92 93
    """
    DeepSpeech2 training.
    """
94
    # initialize data generator
95
    data_generator = DataGenerator(
96
        vocab_filepath=args.vocab_filepath,
97
        normalizer_manifest_path=args.normalizer_manifest_path,
98 99 100 101 102 103
        normalizer_num_samples=200,
        max_duration=20.0,
        min_duration=0.0,
        stride_ms=10,
        window_ms=20)

104
    # create network config
105
    dict_size = data_generator.vocabulary_size()
106 107 108
    audio_data = paddle.layer.data(
        name="audio_spectrogram",
        height=161,
109 110
        width=2000,
        type=paddle.data_type.dense_vector(322000))
111 112 113
    text_data = paddle.layer.data(
        name="transcript_text",
        type=paddle.data_type.integer_value_sequence(dict_size))
114
    cost = deep_speech2(
115 116 117 118 119
        audio_data=audio_data,
        text_data=text_data,
        dict_size=dict_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
120 121
        rnn_size=args.rnn_layer_size,
        is_inference=False)
122

123 124 125 126 127 128 129
    # create/load parameters and optimizer
    if args.init_model_path is None:
        parameters = paddle.parameters.create(cost)
    else:
        assert os.path.isfile(args.init_model_path), "Invalid model."
        parameters = paddle.parameters.Parameters.from_tar(
            gzip.open(args.init_model_path))
130
    optimizer = paddle.optimizer.Adam(
131
        learning_rate=args.adam_learning_rate, gradient_clipping_threshold=400)
132 133 134
    trainer = paddle.trainer.SGD(
        cost=cost, parameters=parameters, update_equation=optimizer)

135 136 137
    # prepare data reader
    train_batch_reader_sortagrad = data_generator.batch_reader_creator(
        manifest_path=args.train_manifest_path,
138
        batch_size=args.batch_size,
139 140 141 142 143 144
        padding_to=2000,
        flatten=True,
        sort_by_duration=True,
        shuffle=False)
    train_batch_reader_nosortagrad = data_generator.batch_reader_creator(
        manifest_path=args.train_manifest_path,
145
        batch_size=args.batch_size,
146 147 148 149 150 151
        padding_to=2000,
        flatten=True,
        sort_by_duration=False,
        shuffle=True)
    test_batch_reader = data_generator.batch_reader_creator(
        manifest_path=args.dev_manifest_path,
152
        batch_size=args.batch_size,
153 154 155 156 157 158
        padding_to=2000,
        flatten=True,
        sort_by_duration=False,
        shuffle=False)
    feeding = data_generator.data_name_feeding()

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

    # run train
183 184 185
    # first pass with sortagrad
    if args.use_sortagrad:
        trainer.train(
186
            reader=train_batch_reader_sortagrad,
187 188 189 190 191
            event_handler=event_handler,
            num_passes=1,
            feeding=feeding)
        args.num_passes -= 1
    # other passes without sortagrad
192
    trainer.train(
193
        reader=train_batch_reader_nosortagrad,
194
        event_handler=event_handler,
195
        num_passes=args.num_passes,
196 197 198 199
        feeding=feeding)


def main():
200
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
201 202 203 204 205
    train()


if __name__ == '__main__':
    main()