infer.py 8.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 7
import argparse
import gzip
8 9 10
import distutils.util
import paddle.v2 as paddle
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
11
from model import deep_speech2
Y
Yibing Liu 已提交
12
from decoder import *
13
from error_rate import wer
14
import utils
15

16
parser = argparse.ArgumentParser(description=__doc__)
17
parser.add_argument(
X
Xinghai Sun 已提交
18
    "--num_samples",
19
    default=100,
X
Xinghai Sun 已提交
20
    type=int,
21
    help="Number of samples for inference. (default: %(default)s)")
22
parser.add_argument(
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    "--num_conv_layers",
    default=2,
    type=int,
    help="Convolution layer number. (default: %(default)s)")
parser.add_argument(
    "--num_rnn_layers",
    default=3,
    type=int,
    help="RNN layer number. (default: %(default)s)")
parser.add_argument(
    "--rnn_layer_size",
    default=512,
    type=int,
    help="RNN layer cell number. (default: %(default)s)")
parser.add_argument(
    "--use_gpu",
    default=True,
    type=distutils.util.strtobool,
    help="Use gpu or not. (default: %(default)s)")
42
parser.add_argument(
43 44
    "--mean_std_filepath",
    default='mean_std.npz',
45 46
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
47
parser.add_argument(
48
    "--decode_manifest_path",
49
    default='data/manifest.libri.test-100sample',
50 51
    type=str,
    help="Manifest path for decoding. (default: %(default)s)")
52
parser.add_argument(
53 54 55 56
    "--model_filepath",
    default='./params.tar.gz',
    type=str,
    help="Model filepath. (default: %(default)s)")
57 58
parser.add_argument(
    "--vocab_filepath",
59
    default='datasets/vocab/eng_vocab.txt',
60 61
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
Y
Yibing Liu 已提交
62 63
parser.add_argument(
    "--decode_method",
Y
Yibing Liu 已提交
64
    default='best_path',
Y
Yibing Liu 已提交
65
    type=str,
66 67 68 69
    help="Method for ctc decoding:"
    "  best_path,"
    "  beam_search, "
    "   or beam_search_nproc. (default: %(default)s)")
Y
Yibing Liu 已提交
70 71
parser.add_argument(
    "--beam_size",
72
    default=500,
Y
Yibing Liu 已提交
73 74 75
    type=int,
    help="Width for beam search decoding. (default: %(default)d)")
parser.add_argument(
Y
Yibing Liu 已提交
76 77
    "--num_results_per_sample",
    default=1,
Y
Yibing Liu 已提交
78
    type=int,
Y
Yibing Liu 已提交
79 80 81
    help="Number of output per sample in beam search. (default: %(default)d)")
parser.add_argument(
    "--language_model_path",
Y
Yibing Liu 已提交
82
    default="data/1Billion.klm",
Y
Yibing Liu 已提交
83
    type=str,
Y
Yibing Liu 已提交
84
    help="Path for language model. (default: %(default)s)")
Y
Yibing Liu 已提交
85 86
parser.add_argument(
    "--alpha",
87
    default=0.26,
Y
Yibing Liu 已提交
88 89 90 91
    type=float,
    help="Parameter associated with language model. (default: %(default)f)")
parser.add_argument(
    "--beta",
92
    default=0.1,
Y
Yibing Liu 已提交
93 94
    type=float,
    help="Parameter associated with word count. (default: %(default)f)")
95 96 97 98 99 100
parser.add_argument(
    "--cutoff_prob",
    default=0.99,
    type=float,
    help="The cutoff probability of pruning"
    "in beam search. (default: %(default)f)")
101 102 103
args = parser.parse_args()


104
def infer():
Y
Yibing Liu 已提交
105
    """Inference for DeepSpeech2."""
106 107
    # initialize data generator
    data_generator = DataGenerator(
108
        vocab_filepath=args.vocab_filepath,
109 110
        mean_std_filepath=args.mean_std_filepath,
        augmentation_config='{}')
111

112
    # create network config
113 114 115
    # paddle.data_type.dense_array is used for variable batch input.
    # The size 161 * 161 is only an placeholder value and the real shape
    # of input batch data will be induced during training.
116
    audio_data = paddle.layer.data(
117
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
118 119
    text_data = paddle.layer.data(
        name="transcript_text",
120
        type=paddle.data_type.integer_value_sequence(data_generator.vocab_size))
121
    output_probs = deep_speech2(
122 123
        audio_data=audio_data,
        text_data=text_data,
124
        dict_size=data_generator.vocab_size,
125 126
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
127 128
        rnn_size=args.rnn_layer_size,
        is_inference=True)
129 130 131

    # load parameters
    parameters = paddle.parameters.Parameters.from_tar(
132
        gzip.open(args.model_filepath))
133 134

    # prepare infer data
135
    batch_reader = data_generator.batch_reader_creator(
136 137
        manifest_path=args.decode_manifest_path,
        batch_size=args.num_samples,
138
        sortagrad=False,
139
        shuffle_method=None)
140
    infer_data = batch_reader().next()
141

142 143 144
    # run inference
    infer_results = paddle.infer(
        output_layer=output_probs, parameters=parameters, input=infer_data)
145
    num_steps = len(infer_results) // len(infer_data)
146 147
    probs_split = [
        infer_results[i * num_steps:(i + 1) * num_steps]
148
        for i in xrange(len(infer_data))
149
    ]
150

Y
Yibing Liu 已提交
151 152
    ## decode and print
    # best path decode
153
    wer_sum, wer_counter = 0, 0
Y
Yibing Liu 已提交
154 155
    if args.decode_method == "best_path":
        for i, probs in enumerate(probs_split):
Y
Yibing Liu 已提交
156 157 158
            target_transcription = ''.join([
                data_generator.vocab_list[index] for index in infer_data[i][1]
            ])
Y
Yibing Liu 已提交
159
            best_path_transcription = ctc_best_path_decode(
Y
Yibing Liu 已提交
160
                probs_seq=probs, vocabulary=data_generator.vocab_list)
Y
Yibing Liu 已提交
161 162
            print("\nTarget Transcription: %s\nOutput Transcription: %s" %
                  (target_transcription, best_path_transcription))
163 164 165 166 167
            wer_cur = wer(target_transcription, best_path_transcription)
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f, average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
168 169
    # beam search decode
    elif args.decode_method == "beam_search":
170
        ext_scorer = Scorer(args.alpha, args.beta, args.language_model_path)
Y
Yibing Liu 已提交
171
        for i, probs in enumerate(probs_split):
Y
Yibing Liu 已提交
172 173 174
            target_transcription = ''.join([
                data_generator.vocab_list[index] for index in infer_data[i][1]
            ])
Y
Yibing Liu 已提交
175 176
            beam_search_result = ctc_beam_search_decoder(
                probs_seq=probs,
Y
Yibing Liu 已提交
177
                vocabulary=data_generator.vocab_list,
Y
Yibing Liu 已提交
178
                beam_size=args.beam_size,
Y
Yibing Liu 已提交
179
                blank_id=len(data_generator.vocab_list),
180 181
                cutoff_prob=args.cutoff_prob,
                ext_scoring_func=ext_scorer, )
Y
Yibing Liu 已提交
182
            print("\nTarget Transcription:\t%s" % target_transcription)
183

184
            for index in xrange(args.num_results_per_sample):
185 186 187 188 189 190 191 192 193 194 195 196
                result = beam_search_result[index]
                #output: index, log prob, beam result
                print("Beam %d: %f \t%s" % (index, result[0], result[1]))
            wer_cur = wer(target_transcription, beam_search_result[0][1])
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f , average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
    elif args.decode_method == "beam_search_nproc":
        ext_scorer = Scorer(args.alpha, args.beta, args.language_model_path)
        beam_search_nproc_results = ctc_beam_search_decoder_nproc(
            probs_split=probs_split,
197
            vocabulary=data_generator.vocab_list,
198
            beam_size=args.beam_size,
Y
Yibing Liu 已提交
199
            blank_id=len(data_generator.vocab_list),
200 201
            cutoff_prob=args.cutoff_prob,
            ext_scoring_func=ext_scorer, )
202
        for i, beam_search_result in enumerate(beam_search_nproc_results):
Y
Yibing Liu 已提交
203 204 205
            target_transcription = ''.join([
                data_generator.vocab_list[index] for index in infer_data[i][1]
            ])
206 207
            print("\nTarget Transcription:\t%s" % target_transcription)

208
            for index in xrange(args.num_results_per_sample):
Y
Yibing Liu 已提交
209
                result = beam_search_result[index]
Y
Yibing Liu 已提交
210
                #output: index, log prob, beam result
Y
Yibing Liu 已提交
211
                print("Beam %d: %f \t%s" % (index, result[0], result[1]))
212 213 214 215 216
            wer_cur = wer(target_transcription, beam_search_result[0][1])
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f , average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
217
    else:
Y
Yibing Liu 已提交
218 219
        raise ValueError("Decoding method [%s] is not supported." %
                         decode_method)
220 221 222


def main():
223
    utils.print_arguments(args)
224
    paddle.init(use_gpu=args.use_gpu, trainer_count=1)
225
    infer()
226 227 228 229


if __name__ == '__main__':
    main()