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


def tune():
Y
Yibing Liu 已提交
133
    """Tune parameters alpha and beta on one minibatch."""
134 135 136 137
    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!")
138 139 140

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

156 157 158 159 160 161 162
    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,
        pretrained_model_path=args.model_filepath)

163 164 165 166 167 168
    # 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]

169
    ## tune parameters in loop
Y
Yibing Liu 已提交
170
    for alpha, beta in params_grid:
171 172 173 174 175
        result_transcripts = ds2_model.infer_batch(
            infer_data=tune_data,
            decode_method='beam_search',
            beam_alpha=alpha,
            beam_beta=beta,
Y
Yibing Liu 已提交
176 177
            beam_size=args.beam_size,
            cutoff_prob=args.cutoff_prob,
178 179 180 181 182 183 184
            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
185
        print("alpha = %f\tbeta = %f\tWER = %f" %
186
              (alpha, beta, wer_sum / num_ins))
187 188 189


def main():
190 191
    utils.print_arguments(args)
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
192 193 194 195 196
    tune()


if __name__ == '__main__':
    main()