tune.py 5.2 KB
Newer Older
1
"""Beam search parameters tuning for DeepSpeech2 model."""
Y
Yibing Liu 已提交
2 3 4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
5

6
import numpy as np
7
import argparse
X
Xinghai Sun 已提交
8
import functools
Y
Yibing Liu 已提交
9
import paddle.v2 as paddle
10
import _init_paths
Y
Yibing Liu 已提交
11
from data_utils.data import DataGenerator
12
from model_utils.model import DeepSpeech2Model
13 14
from utils.error_rate import wer
from utils.utility import add_arguments, print_arguments
15

16
parser = argparse.ArgumentParser(description=__doc__)
X
Xinghai Sun 已提交
17 18
add_arg = functools.partial(add_arguments, argparser=parser)
# yapf: disable
19 20 21
add_arg('num_samples',      int,    100,    "# of samples to infer.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('beam_size',        int,    500,    "Beam search width.")
22
add_arg('num_proc_bsearch', int,    12,     "# of CPUs for beam search.")
23 24 25
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.")
26 27 28 29 30
add_arg('num_alphas',       int,    14,     "# of alpha candidates for tuning.")
add_arg('num_betas',        int,    20,     "# of beta candidates for tuning.")
add_arg('alpha_from',       float,  0.1,    "Where alpha starts tuning from.")
add_arg('alpha_to',         float,  0.36,   "Where alpha ends tuning with.")
add_arg('beta_from',        float,  0.05,   "Where beta starts tuning from.")
31
add_arg('beta_to',          float,  1.0,    "Where beta ends tuning with.")
32
add_arg('cutoff_prob',      float,  0.99,   "Cutoff probability for pruning.")
33
add_arg('use_gru',          bool,   False,  "Use GRUs instead of simple RNNs.")
34
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
35 36
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
37
add_arg('tune_manifest',    str,
38
        'data/librispeech/manifest.dev',
39 40
        "Filepath of manifest to tune.")
add_arg('mean_std_path',    str,
41
        'data/librispeech/mean_std.npz',
42 43
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
44
        'data/librispeech/vocab.txt',
45
        "Filepath of vocabulary.")
46
add_arg('lang_model_path',  str,
47
        'models/lm/common_crawl_00.prune01111.trie.klm',
48
        "Filepath for language model.")
49
add_arg('model_path',       str,
50
        './checkpoints/libri/params.latest.tar.gz',
51 52
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
53 54 55 56 57 58 59 60
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'])
61
# yapf: disable
X
Xinghai Sun 已提交
62
args = parser.parse_args()
63

64

65
def tune():
Y
Yibing Liu 已提交
66
    """Tune parameters alpha and beta on one minibatch."""
67 68 69 70
    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!")
71 72

    data_generator = DataGenerator(
73 74
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
Y
Yibing Liu 已提交
75
        augmentation_config='{}',
76
        specgram_type=args.specgram_type,
77
        num_threads=1)
Y
Yibing Liu 已提交
78
    batch_reader = data_generator.batch_reader_creator(
79
        manifest_path=args.tune_manifest,
80
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
81 82
        sortagrad=False,
        shuffle_method=None)
83 84 85 86
    tune_data = batch_reader().next()
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in tune_data
87 88
    ]

89 90 91 92 93
    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 已提交
94
        use_gru=args.use_gru,
95
        pretrained_model_path=args.model_path,
96
        share_rnn_weights=args.share_rnn_weights)
97

98 99 100 101 102 103
    # 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]

104
    ## tune parameters in loop
Y
Yibing Liu 已提交
105
    for alpha, beta in params_grid:
106 107
        result_transcripts = ds2_model.infer_batch(
            infer_data=tune_data,
108
            decoding_method='ctc_beam_search',
109 110
            beam_alpha=alpha,
            beam_beta=beta,
Y
Yibing Liu 已提交
111 112
            beam_size=args.beam_size,
            cutoff_prob=args.cutoff_prob,
113
            vocab_list=data_generator.vocab_list,
114
            language_model_path=args.lang_model_path,
115
            num_processes=args.num_proc_bsearch)
116 117 118 119
        wer_sum, num_ins = 0.0, 0
        for target, result in zip(target_transcripts, result_transcripts):
            wer_sum += wer(target, result)
            num_ins += 1
120
        print("alpha = %f\tbeta = %f\tWER = %f" %
121
              (alpha, beta, wer_sum / num_ins))
122 123 124


def main():
125
    print_arguments(args)
126
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
127 128 129 130 131
    tune()


if __name__ == '__main__':
    main()