tune.py 9.1 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 sys
7
import os
8
import numpy as np
9
import argparse
X
Xinghai Sun 已提交
10
import functools
11 12
import gzip
import logging
Y
Yibing Liu 已提交
13
import paddle.v2 as paddle
14
import _init_paths
Y
Yibing Liu 已提交
15
from data_utils.data import DataGenerator
16 17 18
from decoders.swig_wrapper import Scorer
from decoders.swig_wrapper import ctc_beam_search_decoder_batch
from model_utils.model import deep_speech_v2_network
19
from utils.error_rate import wer, cer
20
from utils.utility import add_arguments, print_arguments
21

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

73

74 75 76
logging.basicConfig(
    format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s')

77
def tune():
78
    """Tune parameters alpha and beta incrementally."""
79 80 81 82
    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!")
83 84

    data_generator = DataGenerator(
85 86
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
Y
Yibing Liu 已提交
87
        augmentation_config='{}',
88
        specgram_type=args.specgram_type,
89
        num_threads=1)
90 91

    audio_data = paddle.layer.data(
Y
Yibing Liu 已提交
92 93
        name="audio_spectrogram",
        type=paddle.data_type.dense_array(161 * 161))
94
    text_data = paddle.layer.data(
Y
Yibing Liu 已提交
95 96
        name="transcript_text",
        type=paddle.data_type.integer_value_sequence(data_generator.vocab_size))
97 98

    output_probs, _ = deep_speech_v2_network(
Y
Yibing Liu 已提交
99 100 101 102 103 104 105 106
        audio_data=audio_data,
        text_data=text_data,
        dict_size=data_generator.vocab_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
        rnn_size=args.rnn_layer_size,
        use_gru=args.use_gru,
        share_rnn_weights=args.share_rnn_weights)
107

Y
Yibing Liu 已提交
108
    batch_reader = data_generator.batch_reader_creator(
109
        manifest_path=args.tune_manifest,
110
        batch_size=args.batch_size,
Y
Yibing Liu 已提交
111 112
        sortagrad=False,
        shuffle_method=None)
113

114
    # load parameters
115 116
    if not os.path.isfile(args.model_path):
        raise IOError("Invaid model path: %s" % args.model_path)
117 118 119 120 121
    parameters = paddle.parameters.Parameters.from_tar(
        gzip.open(args.model_path))

    inferer = paddle.inference.Inference(
        output_layer=output_probs, parameters=parameters)
122 123 124
    # decoders only accept string encoded in utf-8
    vocab_list = [chars.encode("utf-8") for chars in data_generator.vocab_list]

125 126 127 128 129
    # init logger
    logger = logging.getLogger("")
    logger.setLevel(level=logging.INFO)
    # init external scorer
    logger.info("begin to initialize the external scorer for tuning")
130 131
    if not os.path.isfile(args.lang_model_path):
        raise IOError("Invaid language model path: %s" % args.lang_model_path)
132 133 134 135 136 137 138 139 140 141 142
    ext_scorer = Scorer(
        alpha=args.alpha_from,
        beta=args.beta_from,
        model_path=args.lang_model_path,
        vocabulary=vocab_list)
    logger.info("language model: "
                "is_character_based = %d," % ext_scorer.is_character_based() +
                " max_order = %d," % ext_scorer.get_max_order() +
                " dict_size = %d" % ext_scorer.get_dict_size())
    logger.info("end initializing scorer. Start tuning ...")

143
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
144 145 146 147 148 149
    # 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]

150 151 152 153 154 155 156
    err_sum = [0.0 for i in xrange(len(params_grid))]
    err_ave = [0.0 for i in xrange(len(params_grid))]
    num_ins, cur_batch = 0, 0
    ## incremental tuning parameters over multiple batches
    for infer_data in batch_reader():
        if (args.num_batches >= 0) and (cur_batch >= args.num_batches):
            break
157 158 159 160 161 162 163
        infer_results = inferer.infer(input=infer_data)

        num_steps = len(infer_results) // len(infer_data)
        probs_split = [
            infer_results[i * num_steps:(i + 1) * num_steps]
            for i in xrange(len(infer_data))
        ]
164 165 166 167 168 169 170 171 172

        target_transcripts = [
            ''.join([data_generator.vocab_list[token] for token in transcript])
            for _, transcript in infer_data
        ]

        num_ins += len(target_transcripts)
        # grid search
        for index, (alpha, beta) in enumerate(params_grid):
173 174 175
            # reset alpha & beta
            ext_scorer.reset_params(alpha, beta)
            beam_search_results = ctc_beam_search_decoder_batch(
Y
Yibing Liu 已提交
176 177 178 179 180 181 182
                probs_split=probs_split,
                vocabulary=vocab_list,
                beam_size=args.beam_size,
                num_processes=args.num_proc_bsearch,
                cutoff_prob=args.cutoff_prob,
                cutoff_top_n=args.cutoff_top_n,
                ext_scoring_func=ext_scorer, )
183 184

            result_transcripts = [res[0][1] for res in beam_search_results]
185 186 187
            for target, result in zip(target_transcripts, result_transcripts):
                err_sum[index] += error_rate_func(target, result)
            err_ave[index] = err_sum[index] / num_ins
188
            if index % 2 == 0:
189 190 191
                sys.stdout.write('.')
                sys.stdout.flush()

Y
Yibing Liu 已提交
192
        # output on-line tuning result at the end of current batch
193 194
        err_ave_min = min(err_ave)
        min_index = err_ave.index(err_ave_min)
195 196 197 198 199
        print("\nBatch %d [%d/?], current opt (alpha, beta) = (%s, %s), "
              " min [%s] = %f" %(cur_batch, num_ins,
              "%.3f" % params_grid[min_index][0],
              "%.3f" % params_grid[min_index][1],
              args.error_rate_type, err_ave_min))
200 201
        cur_batch += 1

Y
Yibing Liu 已提交
202
    # output WER/CER at every (alpha, beta)
203
    print("\nFinal %s:\n" % args.error_rate_type)
204
    for index in xrange(len(params_grid)):
205 206 207
        print("(alpha, beta) = (%s, %s), [%s] = %f"
             % ("%.3f" % params_grid[index][0], "%.3f" % params_grid[index][1],
             args.error_rate_type, err_ave[index]))
208 209 210

    err_ave_min = min(err_ave)
    min_index = err_ave.index(err_ave_min)
211 212 213
    print("\nFinish tuning on %d batches, final opt (alpha, beta) = (%s, %s)"
            % (args.num_batches, "%.3f" % params_grid[min_index][0],
              "%.3f" % params_grid[min_index][1]))
214

215
    logger.info("finish tuning")
216

217

218
def main():
219
    print_arguments(args)
220 221 222
    paddle.init(use_gpu=args.use_gpu,
                rnn_use_batch=True,
                trainer_count=args.trainer_count)
223 224 225 226 227
    tune()


if __name__ == '__main__':
    main()