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

6
import argparse
7
import distutils.util
8
import multiprocessing
9
import paddle.v2 as paddle
10
from model import DeepSpeech2Model
11
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
12

13
NUM_CPU = multiprocessing.cpu_count() // 2
14
parser = argparse.ArgumentParser(description=__doc__)
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80


def add_arg(argname, type, default, help, **kwargs):
    type = distutils.util.strtobool if type == bool else type
    parser.add_argument(
        "--" + argname,
        default=default,
        type=type,
        help=help + ' Default: %(default)s.',
        **kwargs)


# yapf: disable
# configurations of optimization
add_arg('batch_size',       int,    256,    "Minibatch size.")
add_arg('learning_rate',    float,  5e-4,   "Learning rate.")
add_arg('use_sortagrad',    bool,   True,   "Use SortaGrad or not.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
add_arg('num_passes',       int,    200,    "# of training epochs.")
add_arg('is_local',         bool,   True,   "Use pserver or not.")
add_arg('num_iter_print',   int,    100,    "Every # iterations for printing "
                                            "train cost.")
# configurations of data preprocess
add_arg('max_duration',     float,  27.0,   "Longest audio duration allowed.")
add_arg('min_duration',     float,  0.0,    "Shortest audio duration allowed.")
add_arg('parallels_data',   int,    NUM_CPU,"# of CPUs for data preprocessing.")
add_arg('specgram_type',    str,
        'linear',
        "Audio feature type. Options: linear, mfcc.",
        choices=['linear', 'mfcc'])
add_arg('augment_conf_path',str,
        'conf/augmentation.config',
        "Filepath of augmentation configuration file (json-format).")
add_arg('shuffle_method',   str,
        'batch_shuffle_clipped',
        "Shuffle method.",
        choices=['instance_shuffle', 'batch_shuffle', 'batch_shuffle_clipped'])
# configurations of model structure
add_arg('num_conv_layers',  int,    2,      "# of convolution layers.")
add_arg('num_rnn_layers',   int,    3,      "# of recurrent layers.")
add_arg('rnn_layer_size',   int,    2048,   "# of recurrent cells per layer.")
add_arg('use_gru',          bool,   False,  "Use GRUs instead of Simple RNNs.")
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
# configurations of data io
add_arg('train_manifest',   str,
        'datasets/manifest.train',
        "Filepath of train manifest.")
add_arg('dev_manifest',     str,
        'datasets/manifest.dev',
        "Filepath of validation manifest.")
add_arg('mean_std_path',    str,
        'mean_std.npz',
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
        'datasets/vocab/eng_vocab.txt',
        "Filepath of vocabulary.")
# configurations of model io
add_arg('init_model_path',  str,
        None,
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
add_arg('output_model_dir', str,
        "./checkpoints",
        "Directory for saving checkpoints.")
81
args = parser.parse_args()
82
# yapf: disable
83 84 85


def train():
86
    """DeepSpeech2 training."""
87
    train_generator = DataGenerator(
88 89 90
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
        augmentation_config=open(args.augment_conf_path, 'r').read(),
91 92 93
        max_duration=args.max_duration,
        min_duration=args.min_duration,
        specgram_type=args.specgram_type,
94
        num_threads=args.parallels_data)
95
    dev_generator = DataGenerator(
96 97
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
98 99
        augmentation_config="{}",
        specgram_type=args.specgram_type,
100
        num_threads=args.parallels_data)
101
    train_batch_reader = train_generator.batch_reader_creator(
102
        manifest_path=args.train_manifest,
103
        batch_size=args.batch_size,
104
        min_batch_size=args.trainer_count,
105
        sortagrad=args.use_sortagrad if args.init_model_path is None else False,
106
        shuffle_method=args.shuffle_method)
107
    dev_batch_reader = dev_generator.batch_reader_creator(
108
        manifest_path=args.dev_manifest,
109
        batch_size=args.batch_size,
110
        min_batch_size=1,  # must be 1, but will have errors.
111
        sortagrad=False,
112
        shuffle_method=None)
113

114 115 116 117 118
    ds2_model = DeepSpeech2Model(
        vocab_size=train_generator.vocab_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
        rnn_layer_size=args.rnn_layer_size,
X
Xinghai Sun 已提交
119
        use_gru=args.use_gru,
120
        pretrained_model_path=args.init_model_path,
121
        share_rnn_weights=args.share_weights)
122 123 124 125
    ds2_model.train(
        train_batch_reader=train_batch_reader,
        dev_batch_reader=dev_batch_reader,
        feeding_dict=train_generator.feeding,
126
        learning_rate=args.learning_rate,
127
        gradient_clipping=400,
128
        num_passes=args.num_passes,
129
        num_iterations_print=args.num_iter_print,
130 131
        output_model_dir=args.output_model_dir,
        is_local=args.is_local)
132 133


134 135 136 137 138 139 140
def print_arguments(args):
    print("-----------  Configuration Arguments -----------")
    for arg, value in sorted(vars(args).iteritems()):
        print("%s: %s" % (arg, value))
    print("------------------------------------------------")


141
def main():
142
    print_arguments(args)
143
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
144 145 146 147 148
    train()


if __name__ == '__main__':
    main()