File size: 11,190 Bytes
0b3b2a4 | 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | #!/usr/bin/env python3
"""
eval_model.py
Evaluate a .nemo ASR model on a manifest (batch + streaming WER).
Usage:
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json --gpu 0
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json --no-streaming
Manifest format (one JSON object per line):
{"audio_filepath": "/abs/path/utt.wav", "text": "reference transcript"}
Only `audio_filepath` and `text` are read; other keys (e.g. `duration`) are ignored.
Note:
WER here uses Whisper's BasicMultilingualTextNormalizer from the
Open ASR Leaderboard repo, matching the paper pipeline.
Requirements:
pip install nemo_toolkit[asr] soundfile numpy
"""
import argparse
import json
import os
import sys
import numpy as np
import torch
# Use Whisper's BasicMultilingualTextNormalizer for consistency with paper runs.
try:
from normalizer import BasicMultilingualTextNormalizer
_ml_normalizer = BasicMultilingualTextNormalizer()
except ImportError:
print(
"ERROR: could not import BasicMultilingualTextNormalizer. "
"This script requires Whisper's BasicMultilingualTextNormalizer, "
"shipped in the Open ASR Leaderboard repo. "
"Clone https://github.com/huggingface/open_asr_leaderboard and add it "
"to PYTHONPATH (or set OPEN_ASR_LB_ROOT).",
file=sys.stderr,
)
raise SystemExit(1)
def normalize_text(text):
return _ml_normalizer(text)
def simple_wer(ref_words, hyp_words):
n, m = len(ref_words), len(hyp_words)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1): dp[i][0] = i
for j in range(m + 1): dp[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[n][m]
@torch.no_grad()
def evaluate_batch(model, manifest_path, device):
import soundfile as sf
model.eval()
samples = []
with open(manifest_path) as f:
for line in f:
samples.append(json.loads(line))
total_edits, total_words = 0, 0
errors = 0
batch_size = 16
examples = []
for start in range(0, len(samples), batch_size):
batch_samples = samples[start:start + batch_size]
try:
audios = []
for s in batch_samples:
audio, sr = sf.read(s["audio_filepath"], dtype="float32")
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
audios.append(torch.FloatTensor(audio))
audio_lens = torch.LongTensor([len(a) for a in audios])
max_len = audio_lens.max().item()
padded = torch.zeros(len(audios), max_len)
for i, a in enumerate(audios):
padded[i, :len(a)] = a
padded = padded.to(device)
audio_lens = audio_lens.to(device)
mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
if isinstance(best_hyps, tuple):
best_hyps = best_hyps[0]
for s, hyp in zip(batch_samples, best_hyps):
if hasattr(hyp, 'text') and hyp.text:
pred = hyp.text
elif hasattr(hyp, 'y_sequence'):
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
pred = model.tokenizer.ids_to_text(tids) if tids else ""
else:
pred = str(hyp)
ref_n = normalize_text(s["text"])
pred_n = normalize_text(pred)
ref_words = ref_n.split()
pred_words = pred_n.split()
if ref_words:
total_edits += simple_wer(ref_words, pred_words)
total_words += len(ref_words)
if len(examples) < 10:
examples.append((s["text"][:60], pred[:60]))
except Exception as e:
errors += 1
if errors <= 3:
print(f" [batch eval error] {type(e).__name__}: {e}")
wer_score = total_edits / max(total_words, 1) * 100
print(f"\n {'Reference':<60} | {'Prediction':<60}")
print(f" {'-'*60} | {'-'*60}")
for ref, pred in examples:
print(f" {ref:<60} | {pred:<60}")
if errors:
print(f" ({errors} batch eval errors)")
return wer_score, total_edits, total_words
@torch.no_grad()
def evaluate_streaming(model, manifest_path, device):
import soundfile as sf
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
model.eval()
right_context = 13
chunk_frames = 1 + right_context
model.encoder.setup_streaming_params(
chunk_size=chunk_frames,
shift_size=chunk_frames,
left_chunks=70 // max(chunk_frames, 1),
)
samples = []
with open(manifest_path) as f:
for line in f:
samples.append(json.loads(line))
total_edits, total_words = 0, 0
examples = []
errors = 0
for s in samples:
try:
audio, sr = sf.read(s["audio_filepath"], dtype="float32")
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
buffer = CacheAwareStreamingAudioBuffer(model=model)
buffer.append_audio(audio)
cache_last_channel, cache_last_time, cache_last_channel_len = \
model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
previous_hypotheses = None
pred = ""
for chunk_audio, chunk_len in buffer:
if chunk_audio is None:
break
result = model.conformer_stream_step(
processed_signal=chunk_audio,
processed_signal_length=chunk_len,
cache_last_channel=cache_last_channel,
cache_last_time=cache_last_time,
cache_last_channel_len=cache_last_channel_len,
previous_hypotheses=previous_hypotheses,
return_transcription=True,
)
if isinstance(result, tuple) and len(result) >= 6:
cache_last_channel = result[2]
cache_last_time = result[3]
cache_last_channel_len = result[4]
previous_hypotheses = result[5]
if result[5] and len(result[5]) > 0:
hyp = result[5][0]
new_text = ""
if hasattr(hyp, 'text') and hyp.text:
new_text = hyp.text
elif hasattr(hyp, 'y_sequence'):
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
if tids:
new_text = model.tokenizer.ids_to_text(tids)
if new_text and len(new_text) > len(pred):
pred = new_text
ref_n = normalize_text(s["text"])
pred_n = normalize_text(pred)
ref_words = ref_n.split()
pred_words = pred_n.split()
if ref_words:
total_edits += simple_wer(ref_words, pred_words)
total_words += len(ref_words)
if len(examples) < 10:
examples.append((s["text"][:60], pred[:60]))
except Exception as e:
errors += 1
if errors <= 3:
print(f" [streaming eval error] {type(e).__name__}: {e}")
wer_score = total_edits / max(total_words, 1) * 100
print(f"\n {'Reference':<60} | {'Prediction':<60}")
print(f" {'-'*60} | {'-'*60}")
for ref, pred in examples:
print(f" {ref:<60} | {pred:<60}")
if errors:
print(f" ({errors} samples failed)")
return wer_score, total_edits, total_words
def main():
parser = argparse.ArgumentParser(description="Evaluate NeMo ASR model")
parser.add_argument("--model", type=str, required=True, help="Path to .nemo model")
parser.add_argument("--manifest", type=str, required=True,
help="Path to evaluation manifest (JSONL)")
parser.add_argument("--gpu", type=int, default=0, help="GPU index")
parser.add_argument("--no-streaming", action="store_true", help="Skip streaming eval")
args = parser.parse_args()
device = torch.device(f"cuda:{args.gpu}")
torch.cuda.set_device(args.gpu)
import nemo.collections.asr as nemo_asr
from nemo.core.classes.common import typecheck
typecheck.set_typecheck_enabled(False)
print(f"\n{'='*65}")
print(f" Model: {args.model}")
print(f" Manifest: {args.manifest}")
print(f" GPU: {args.gpu}")
print(f"{'='*65}")
print(f"\n Loading model...")
model = nemo_asr.models.ASRModel.restore_from(args.model, map_location=device)
model = model.to(device)
model.eval()
from omegaconf import open_dict
with open_dict(model.cfg):
model.cfg.decoding.greedy.use_cuda_graph_decoder = False
model.change_decoding_strategy(model.cfg.decoding)
print(f" Vocab: {model.tokenizer.vocab_size} tokens")
print(f" Params: {sum(p.numel() for p in model.parameters()) / 1e6:.1f}M")
# Count samples
with open(args.manifest) as f:
n_samples = sum(1 for _ in f)
print(f" Samples: {n_samples}")
# Batch eval
print(f"\n{'='*65}")
print(f" Batch Evaluation")
print(f"{'='*65}")
batch_wer, batch_edits, batch_words = evaluate_batch(model, args.manifest, device)
print(f"\n Batch WER: {batch_wer:.2f}% ({batch_edits}/{batch_words})")
# Streaming eval
if not args.no_streaming:
print(f"\n{'='*65}")
print(f" Streaming Evaluation")
print(f"{'='*65}")
stream_wer, stream_edits, stream_words = evaluate_streaming(model, args.manifest, device)
print(f"\n Streaming WER: {stream_wer:.2f}% ({stream_edits}/{stream_words})")
# Summary
print(f"\n{'='*65}")
print(f" Summary")
print(f"{'='*65}")
print(f" Model: {os.path.basename(args.model)}")
print(f" Manifest: {os.path.basename(args.manifest)}")
print(f" Batch WER: {batch_wer:.2f}%")
if not args.no_streaming:
print(f" Streaming WER: {stream_wer:.2f}%")
print(f"{'='*65}")
if __name__ == "__main__":
main()
|