#!/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()