infer.py 5.0 KB
Newer Older
1
"""Inferer for DeepSpeech2 model."""
2 3 4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
X
Xinghai Sun 已提交
5

6
import argparse
7
import distutils.util
8
import multiprocessing
9 10
import paddle.v2 as paddle
from data_utils.data import DataGenerator
11
from model import DeepSpeech2Model
Y
yangyaming 已提交
12
from error_rate import wer, cer
13

14
NUM_CPU = multiprocessing.cpu_count() // 2
15
parser = argparse.ArgumentParser(description=__doc__)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36


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 overall
add_arg('num_samples',      int,    10,     "# of samples to infer.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('beam_size',        int,    500,    "Beam search width.")
add_arg('parallels_bsearch',int,    NUM_CPU,"# of CPUs for beam search.")
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.")
37 38 39
add_arg('alpha',            float,  0.36,   "Coef of LM for beam search.")
add_arg('beta',             float,  0.25,   "Coef of WC for beam search.")
add_arg('cutoff_prob',      float,  0.99,   "Cutoff probability for pruning.")
40
add_arg('use_gru',          bool,   False,  "Use GRUs instead of Simple RNNs.")
41
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
42 43 44 45 46 47 48 49 50 51 52
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('infer_manifest',   str,
        'datasets/manifest.dev',
        "Filepath of manifest to infer.")
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.")
53 54 55
add_arg('lang_model_path',  str,
        'lm/data/common_crawl_00.prune01111.trie.klm',
        "Filepath for language model.")
56 57 58 59
add_arg('model_path',       str,
        './checkpoints/params.latest.tar.gz',
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
60 61 62 63 64 65 66 67 68 69 70 71
add_arg('decoder_method',   str,
        'ctc_beam_search',
        "Decoder method. Options: ctc_beam_search, ctc_greedy",
        choices = ['ctc_beam_search', 'ctc_greedy'])
add_arg('error_rate_type',  str,
        'wer',
        "Error rate type for evaluation.",
        choices=['wer', 'cer'])
add_arg('specgram_type',    str,
        'linear',
        "Audio feature type. Options: linear, mfcc.",
        choices=['linear', 'mfcc'])
72
args = parser.parse_args()
73
# yapf: disable
74 75


76
def infer():
Y
Yibing Liu 已提交
77
    """Inference for DeepSpeech2."""
78
    data_generator = DataGenerator(
79 80
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
81
        augmentation_config='{}',
82
        specgram_type=args.specgram_type,
83
        num_threads=1)
84
    batch_reader = data_generator.batch_reader_creator(
85
        manifest_path=args.infer_manifest,
86
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
87
        min_batch_size=1,
88
        sortagrad=False,
89
        shuffle_method=None)
90
    infer_data = batch_reader().next()
91

92 93 94 95 96
    ds2_model = DeepSpeech2Model(
        vocab_size=data_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 已提交
97
        use_gru=args.use_gru,
98
        pretrained_model_path=args.model_path,
99
        share_rnn_weights=args.share_rnn_weights)
100 101
    result_transcripts = ds2_model.infer_batch(
        infer_data=infer_data,
102
        decoder_method=args.decoder_method,
103 104 105 106 107
        beam_alpha=args.alpha,
        beam_beta=args.beta,
        beam_size=args.beam_size,
        cutoff_prob=args.cutoff_prob,
        vocab_list=data_generator.vocab_list,
108 109
        language_model_path=args.lang_model_path,
        num_processes=args.parallels_bsearch)
110

Y
yangyaming 已提交
111
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
112 113 114
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in infer_data
Y
Yibing Liu 已提交
115
    ]
116 117 118
    for target, result in zip(target_transcripts, result_transcripts):
        print("\nTarget Transcription: %s\nOutput Transcription: %s" %
              (target, result))
Y
yangyaming 已提交
119 120
        print("Current error rate [%s] = %f" %
              (args.error_rate_type, error_rate_func(target, result)))
121 122


123 124 125 126 127 128 129
def print_arguments(args):
    print("-----------  Configuration Arguments -----------")
    for arg, value in sorted(vars(args).iteritems()):
        print("%s: %s" % (arg, value))
    print("------------------------------------------------")


130
def main():
131
    print_arguments(args)
132
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
133
    infer()
134 135 136 137


if __name__ == '__main__':
    main()