rescore RTF

rescore RTF

python版本

见10.22.24.2:/home/yelong/data/wenet/examples/aishell/s0/recognize_lm.py

注意(花哥教):rescore lm是累计n-best的时间,am是一次的时间(一次出来n-best)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
from __future__ import print_function
import time
import argparse
import copy
import logging
import os
import sys

import torch
import yaml
from torch.utils.data import DataLoader

from wenet.dataset.dataset import Dataset
from wenet.transformer.asr_model import init_asr_model
from wenet.utils.checkpoint import load_checkpoint
from wenet.utils.file_utils import read_symbol_table, read_non_lang_symbols
from wenet.utils.config import override_config
import sentencepiece as spm
import torch.nn.functional as F
torch.set_num_threads(1)
def get_args():
parser = argparse.ArgumentParser(description='recognize with your model')
parser.add_argument('--config', default='exp/seewo/conformer/train.yaml', help='config file')
parser.add_argument('--test_data', default='data/xueyuan/data.list1', help='test data file')
parser.add_argument('--data_type',
default='raw',
choices=['raw', 'shard'],
help='train and cv data type')
parser.add_argument('--gpu',
type=int,
default=-1,
help='gpu id for this rank, -1 for cpu')
parser.add_argument('--checkpoint', default='exp/seewo/conformer/77.pt', help='checkpoint model')
parser.add_argument('--dict', default='exp/seewo/conformer/words.txt', help='dict file')
# parser.add_argument('--dict', default='data/dict_bpe/lang_char.txt.bpe_100_eng600_chi7200_all7800', help='dict file')
# parser.add_argument('--dict', default='exp/140-models/lang_char.txt', help='dict file')
# parser.add_argument('--symbol_table_old', default='exp/140-models/lang_char.txt', help='dict file')
parser.add_argument("--non_lang_syms",
help="non-linguistic symbol file. One symbol per line.")
parser.add_argument('--beam_size',
type=int,
default=10,
help='beam size for search')
parser.add_argument('--penalty',
type=float,
default=0.0,
help='length penalty')
parser.add_argument('--result_file', default='exp/seewo/conformer/test_xueyuan/text', help='asr result file')
parser.add_argument('--batch_size',
type=int,
default=1,
help='asr result file')
parser.add_argument('--mode',
choices=[
'attention', 'ctc_greedy_search',
'ctc_prefix_beam_search', 'attention_rescoring'
],
default='ctc_prefix_beam_search',
help='decoding mode')
parser.add_argument('--ctc_weight',
type=float,
default=0.5,
help='ctc weight for attention rescoring decode mode')
parser.add_argument('--decoding_chunk_size',
type=int,
default=-1,
help='''decoding chunk size,
<0: for decoding, use full chunk.
>0: for decoding, use fixed chunk size as set.
0: used for training, it's prohibited here''')
parser.add_argument('--num_decoding_left_chunks',
type=int,
default=-1,
help='number of left chunks for decoding')
parser.add_argument('--simulate_streaming',
action='store_true',
help='simulate streaming inference')
parser.add_argument('--reverse_weight',
type=float,
default=0.0,
help='''right to left weight for attention rescoring
decode mode''')
parser.add_argument('--bpe_model',
default='data/lang_char/train_unigram1000.model',
type=str,
help='bpe model for english part')
parser.add_argument('--override_config',
action='append',
default=[],
help="override yaml config")
parser.add_argument('--connect_symbol',
default='',
type=str,
help='used to connect the output characters')

args = parser.parse_args()
print(args)
return args


def main():
args = get_args()
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s')
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)

if args.mode in ['ctc_prefix_beam_search', 'attention_rescoring'
] and args.batch_size > 1:
logging.fatal(
'decoding mode {} must be running with batch_size == 1'.format(
args.mode))
sys.exit(1)

with open(args.config, 'r') as fin:
configs = yaml.load(fin, Loader=yaml.FullLoader)
if len(args.override_config) > 0:
configs = override_config(configs, args.override_config)

symbol_table = read_symbol_table(args.dict)
symbol_table_old = read_symbol_table(args.symbol_table_old if 'symbol_table_old' in args else args.dict) # --yl
configs['output_dim'] = len(symbol_table) # --yl
test_conf = copy.deepcopy(configs['dataset_conf'])

test_conf['filter_conf']['max_length'] = 102400
test_conf['filter_conf']['min_length'] = 0
test_conf['filter_conf']['token_max_length'] = 102400
test_conf['filter_conf']['token_min_length'] = 0
test_conf['filter_conf']['max_output_input_ratio'] = 102400
test_conf['filter_conf']['min_output_input_ratio'] = 0
test_conf['speed_perturb'] = False
test_conf['spec_aug'] = False
test_conf['spec_sub'] = False
test_conf['shuffle'] = False
test_conf['sort'] = False
if 'fbank_conf' in test_conf:
test_conf['fbank_conf']['dither'] = 0.0
elif 'mfcc_conf' in test_conf:
test_conf['mfcc_conf']['dither'] = 0.0
test_conf['batch_conf']['batch_type'] = "static"
test_conf['batch_conf']['batch_size'] = args.batch_size
non_lang_syms = read_non_lang_symbols(args.non_lang_syms)

