tune.py 6.1 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
import numpy as np
7 8
import distutils.util
import argparse
9
import multiprocessing
Y
Yibing Liu 已提交
10
import paddle.v2 as paddle
Y
Yibing Liu 已提交
11
from data_utils.data import DataGenerator
12
from model import DeepSpeech2Model
13
from error_rate import wer
Y
Yibing Liu 已提交
14
import utils
15

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
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)")
X
Xinghai Sun 已提交
37 38
parser.add_argument(
    "--use_gru",
39 40
    default=False,
    type=distutils.util.strtobool,
X
Xinghai Sun 已提交
41
    help="Use GRU or simple RNN. (default: %(default)s)")
42 43 44 45 46
parser.add_argument(
    "--use_gpu",
    default=True,
    type=distutils.util.strtobool,
    help="Use gpu or not. (default: %(default)s)")
47 48 49 50 51
parser.add_argument(
    "--trainer_count",
    default=8,
    type=int,
    help="Trainer number. (default: %(default)s)")
Y
Yibing Liu 已提交
52 53
parser.add_argument(
    "--num_threads_data",
54
    default=1,
Y
Yibing Liu 已提交
55 56 57 58
    type=int,
    help="Number of cpu threads for preprocessing data. (default: %(default)s)")
parser.add_argument(
    "--num_processes_beam_search",
59
    default=multiprocessing.cpu_count() // 2,
Y
Yibing Liu 已提交
60 61
    type=int,
    help="Number of cpu processes for beam search. (default: %(default)s)")
62 63 64 65 66 67
parser.add_argument(
    "--specgram_type",
    default='linear',
    type=str,
    help="Feature type of audio data: 'linear' (power spectrum)"
    " or 'mfcc'. (default: %(default)s)")
Y
Yibing Liu 已提交
68 69 70 71 72
parser.add_argument(
    "--mean_std_filepath",
    default='mean_std.npz',
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
73
parser.add_argument(
74
    "--tune_manifest_path",
75
    default='datasets/manifest.dev',
76
    type=str,
77
    help="Manifest path for tuning. (default: %(default)s)")
78 79
parser.add_argument(
    "--model_filepath",
Y
Yibing Liu 已提交
80
    default='checkpoints/params.latest.tar.gz',
81 82 83 84
    type=str,
    help="Model filepath. (default: %(default)s)")
parser.add_argument(
    "--vocab_filepath",
Y
Yibing Liu 已提交
85
    default='datasets/vocab/eng_vocab.txt',
86 87 88 89 90 91 92 93 94
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
parser.add_argument(
    "--beam_size",
    default=500,
    type=int,
    help="Width for beam search decoding. (default: %(default)d)")
parser.add_argument(
    "--language_model_path",
Y
Yibing Liu 已提交
95
    default="lm/data/common_crawl_00.prune01111.trie.klm",
96 97 98 99
    type=str,
    help="Path for language model. (default: %(default)s)")
parser.add_argument(
    "--alpha_from",
100
    default=0.1,
101
    type=float,
102
    help="Where alpha starts from. (default: %(default)f)")
103
parser.add_argument(
104 105 106 107
    "--num_alphas",
    default=14,
    type=int,
    help="Number of candidate alphas. (default: %(default)d)")
108 109
parser.add_argument(
    "--alpha_to",
110
    default=0.36,
111
    type=float,
112
    help="Where alpha ends with. (default: %(default)f)")
113 114
parser.add_argument(
    "--beta_from",
115
    default=0.05,
116
    type=float,
117
    help="Where beta starts from. (default: %(default)f)")
118
parser.add_argument(
119 120
    "--num_betas",
    default=20,
121
    type=float,
122
    help="Number of candidate betas. (default: %(default)d)")
123 124
parser.add_argument(
    "--beta_to",
125
    default=1.0,
126
    type=float,
127 128 129 130 131 132 133
    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)")
134 135 136 137
args = parser.parse_args()


def tune():
Y
Yibing Liu 已提交
138
    """Tune parameters alpha and beta on one minibatch."""
139 140 141 142
    if not args.num_alphas >= 0:
        raise ValueError("num_alphas must be non-negative!")
    if not args.num_betas >= 0:
        raise ValueError("num_betas must be non-negative!")
143 144 145

    data_generator = DataGenerator(
        vocab_filepath=args.vocab_filepath,
Y
Yibing Liu 已提交
146
        mean_std_filepath=args.mean_std_filepath,
Y
Yibing Liu 已提交
147
        augmentation_config='{}',
148
        specgram_type=args.specgram_type,
Y
Yibing Liu 已提交
149
        num_threads=args.num_threads_data)
Y
Yibing Liu 已提交
150
    batch_reader = data_generator.batch_reader_creator(
151
        manifest_path=args.tune_manifest_path,
152
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
153 154
        sortagrad=False,
        shuffle_method=None)
155 156 157 158
    tune_data = batch_reader().next()
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in tune_data
159 160
    ]

161 162 163 164 165
    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 已提交
166
        use_gru=args.use_gru,
167 168
        pretrained_model_path=args.model_filepath)

169 170 171 172 173 174
    # 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]

175
    ## tune parameters in loop
Y
Yibing Liu 已提交
176
    for alpha, beta in params_grid:
177 178 179 180 181
        result_transcripts = ds2_model.infer_batch(
            infer_data=tune_data,
            decode_method='beam_search',
            beam_alpha=alpha,
            beam_beta=beta,
Y
Yibing Liu 已提交
182 183
            beam_size=args.beam_size,
            cutoff_prob=args.cutoff_prob,
184 185 186 187 188 189 190
            vocab_list=data_generator.vocab_list,
            language_model_path=args.language_model_path,
            num_processes=args.num_processes_beam_search)
        wer_sum, num_ins = 0.0, 0
        for target, result in zip(target_transcripts, result_transcripts):
            wer_sum += wer(target, result)
            num_ins += 1
191
        print("alpha = %f\tbeta = %f\tWER = %f" %
192
              (alpha, beta, wer_sum / num_ins))
193 194 195


def main():
196 197
    utils.print_arguments(args)
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
198 199 200 201 202
    tune()


if __name__ == '__main__':
    main()