tune.py 7.8 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4
"""Parameters tuning for DeepSpeech2 model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
5 6 7 8 9

import paddle.v2 as paddle
import distutils.util
import argparse
import gzip
Y
Yibing Liu 已提交
10
from data_utils.data import DataGenerator
11 12
from model import deep_speech2
from decoder import *
Y
Yibing Liu 已提交
13
from scorer import Scorer
14 15
from error_rate import wer

Y
Yibing Liu 已提交
16
parser = argparse.ArgumentParser(description=__doc__)
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
parser.add_argument(
    "--num_samples",
    default=100,
    type=int,
    help="Number of samples for parameters tuning. (default: %(default)s)")
parser.add_argument(
    "--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)")
Y
Yibing Liu 已提交
42 43 44 45 46
parser.add_argument(
    "--mean_std_filepath",
    default='mean_std.npz',
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
parser.add_argument(
    "--normalizer_manifest_path",
    default='data/manifest.libri.train-clean-100',
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
parser.add_argument(
    "--decode_manifest_path",
    default='data/manifest.libri.test-100sample',
    type=str,
    help="Manifest path for decoding. (default: %(default)s)")
parser.add_argument(
    "--model_filepath",
    default='./params.tar.gz',
    type=str,
    help="Model filepath. (default: %(default)s)")
parser.add_argument(
    "--vocab_filepath",
Y
Yibing Liu 已提交
64
    default='datasets/vocab/eng_vocab.txt',
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
parser.add_argument(
    "--decode_method",
    default='beam_search_nproc',
    type=str,
    help="Method for decoding, beam_search or beam_search_nproc. (default: %(default)s)"
)
parser.add_argument(
    "--beam_size",
    default=500,
    type=int,
    help="Width for beam search decoding. (default: %(default)d)")
parser.add_argument(
    "--num_results_per_sample",
    default=1,
    type=int,
    help="Number of outputs per sample in beam search. (default: %(default)d)")
parser.add_argument(
    "--language_model_path",
Y
Yibing Liu 已提交
85
    default="data/en.00.UNKNOWN.klm",
86 87 88 89
    type=str,
    help="Path for language model. (default: %(default)s)")
parser.add_argument(
    "--alpha_from",
90
    default=0.1,
91
    type=float,
92
    help="Where alpha starts from. (default: %(default)f)")
93
parser.add_argument(
94 95 96 97
    "--num_alphas",
    default=14,
    type=int,
    help="Number of candidate alphas. (default: %(default)d)")
98 99
parser.add_argument(
    "--alpha_to",
100
    default=0.36,
101
    type=float,
102
    help="Where alpha ends with. (default: %(default)f)")
103 104
parser.add_argument(
    "--beta_from",
105
    default=0.05,
106
    type=float,
107
    help="Where beta starts from. (default: %(default)f)")
108
parser.add_argument(
109 110
    "--num_betas",
    default=20,
111
    type=float,
112
    help="Number of candidate betas. (default: %(default)d)")
113 114
parser.add_argument(
    "--beta_to",
115
    default=1.0,
116
    type=float,
117 118 119 120 121 122 123
    help="Where beta ends with. (default: %(default)f)")
parser.add_argument(
    "--cutoff_prob",
    default=0.99,
    type=float,
    help="The cutoff probability of pruning"
    "in beam search. (default: %(default)f)")
124 125 126 127
args = parser.parse_args()


def tune():
Y
Yibing Liu 已提交
128
    """Tune parameters alpha and beta on one minibatch."""
129

130 131
    if not args.num_alphas >= 0:
        raise ValueError("num_alphas must be non-negative!")
132

133 134
    if not args.num_betas >= 0:
        raise ValueError("num_betas must be non-negative!")
135 136 137 138

    # initialize data generator
    data_generator = DataGenerator(
        vocab_filepath=args.vocab_filepath,
Y
Yibing Liu 已提交
139 140
        mean_std_filepath=args.mean_std_filepath,
        augmentation_config='{}')
141 142

    # create network config
Y
Yibing Liu 已提交
143 144 145
    # 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.
146
    audio_data = paddle.layer.data(
Y
Yibing Liu 已提交
147
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
148 149
    text_data = paddle.layer.data(
        name="transcript_text",
Y
Yibing Liu 已提交
150
        type=paddle.data_type.integer_value_sequence(data_generator.vocab_size))
151 152 153
    output_probs = deep_speech2(
        audio_data=audio_data,
        text_data=text_data,
Y
Yibing Liu 已提交
154
        dict_size=data_generator.vocab_size,
155 156 157 158 159 160 161 162 163 164
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
        rnn_size=args.rnn_layer_size,
        is_inference=True)

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

    # prepare infer data
Y
Yibing Liu 已提交
165
    batch_reader = data_generator.batch_reader_creator(
166 167
        manifest_path=args.decode_manifest_path,
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
168 169
        sortagrad=False,
        shuffle_method=None)
170
    # get one batch data for tuning
Y
Yibing Liu 已提交
171
    infer_data = batch_reader().next()
172 173 174 175

    # run inference
    infer_results = paddle.infer(
        output_layer=output_probs, parameters=parameters, input=infer_data)
Y
Yibing Liu 已提交
176
    num_steps = len(infer_results) // len(infer_data)
177 178 179 180 181
    probs_split = [
        infer_results[i * num_steps:(i + 1) * num_steps]
        for i in xrange(0, len(infer_data))
    ]

182 183 184 185 186 187
    # create grid for search
    cand_alphas = np.linspace(args.alpha_from, args.alpha_to, args.num_alphas)
    cand_betas = np.linspace(args.beta_from, args.beta_to, args.num_betas)
    params_grid = [(alpha, beta) for alpha in cand_alphas
                   for beta in cand_betas]

188 189 190 191 192 193 194
    ## tune parameters in loop
    for (alpha, beta) in params_grid:
        wer_sum, wer_counter = 0, 0
        ext_scorer = Scorer(alpha, beta, args.language_model_path)
        # beam search decode
        if args.decode_method == "beam_search":
            for i, probs in enumerate(probs_split):
Y
Yibing Liu 已提交
195 196 197 198
                target_transcription = ''.join([
                    data_generator.vocab_list[index]
                    for index in infer_data[i][1]
                ])
199 200
                beam_search_result = ctc_beam_search_decoder(
                    probs_seq=probs,
Y
Yibing Liu 已提交
201
                    vocabulary=data_generator.vocab_list,
202
                    beam_size=args.beam_size,
Y
Yibing Liu 已提交
203
                    blank_id=len(data_generator.vocab_list),
204 205
                    cutoff_prob=args.cutoff_prob,
                    ext_scoring_func=ext_scorer, )
206 207 208 209 210 211
                wer_sum += wer(target_transcription, beam_search_result[0][1])
                wer_counter += 1
        # beam search using multiple processes
        elif args.decode_method == "beam_search_nproc":
            beam_search_nproc_results = ctc_beam_search_decoder_nproc(
                probs_split=probs_split,
Y
Yibing Liu 已提交
212
                vocabulary=data_generator.vocab_list,
213
                beam_size=args.beam_size,
214
                cutoff_prob=args.cutoff_prob,
Y
Yibing Liu 已提交
215
                blank_id=len(data_generator.vocab_list),
216
                ext_scoring_func=ext_scorer, )
217
            for i, beam_search_result in enumerate(beam_search_nproc_results):
Y
Yibing Liu 已提交
218 219 220 221
                target_transcription = ''.join([
                    data_generator.vocab_list[index]
                    for index in infer_data[i][1]
                ])
222 223 224
                wer_sum += wer(target_transcription, beam_search_result[0][1])
                wer_counter += 1
        else:
Y
Yibing Liu 已提交
225 226
            raise ValueError("Decoding method [%s] is not supported." %
                             decode_method)
227 228 229 230 231 232 233 234 235 236 237 238

        print("alpha = %f\tbeta = %f\tWER = %f" %
              (alpha, beta, wer_sum / wer_counter))


def main():
    paddle.init(use_gpu=args.use_gpu, trainer_count=1)
    tune()


if __name__ == '__main__':
    main()