test_dataset = Dataset(args.data_type,
args.test_data,
symbol_table,
test_conf,
args.bpe_model,
non_lang_syms,
partition=False)

test_data_loader = DataLoader(test_dataset, batch_size=None, num_workers=1)

# Init asr model from configs
model = init_asr_model(configs)

# Load dict
char_dict = {v: k for k, v in symbol_table.items()}
eos = len(char_dict) - 1

load_checkpoint(model, args.checkpoint, symbol_table, symbol_table_old)
use_cuda = args.gpu >= 0 and torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
model = model.to(device)

model.eval()
from transformers import BertTokenizer,BertForMaskedLM
path_to_TAL_EduBERT = "/home/yelong/data/edu-bert/models/TAL-EduBERT"
lm_tokenizer = BertTokenizer.from_pretrained(path_to_TAL_EduBERT)
lm_model = BertForMaskedLM.from_pretrained(path_to_TAL_EduBERT)
lm_model.eval()

sp = spm.SentencePieceProcessor()
sp.Load('data/lang_char/train_unigram100.model')
all_dura_am, all_dura_lm, wav_dura = 0, 0, 0
with torch.no_grad(), open(args.result_file, 'w') as fout:
for batch_idx, batch in enumerate(test_data_loader):
keys, feats, target, feats_lengths, target_lengths = batch
feats = feats.to(device)
target = target.to(device)
feats_lengths = feats_lengths.to(device)
target_lengths = target_lengths.to(device)
if args.mode == 'attention':
hyps, _ = model.recognize(
feats,
feats_lengths,
beam_size=args.beam_size,
decoding_chunk_size=args.decoding_chunk_size,
num_decoding_left_chunks=args.num_decoding_left_chunks,
simulate_streaming=args.simulate_streaming)
hyps = [hyp.tolist() for hyp in hyps]
elif args.mode == 'ctc_greedy_search':
hyps, _ = model.ctc_greedy_search(
feats,
feats_lengths,
decoding_chunk_size=args.decoding_chunk_size,
num_decoding_left_chunks=args.num_decoding_left_chunks,
simulate_streaming=args.simulate_streaming)
# ctc_prefix_beam_search and attention_rescoring only return one
# result in List[int], change it to List[List[int]] for compatible
# with other batch decoding mode
elif args.mode == 'ctc_prefix_beam_search':
assert (feats.size(0) == 1)
# hyp, _ = model.ctc_prefix_beam_search(
start_time_am = time.time()
hyp = model.ctc_prefix_beam_search(
feats,
feats_lengths,
args.beam_size,
decoding_chunk_size=args.decoding_chunk_size,
num_decoding_left_chunks=args.num_decoding_left_chunks,
simulate_streaming=args.simulate_streaming)
hyps = hyp
end_time_am = time.time()
# hyps = [hyp]
elif args.mode == 'attention_rescoring':
assert (feats.size(0) == 1)
hyp, _ = model.attention_rescoring(
feats,
feats_lengths,
args.beam_size,
decoding_chunk_size=args.decoding_chunk_size,
num_decoding_left_chunks=args.num_decoding_left_chunks,
ctc_weight=args.ctc_weight,
simulate_streaming=args.simulate_streaming,
reverse_weight=args.reverse_weight)
hyps = [hyp]
dura_am = end_time_am - start_time_am
all_dura_am += dura_am
wav_dura += feats_lengths.item()
dura_lm = 0
for j in range(len(hyp)): #十条
content = []
for w in hyps[j][0]:
if w == eos:
break
content.append(char_dict[w])
text = sp.DecodePieces([args.connect_symbol.join(content)]).replace("▁"," ").lower()
start_time_lm = time.time()
lm_inputs_token = lm_tokenizer(text, return_tensors="pt", add_special_tokens=False)
outputs = lm_model(**lm_inputs_token).logits
# Perplexity
outputs = F.softmax(outputs[0], dim=-1)
outputs = torch.log(outputs)
logit = 0
for i in range(len(outputs)):
logit = logit + outputs[i][lm_inputs_token['input_ids'][0][i]].item()
dura_lm += time.time() - start_time_lm
if j == len(hyp) -1 :
all_dura_lm += dura_lm
logging.info('{} {} {:.5} {:.5} {:.5} {:.5}'.format(keys[0], args.connect_symbol.join(content), str(100*dura_am/feats_lengths.item()), str(100*dura_lm/feats_lengths.item()), str(100*(dura_am + dura_lm)/feats_lengths.item()), str(logit)))
else:
logging.info('{} {}'.format(keys[0], args.connect_symbol.join(content)))
# logging.info('{} {} {:.4} {:.4} {:.4} {:.4}'.format(keys[0], args.connect_symbol.join(content), str(dura_am), str(dura_lm), str(dura_am + dura_lm), str(logit)))
fout.write('{} {}\n'.format(keys[0], args.connect_symbol.join(content)))
logging.info('{:.5} {:.5} {:.5}'.format(str(100*all_dura_am/wav_dura), str(100*all_dura_lm/wav_dura), str(100*(all_dura_am+all_dura_lm)/wav_dura)))

if __name__ == '__main__':
main()