Upload 9 files
Browse files- README.md +16 -0
- eval_model.py +307 -0
- onnx_eval/eval_fleurs_onnx.py +255 -0
- onnx_eval/run_fleurs_eval.sh +75 -0
- paper/aggregate.py +687 -0
- paper/wer_results.json +0 -0
- requirements.txt +25 -0
- train_multilingual_nemotron.py +1029 -0
- train_single_lang.py +1858 -0
README.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code and Artifacts
|
| 2 |
+
|
| 3 |
+
This repository contains the code and supporting artifacts that accompany a paper
|
| 4 |
+
currently under double-blind peer review.
|
| 5 |
+
|
| 6 |
+
All documentation — the training and decoding recipe, dataset details, and reproduction steps — is provided in the supplementary material of the paper.
|
| 7 |
+
|
| 8 |
+
## Anonymity notice
|
| 9 |
+
|
| 10 |
+
To preserve double-blind review, the paper title, author names, and affiliations are
|
| 11 |
+
withheld, and identifying paths and identifiers have been removed. Please do not
|
| 12 |
+
attempt to de-anonymize the authors.
|
| 13 |
+
|
| 14 |
+
## License
|
| 15 |
+
|
| 16 |
+
Released under the MIT License.
|
eval_model.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
eval_model.py
|
| 4 |
+
|
| 5 |
+
Evaluate a .nemo ASR model on a manifest (batch + streaming WER).
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json
|
| 9 |
+
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json --gpu 0
|
| 10 |
+
python eval_model.py --model /path/to/best_model.nemo --manifest /path/to/test_manifest.json --no-streaming
|
| 11 |
+
|
| 12 |
+
Manifest format (one JSON object per line):
|
| 13 |
+
{"audio_filepath": "/abs/path/utt.wav", "text": "reference transcript"}
|
| 14 |
+
Only `audio_filepath` and `text` are read; other keys (e.g. `duration`) are ignored.
|
| 15 |
+
|
| 16 |
+
Note:
|
| 17 |
+
WER here uses Whisper's BasicMultilingualTextNormalizer from the
|
| 18 |
+
Open ASR Leaderboard repo, matching the paper pipeline.
|
| 19 |
+
|
| 20 |
+
Requirements:
|
| 21 |
+
pip install nemo_toolkit[asr] soundfile numpy
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Use Whisper's BasicMultilingualTextNormalizer for consistency with paper runs.
|
| 34 |
+
try:
|
| 35 |
+
from normalizer import BasicMultilingualTextNormalizer
|
| 36 |
+
_ml_normalizer = BasicMultilingualTextNormalizer()
|
| 37 |
+
except ImportError:
|
| 38 |
+
print(
|
| 39 |
+
"ERROR: could not import BasicMultilingualTextNormalizer. "
|
| 40 |
+
"This script requires Whisper's BasicMultilingualTextNormalizer, "
|
| 41 |
+
"shipped in the Open ASR Leaderboard repo. "
|
| 42 |
+
"Clone https://github.com/huggingface/open_asr_leaderboard and add it "
|
| 43 |
+
"to PYTHONPATH (or set OPEN_ASR_LB_ROOT).",
|
| 44 |
+
file=sys.stderr,
|
| 45 |
+
)
|
| 46 |
+
raise SystemExit(1)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def normalize_text(text):
|
| 50 |
+
return _ml_normalizer(text)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def simple_wer(ref_words, hyp_words):
|
| 54 |
+
n, m = len(ref_words), len(hyp_words)
|
| 55 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 56 |
+
for i in range(n + 1): dp[i][0] = i
|
| 57 |
+
for j in range(m + 1): dp[0][j] = j
|
| 58 |
+
for i in range(1, n + 1):
|
| 59 |
+
for j in range(1, m + 1):
|
| 60 |
+
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
|
| 61 |
+
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
|
| 62 |
+
return dp[n][m]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@torch.no_grad()
|
| 66 |
+
def evaluate_batch(model, manifest_path, device):
|
| 67 |
+
import soundfile as sf
|
| 68 |
+
model.eval()
|
| 69 |
+
|
| 70 |
+
samples = []
|
| 71 |
+
with open(manifest_path) as f:
|
| 72 |
+
for line in f:
|
| 73 |
+
samples.append(json.loads(line))
|
| 74 |
+
|
| 75 |
+
total_edits, total_words = 0, 0
|
| 76 |
+
errors = 0
|
| 77 |
+
batch_size = 16
|
| 78 |
+
examples = []
|
| 79 |
+
|
| 80 |
+
for start in range(0, len(samples), batch_size):
|
| 81 |
+
batch_samples = samples[start:start + batch_size]
|
| 82 |
+
try:
|
| 83 |
+
audios = []
|
| 84 |
+
for s in batch_samples:
|
| 85 |
+
audio, sr = sf.read(s["audio_filepath"], dtype="float32")
|
| 86 |
+
if len(audio.shape) > 1:
|
| 87 |
+
audio = audio.mean(axis=1)
|
| 88 |
+
audios.append(torch.FloatTensor(audio))
|
| 89 |
+
|
| 90 |
+
audio_lens = torch.LongTensor([len(a) for a in audios])
|
| 91 |
+
max_len = audio_lens.max().item()
|
| 92 |
+
padded = torch.zeros(len(audios), max_len)
|
| 93 |
+
for i, a in enumerate(audios):
|
| 94 |
+
padded[i, :len(a)] = a
|
| 95 |
+
|
| 96 |
+
padded = padded.to(device)
|
| 97 |
+
audio_lens = audio_lens.to(device)
|
| 98 |
+
|
| 99 |
+
mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
|
| 100 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 101 |
+
|
| 102 |
+
best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
|
| 103 |
+
if isinstance(best_hyps, tuple):
|
| 104 |
+
best_hyps = best_hyps[0]
|
| 105 |
+
|
| 106 |
+
for s, hyp in zip(batch_samples, best_hyps):
|
| 107 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 108 |
+
pred = hyp.text
|
| 109 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 110 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 111 |
+
pred = model.tokenizer.ids_to_text(tids) if tids else ""
|
| 112 |
+
else:
|
| 113 |
+
pred = str(hyp)
|
| 114 |
+
|
| 115 |
+
ref_n = normalize_text(s["text"])
|
| 116 |
+
pred_n = normalize_text(pred)
|
| 117 |
+
ref_words = ref_n.split()
|
| 118 |
+
pred_words = pred_n.split()
|
| 119 |
+
if ref_words:
|
| 120 |
+
total_edits += simple_wer(ref_words, pred_words)
|
| 121 |
+
total_words += len(ref_words)
|
| 122 |
+
|
| 123 |
+
if len(examples) < 10:
|
| 124 |
+
examples.append((s["text"][:60], pred[:60]))
|
| 125 |
+
|
| 126 |
+
except Exception as e:
|
| 127 |
+
errors += 1
|
| 128 |
+
if errors <= 3:
|
| 129 |
+
print(f" [batch eval error] {type(e).__name__}: {e}")
|
| 130 |
+
|
| 131 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 132 |
+
|
| 133 |
+
print(f"\n {'Reference':<60} | {'Prediction':<60}")
|
| 134 |
+
print(f" {'-'*60} | {'-'*60}")
|
| 135 |
+
for ref, pred in examples:
|
| 136 |
+
print(f" {ref:<60} | {pred:<60}")
|
| 137 |
+
if errors:
|
| 138 |
+
print(f" ({errors} batch eval errors)")
|
| 139 |
+
|
| 140 |
+
return wer_score, total_edits, total_words
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@torch.no_grad()
|
| 144 |
+
def evaluate_streaming(model, manifest_path, device):
|
| 145 |
+
import soundfile as sf
|
| 146 |
+
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
|
| 147 |
+
|
| 148 |
+
model.eval()
|
| 149 |
+
|
| 150 |
+
right_context = 13
|
| 151 |
+
chunk_frames = 1 + right_context
|
| 152 |
+
model.encoder.setup_streaming_params(
|
| 153 |
+
chunk_size=chunk_frames,
|
| 154 |
+
shift_size=chunk_frames,
|
| 155 |
+
left_chunks=70 // max(chunk_frames, 1),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
samples = []
|
| 159 |
+
with open(manifest_path) as f:
|
| 160 |
+
for line in f:
|
| 161 |
+
samples.append(json.loads(line))
|
| 162 |
+
|
| 163 |
+
total_edits, total_words = 0, 0
|
| 164 |
+
examples = []
|
| 165 |
+
errors = 0
|
| 166 |
+
|
| 167 |
+
for s in samples:
|
| 168 |
+
try:
|
| 169 |
+
audio, sr = sf.read(s["audio_filepath"], dtype="float32")
|
| 170 |
+
if len(audio.shape) > 1:
|
| 171 |
+
audio = audio.mean(axis=1)
|
| 172 |
+
|
| 173 |
+
buffer = CacheAwareStreamingAudioBuffer(model=model)
|
| 174 |
+
buffer.append_audio(audio)
|
| 175 |
+
|
| 176 |
+
cache_last_channel, cache_last_time, cache_last_channel_len = \
|
| 177 |
+
model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
|
| 178 |
+
previous_hypotheses = None
|
| 179 |
+
pred = ""
|
| 180 |
+
|
| 181 |
+
for chunk_audio, chunk_len in buffer:
|
| 182 |
+
if chunk_audio is None:
|
| 183 |
+
break
|
| 184 |
+
result = model.conformer_stream_step(
|
| 185 |
+
processed_signal=chunk_audio,
|
| 186 |
+
processed_signal_length=chunk_len,
|
| 187 |
+
cache_last_channel=cache_last_channel,
|
| 188 |
+
cache_last_time=cache_last_time,
|
| 189 |
+
cache_last_channel_len=cache_last_channel_len,
|
| 190 |
+
previous_hypotheses=previous_hypotheses,
|
| 191 |
+
return_transcription=True,
|
| 192 |
+
)
|
| 193 |
+
if isinstance(result, tuple) and len(result) >= 6:
|
| 194 |
+
cache_last_channel = result[2]
|
| 195 |
+
cache_last_time = result[3]
|
| 196 |
+
cache_last_channel_len = result[4]
|
| 197 |
+
previous_hypotheses = result[5]
|
| 198 |
+
if result[5] and len(result[5]) > 0:
|
| 199 |
+
hyp = result[5][0]
|
| 200 |
+
new_text = ""
|
| 201 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 202 |
+
new_text = hyp.text
|
| 203 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 204 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 205 |
+
if tids:
|
| 206 |
+
new_text = model.tokenizer.ids_to_text(tids)
|
| 207 |
+
if new_text and len(new_text) > len(pred):
|
| 208 |
+
pred = new_text
|
| 209 |
+
|
| 210 |
+
ref_n = normalize_text(s["text"])
|
| 211 |
+
pred_n = normalize_text(pred)
|
| 212 |
+
ref_words = ref_n.split()
|
| 213 |
+
pred_words = pred_n.split()
|
| 214 |
+
|
| 215 |
+
if ref_words:
|
| 216 |
+
total_edits += simple_wer(ref_words, pred_words)
|
| 217 |
+
total_words += len(ref_words)
|
| 218 |
+
|
| 219 |
+
if len(examples) < 10:
|
| 220 |
+
examples.append((s["text"][:60], pred[:60]))
|
| 221 |
+
|
| 222 |
+
except Exception as e:
|
| 223 |
+
errors += 1
|
| 224 |
+
if errors <= 3:
|
| 225 |
+
print(f" [streaming eval error] {type(e).__name__}: {e}")
|
| 226 |
+
|
| 227 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 228 |
+
|
| 229 |
+
print(f"\n {'Reference':<60} | {'Prediction':<60}")
|
| 230 |
+
print(f" {'-'*60} | {'-'*60}")
|
| 231 |
+
for ref, pred in examples:
|
| 232 |
+
print(f" {ref:<60} | {pred:<60}")
|
| 233 |
+
if errors:
|
| 234 |
+
print(f" ({errors} samples failed)")
|
| 235 |
+
|
| 236 |
+
return wer_score, total_edits, total_words
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def main():
|
| 240 |
+
parser = argparse.ArgumentParser(description="Evaluate NeMo ASR model")
|
| 241 |
+
parser.add_argument("--model", type=str, required=True, help="Path to .nemo model")
|
| 242 |
+
parser.add_argument("--manifest", type=str, required=True,
|
| 243 |
+
help="Path to evaluation manifest (JSONL)")
|
| 244 |
+
parser.add_argument("--gpu", type=int, default=0, help="GPU index")
|
| 245 |
+
parser.add_argument("--no-streaming", action="store_true", help="Skip streaming eval")
|
| 246 |
+
args = parser.parse_args()
|
| 247 |
+
|
| 248 |
+
device = torch.device(f"cuda:{args.gpu}")
|
| 249 |
+
torch.cuda.set_device(args.gpu)
|
| 250 |
+
|
| 251 |
+
import nemo.collections.asr as nemo_asr
|
| 252 |
+
from nemo.core.classes.common import typecheck
|
| 253 |
+
typecheck.set_typecheck_enabled(False)
|
| 254 |
+
|
| 255 |
+
print(f"\n{'='*65}")
|
| 256 |
+
print(f" Model: {args.model}")
|
| 257 |
+
print(f" Manifest: {args.manifest}")
|
| 258 |
+
print(f" GPU: {args.gpu}")
|
| 259 |
+
print(f"{'='*65}")
|
| 260 |
+
|
| 261 |
+
print(f"\n Loading model...")
|
| 262 |
+
model = nemo_asr.models.ASRModel.restore_from(args.model, map_location=device)
|
| 263 |
+
model = model.to(device)
|
| 264 |
+
model.eval()
|
| 265 |
+
|
| 266 |
+
from omegaconf import open_dict
|
| 267 |
+
with open_dict(model.cfg):
|
| 268 |
+
model.cfg.decoding.greedy.use_cuda_graph_decoder = False
|
| 269 |
+
model.change_decoding_strategy(model.cfg.decoding)
|
| 270 |
+
|
| 271 |
+
print(f" Vocab: {model.tokenizer.vocab_size} tokens")
|
| 272 |
+
print(f" Params: {sum(p.numel() for p in model.parameters()) / 1e6:.1f}M")
|
| 273 |
+
|
| 274 |
+
# Count samples
|
| 275 |
+
with open(args.manifest) as f:
|
| 276 |
+
n_samples = sum(1 for _ in f)
|
| 277 |
+
print(f" Samples: {n_samples}")
|
| 278 |
+
|
| 279 |
+
# Batch eval
|
| 280 |
+
print(f"\n{'='*65}")
|
| 281 |
+
print(f" Batch Evaluation")
|
| 282 |
+
print(f"{'='*65}")
|
| 283 |
+
batch_wer, batch_edits, batch_words = evaluate_batch(model, args.manifest, device)
|
| 284 |
+
print(f"\n Batch WER: {batch_wer:.2f}% ({batch_edits}/{batch_words})")
|
| 285 |
+
|
| 286 |
+
# Streaming eval
|
| 287 |
+
if not args.no_streaming:
|
| 288 |
+
print(f"\n{'='*65}")
|
| 289 |
+
print(f" Streaming Evaluation")
|
| 290 |
+
print(f"{'='*65}")
|
| 291 |
+
stream_wer, stream_edits, stream_words = evaluate_streaming(model, args.manifest, device)
|
| 292 |
+
print(f"\n Streaming WER: {stream_wer:.2f}% ({stream_edits}/{stream_words})")
|
| 293 |
+
|
| 294 |
+
# Summary
|
| 295 |
+
print(f"\n{'='*65}")
|
| 296 |
+
print(f" Summary")
|
| 297 |
+
print(f"{'='*65}")
|
| 298 |
+
print(f" Model: {os.path.basename(args.model)}")
|
| 299 |
+
print(f" Manifest: {os.path.basename(args.manifest)}")
|
| 300 |
+
print(f" Batch WER: {batch_wer:.2f}%")
|
| 301 |
+
if not args.no_streaming:
|
| 302 |
+
print(f" Streaming WER: {stream_wer:.2f}%")
|
| 303 |
+
print(f"{'='*65}")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
main()
|
onnx_eval/eval_fleurs_onnx.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""FLEURS WER eval for a Nemotron ONNX (onnxruntime-genai) model.
|
| 3 |
+
|
| 4 |
+
Streaming inference, per-utterance TSV + JSON summary, BasicMultilingualText
|
| 5 |
+
normalization (same normalizer as the NeMo streaming eval).
|
| 6 |
+
|
| 7 |
+
This is the per-language (monolingual) evaluator used for the INT4
|
| 8 |
+
weight-only quantization study: each ONNX export already targets a single
|
| 9 |
+
language and a single streaming-latency tier (the chunk size is baked into
|
| 10 |
+
``genai_config.json``), so no language-id / prompt override is applied.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python eval_fleurs_onnx.py \
|
| 14 |
+
--onnx_model <ONNX_ROOT>/es_500h_new_ml_1e4_int4 \
|
| 15 |
+
--lang es_419 \
|
| 16 |
+
--name es_500h_new_ml_1e4_int4 \
|
| 17 |
+
--output_dir ./results
|
| 18 |
+
|
| 19 |
+
Requires onnxruntime-genai and a model dir containing genai_config.json
|
| 20 |
+
(plus encoder.onnx / decoder.onnx / joint.onnx / tokenizer.* / etc.).
|
| 21 |
+
"""
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import re
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import onnxruntime_genai as og
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Multilingual exports may emit "<es-ES>" / "<de-DE>" tokens; strip from text.
|
| 34 |
+
# (Harmless no-op for the monolingual exports evaluated here.)
|
| 35 |
+
_LANG_TAG_RE = re.compile(r"\s*<[a-z]{2,3}(?:-[A-Za-z]{2,4})?>\s*")
|
| 36 |
+
|
| 37 |
+
# WER normalization uses the Whisper BasicMultilingualTextNormalizer
|
| 38 |
+
# packaged in the Open ASR Leaderboard repo, used unchanged:
|
| 39 |
+
# https://github.com/huggingface/open_asr_leaderboard
|
| 40 |
+
# Clone it and add the repo root to PYTHONPATH (or set OPEN_ASR_LB_ROOT).
|
| 41 |
+
_oalb = os.environ.get("OPEN_ASR_LB_ROOT")
|
| 42 |
+
if _oalb:
|
| 43 |
+
sys.path.insert(0, _oalb)
|
| 44 |
+
try:
|
| 45 |
+
from normalizer import BasicMultilingualTextNormalizer # noqa: E402
|
| 46 |
+
except ImportError as e:
|
| 47 |
+
raise RuntimeError(
|
| 48 |
+
"Could not import normalizer.BasicMultilingualTextNormalizer. "
|
| 49 |
+
"Clone https://github.com/huggingface/open_asr_leaderboard and set "
|
| 50 |
+
"OPEN_ASR_LB_ROOT=/path/to/open_asr_leaderboard."
|
| 51 |
+
) from e
|
| 52 |
+
|
| 53 |
+
_norm = BasicMultilingualTextNormalizer()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def normalize_text(t: str) -> str:
|
| 57 |
+
return _norm(t)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def compute_wer_ids(ref, hyp):
|
| 61 |
+
n, m = len(ref), len(hyp)
|
| 62 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 63 |
+
for i in range(n + 1):
|
| 64 |
+
dp[i][0] = i
|
| 65 |
+
for j in range(m + 1):
|
| 66 |
+
dp[0][j] = j
|
| 67 |
+
for i in range(1, n + 1):
|
| 68 |
+
for j in range(1, m + 1):
|
| 69 |
+
if ref[i - 1] == hyp[j - 1]:
|
| 70 |
+
dp[i][j] = dp[i - 1][j - 1]
|
| 71 |
+
else:
|
| 72 |
+
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
|
| 73 |
+
subs = dels = ins = 0
|
| 74 |
+
i, j = n, m
|
| 75 |
+
while i > 0 or j > 0:
|
| 76 |
+
if i > 0 and j > 0 and ref[i - 1] == hyp[j - 1]:
|
| 77 |
+
i -= 1; j -= 1
|
| 78 |
+
elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1:
|
| 79 |
+
subs += 1; i -= 1; j -= 1
|
| 80 |
+
elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
|
| 81 |
+
dels += 1; i -= 1
|
| 82 |
+
else:
|
| 83 |
+
ins += 1; j -= 1
|
| 84 |
+
return subs, dels, ins
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def load_fleurs(lang: str):
|
| 88 |
+
from datasets import load_dataset, Audio
|
| 89 |
+
cache = (os.environ.get("HF_DATASETS_CACHE")
|
| 90 |
+
or os.environ.get("HF_HOME"))
|
| 91 |
+
print(f" Loading FLEURS {lang} test (cache_dir={cache})")
|
| 92 |
+
ds = load_dataset("google/fleurs", lang, split="test",
|
| 93 |
+
trust_remote_code=True, cache_dir=cache)
|
| 94 |
+
ds = ds.cast_column("audio", Audio(sampling_rate=16000))
|
| 95 |
+
return ds
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def transcribe(model, params, tokenizer, sample_rate, chunk_samples, audio):
|
| 99 |
+
processor = og.StreamingProcessor(model)
|
| 100 |
+
processor.set_option("use_vad", "false")
|
| 101 |
+
gen = og.Generator(model, params)
|
| 102 |
+
tok_stream = tokenizer.create_stream()
|
| 103 |
+
|
| 104 |
+
text = ""
|
| 105 |
+
|
| 106 |
+
def _drain():
|
| 107 |
+
nonlocal text
|
| 108 |
+
while not gen.is_done():
|
| 109 |
+
gen.generate_next_token()
|
| 110 |
+
toks = gen.get_next_tokens()
|
| 111 |
+
if len(toks) > 0:
|
| 112 |
+
t = tok_stream.decode(toks[0])
|
| 113 |
+
if t:
|
| 114 |
+
t = _LANG_TAG_RE.sub("", t)
|
| 115 |
+
if t:
|
| 116 |
+
text += t
|
| 117 |
+
|
| 118 |
+
for start in range(0, len(audio), chunk_samples):
|
| 119 |
+
chunk = audio[start:start + chunk_samples].astype(np.float32)
|
| 120 |
+
inp = processor.process(chunk)
|
| 121 |
+
if inp is not None:
|
| 122 |
+
gen.set_inputs(inp)
|
| 123 |
+
_drain()
|
| 124 |
+
|
| 125 |
+
inp = processor.flush()
|
| 126 |
+
if inp is not None:
|
| 127 |
+
gen.set_inputs(inp)
|
| 128 |
+
_drain()
|
| 129 |
+
|
| 130 |
+
del gen, processor
|
| 131 |
+
return text
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def evaluate(onnx_dir: str, dataset, name: str, lang: str, max_samples=None):
|
| 135 |
+
with open(os.path.join(onnx_dir, "genai_config.json")) as f:
|
| 136 |
+
cfg = json.load(f)
|
| 137 |
+
sample_rate = cfg["model"]["sample_rate"]
|
| 138 |
+
chunk_samples = cfg["model"]["chunk_samples"]
|
| 139 |
+
|
| 140 |
+
print(f" Model: {onnx_dir}")
|
| 141 |
+
print(f" chunk_samples: {chunk_samples}")
|
| 142 |
+
model = og.Model(og.Config(onnx_dir))
|
| 143 |
+
tokenizer = og.Tokenizer(model)
|
| 144 |
+
params = og.GeneratorParams(model)
|
| 145 |
+
|
| 146 |
+
total_subs = total_dels = total_ins = total_words = 0
|
| 147 |
+
total_audio_sec = total_proc_sec = 0.0
|
| 148 |
+
errors = 0
|
| 149 |
+
utts = []
|
| 150 |
+
|
| 151 |
+
n_total = len(dataset)
|
| 152 |
+
if max_samples:
|
| 153 |
+
n_total = min(n_total, max_samples)
|
| 154 |
+
dataset = dataset.select(range(n_total))
|
| 155 |
+
print(f" Samples: {n_total}")
|
| 156 |
+
|
| 157 |
+
for i, sample in enumerate(dataset):
|
| 158 |
+
try:
|
| 159 |
+
audio = np.asarray(sample["audio"]["array"], dtype=np.float32)
|
| 160 |
+
sr = sample["audio"]["sampling_rate"]
|
| 161 |
+
if sr != sample_rate:
|
| 162 |
+
new_len = int(len(audio) * sample_rate / sr)
|
| 163 |
+
audio = np.interp(np.linspace(0, len(audio) - 1, new_len),
|
| 164 |
+
np.arange(len(audio)), audio).astype(np.float32)
|
| 165 |
+
|
| 166 |
+
t0 = time.perf_counter()
|
| 167 |
+
hyp = transcribe(model, params, tokenizer, sample_rate, chunk_samples, audio)
|
| 168 |
+
proc = time.perf_counter() - t0
|
| 169 |
+
dur = len(audio) / sample_rate
|
| 170 |
+
total_audio_sec += dur
|
| 171 |
+
total_proc_sec += proc
|
| 172 |
+
|
| 173 |
+
ref_n = normalize_text(sample["transcription"])
|
| 174 |
+
pred_n = normalize_text(_LANG_TAG_RE.sub(" ", hyp).strip())
|
| 175 |
+
ref_w = ref_n.split()
|
| 176 |
+
pred_w = pred_n.split()
|
| 177 |
+
|
| 178 |
+
sid = sample.get("id", str(i))
|
| 179 |
+
utts.append({"idx": i, "sample_id": str(sid),
|
| 180 |
+
"duration": f"{dur:.2f}", "ref": ref_n, "hyp": pred_n})
|
| 181 |
+
|
| 182 |
+
if ref_w:
|
| 183 |
+
s, d, ins_ = compute_wer_ids(ref_w, pred_w)
|
| 184 |
+
total_subs += s; total_dels += d; total_ins += ins_
|
| 185 |
+
total_words += len(ref_w)
|
| 186 |
+
|
| 187 |
+
if (i + 1) % 25 == 0:
|
| 188 |
+
running = (total_subs + total_dels + total_ins) / max(total_words, 1) * 100
|
| 189 |
+
rtf = total_audio_sec / max(total_proc_sec, 1e-9)
|
| 190 |
+
print(f" [{i+1}/{n_total}] WER: {running:.2f}% RTF: {rtf:.2f}x",
|
| 191 |
+
flush=True)
|
| 192 |
+
except Exception as e:
|
| 193 |
+
errors += 1
|
| 194 |
+
if errors <= 3:
|
| 195 |
+
print(f" [error] {type(e).__name__}: {e}")
|
| 196 |
+
|
| 197 |
+
del model
|
| 198 |
+
total_edits = total_subs + total_dels + total_ins
|
| 199 |
+
wer = total_edits / max(total_words, 1) * 100
|
| 200 |
+
return {
|
| 201 |
+
"name": name, "dataset": "fleurs", "lang": lang,
|
| 202 |
+
"wer": wer,
|
| 203 |
+
"subs": total_subs, "dels": total_dels, "ins": total_ins,
|
| 204 |
+
"sub_rate": total_subs / max(total_words, 1) * 100,
|
| 205 |
+
"del_rate": total_dels / max(total_words, 1) * 100,
|
| 206 |
+
"ins_rate": total_ins / max(total_words, 1) * 100,
|
| 207 |
+
"total_edits": total_edits, "total_words": total_words,
|
| 208 |
+
"errors": errors,
|
| 209 |
+
"audio_sec": total_audio_sec, "proc_sec": total_proc_sec,
|
| 210 |
+
"rtf": total_audio_sec / max(total_proc_sec, 1e-9),
|
| 211 |
+
"utterances": utts,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def main():
|
| 216 |
+
p = argparse.ArgumentParser()
|
| 217 |
+
p.add_argument("--onnx_model", required=True,
|
| 218 |
+
help="Path to ONNX model dir (must contain genai_config.json).")
|
| 219 |
+
p.add_argument("--lang", required=True,
|
| 220 |
+
help="FLEURS lang code, e.g. es_419, de_de, fr_fr.")
|
| 221 |
+
p.add_argument("--name", default="onnx_model",
|
| 222 |
+
help="Display/file name for outputs.")
|
| 223 |
+
p.add_argument("--output_dir", default=None,
|
| 224 |
+
help="Write per-utterance TSV + JSON summary here.")
|
| 225 |
+
p.add_argument("--max_samples", type=int, default=None)
|
| 226 |
+
args = p.parse_args()
|
| 227 |
+
|
| 228 |
+
print(f"\n === {args.name} (FLEURS {args.lang}) — ONNX streaming ===")
|
| 229 |
+
ds = load_fleurs(args.lang)
|
| 230 |
+
r = evaluate(args.onnx_model, ds, name=args.name, lang=args.lang,
|
| 231 |
+
max_samples=args.max_samples)
|
| 232 |
+
|
| 233 |
+
print(f"\n WER: {r['wer']:.2f}% "
|
| 234 |
+
f"(S={r['sub_rate']:.2f}% D={r['del_rate']:.2f}% I={r['ins_rate']:.2f}%)")
|
| 235 |
+
print(f" Words: {r['total_words']} Errors: {r['errors']} "
|
| 236 |
+
f"Audio: {r['audio_sec']:.1f}s Proc: {r['proc_sec']:.1f}s "
|
| 237 |
+
f"RTF: {r['rtf']:.2f}x")
|
| 238 |
+
|
| 239 |
+
if args.output_dir and r["utterances"]:
|
| 240 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 241 |
+
tsv = os.path.join(args.output_dir, f"{args.name}_fleurs_streaming.tsv")
|
| 242 |
+
with open(tsv, "w") as f:
|
| 243 |
+
f.write("idx\tsample_id\tduration_sec\tref\thyp\n")
|
| 244 |
+
for u in r["utterances"]:
|
| 245 |
+
f.write(f"{u['idx']}\t{u['sample_id']}\t{u['duration']}\t"
|
| 246 |
+
f"{u['ref']}\t{u['hyp']}\n")
|
| 247 |
+
print(f" Saved {len(r['utterances'])} utterances -> {tsv}")
|
| 248 |
+
summary = {k: v for k, v in r.items() if k != "utterances"}
|
| 249 |
+
with open(os.path.join(args.output_dir,
|
| 250 |
+
f"{args.name}_fleurs_streaming.json"), "w") as f:
|
| 251 |
+
json.dump(summary, f, indent=2)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
if __name__ == "__main__":
|
| 255 |
+
main()
|
onnx_eval/run_fleurs_eval.sh
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# FLEURS streaming WER eval for Nemotron ONNX (onnxruntime-genai) models.
|
| 3 |
+
#
|
| 4 |
+
# Mirrors the NeMo streaming-eval drivers, but runs the ONNX exports used for
|
| 5 |
+
# the INT4 weight-only encoder-quantization study. The streaming-latency tier
|
| 6 |
+
# is baked into each ONNX export (chunk_samples in genai_config.json), so there
|
| 7 |
+
# is no --chunk_latency flag here: point ONNX_ROOT at the 160/560/1120 ms export
|
| 8 |
+
# set you want to score.
|
| 9 |
+
#
|
| 10 |
+
# Usage:
|
| 11 |
+
# ONNX_ROOT=/path/to/onnx_models bash run_fleurs_eval.sh [GPU] [FLEURS_LANG]
|
| 12 |
+
# ONNX_ROOT=/path/to/onnx_models bash run_fleurs_eval.sh 0 de_de
|
| 13 |
+
#
|
| 14 |
+
# Required env:
|
| 15 |
+
# ONNX_ROOT dir with one subdir per ONNX model (each has genai_config.json).
|
| 16 |
+
# Optional env:
|
| 17 |
+
# OUTPUT_ROOT where to write per-model TSV+JSON (default: <script_dir>/results).
|
| 18 |
+
# OPEN_ASR_LB_ROOT clone of huggingface/open_asr_leaderboard (WER normalizer).
|
| 19 |
+
# HF_DATASETS_CACHE HuggingFace datasets cache for the FLEURS download.
|
| 20 |
+
set -e
|
| 21 |
+
|
| 22 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 23 |
+
PY="$SCRIPT_DIR/eval_fleurs_onnx.py"
|
| 24 |
+
|
| 25 |
+
GPU=${1:-0}
|
| 26 |
+
LANG_CODE=${2:-es_419}
|
| 27 |
+
: "${ONNX_ROOT:?set ONNX_ROOT to a directory of ONNX model subdirs}"
|
| 28 |
+
OUTPUT_ROOT="${OUTPUT_ROOT:-$SCRIPT_DIR/results}"
|
| 29 |
+
mkdir -p "$OUTPUT_ROOT"
|
| 30 |
+
|
| 31 |
+
# WER normalizer (Whisper BasicMultilingualTextNormalizer) from the Open ASR
|
| 32 |
+
# Leaderboard repo; export OPEN_ASR_LB_ROOT or pre-set PYTHONPATH.
|
| 33 |
+
[[ -n "${OPEN_ASR_LB_ROOT:-}" ]] && export PYTHONPATH="$OPEN_ASR_LB_ROOT:${PYTHONPATH:-}"
|
| 34 |
+
|
| 35 |
+
# Model subdirectories under $ONNX_ROOT to evaluate (also used as display names).
|
| 36 |
+
# Edit this list to match your exported models (INT4 / FP32 / per-tier).
|
| 37 |
+
MODELS=(
|
| 38 |
+
es_500h_new_ml_1e4_int4
|
| 39 |
+
es_500h_new_ml_1e4_fp32
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
for name in "${MODELS[@]}"; do
|
| 43 |
+
ONNX_DIR="$ONNX_ROOT/$name"
|
| 44 |
+
OUT="$OUTPUT_ROOT/$name"
|
| 45 |
+
SUMMARY="$OUT/${name}_fleurs_streaming.json"
|
| 46 |
+
|
| 47 |
+
echo ""
|
| 48 |
+
echo "================================================================="
|
| 49 |
+
echo " Evaluating: $name (FLEURS $LANG_CODE)"
|
| 50 |
+
echo "================================================================="
|
| 51 |
+
if [[ ! -f "$ONNX_DIR/genai_config.json" ]]; then
|
| 52 |
+
echo " SKIP — no genai_config.json at $ONNX_DIR" >&2
|
| 53 |
+
continue
|
| 54 |
+
fi
|
| 55 |
+
if [[ -f "$SUMMARY" ]]; then
|
| 56 |
+
echo " SKIP — result already exists at $SUMMARY"
|
| 57 |
+
continue
|
| 58 |
+
fi
|
| 59 |
+
CUDA_VISIBLE_DEVICES=$GPU python3 "$PY" \
|
| 60 |
+
--onnx_model "$ONNX_DIR" \
|
| 61 |
+
--lang "$LANG_CODE" \
|
| 62 |
+
--name "$name" \
|
| 63 |
+
--output_dir "$OUT"
|
| 64 |
+
done
|
| 65 |
+
|
| 66 |
+
echo ""
|
| 67 |
+
echo "=== SUMMARY ==="
|
| 68 |
+
for name in "${MODELS[@]}"; do
|
| 69 |
+
SUM="$OUTPUT_ROOT/$name/${name}_fleurs_streaming.json"
|
| 70 |
+
if [[ -f "$SUM" ]]; then
|
| 71 |
+
WER=$(grep -oE '"wer":[[:space:]]*[0-9.]+' "$SUM" | head -1 | awk '{print $2}')
|
| 72 |
+
printf " %-40s WER = %s%%\n" "$name" "$WER"
|
| 73 |
+
fi
|
| 74 |
+
done
|
| 75 |
+
echo "ONNX FLEURS streaming eval done!"
|
paper/aggregate.py
ADDED
|
@@ -0,0 +1,687 @@
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Recompute every WER aggregate reported in the paper from a single
|
| 3 |
+
JSON file of per-cell WERs (``wer_results.json``, shipped alongside
|
| 4 |
+
this script).
|
| 5 |
+
|
| 6 |
+
This script is self-contained: it reads only the per-cell WER values
|
| 7 |
+
from the JSON and re-derives every table and figure number in the
|
| 8 |
+
paper that depends on those WERs alone. Quantities that need inputs
|
| 9 |
+
beyond the per-cell WER table -- the per-utterance paired-bootstrap
|
| 10 |
+
significance markers in Table~\\ref{tab:main160}, or convergence-epoch
|
| 11 |
+
counts taken from the training logs -- are out of scope here and are
|
| 12 |
+
not recomputed.
|
| 13 |
+
|
| 14 |
+
Each check below is keyed to a stable LaTeX ``\\label`` (its ``\\ref``
|
| 15 |
+
target), which does not change if the paper is reordered; the ``[N]``
|
| 16 |
+
markers are just this script's own output tags, not paper section
|
| 17 |
+
numbers:
|
| 18 |
+
|
| 19 |
+
[1] tab:main160 FLEURS WER (%) @ 160 ms, per-(lang, hours).
|
| 20 |
+
[2] sec:hours intro seen / unseen group mean Δ trajectory.
|
| 21 |
+
[3] tab:latency_effect mean EN-ML gap per (tier, hours), FLEURS.
|
| 22 |
+
[4] tab:abs_wer mean ML-init absolute WER per (tier, hours).
|
| 23 |
+
[5] tab:lst per-lang Δ + LST per hours; macro mean.
|
| 24 |
+
[6] sec:from_pl HR-from-PL pivot vs direct ML, 160 ms.
|
| 25 |
+
[7] sec:reinitjoint joiner-reinit Δ, 560 ms FLEURS/VP.
|
| 26 |
+
[8] tab:quant INT4 vs FP32 @ 560 ms FLEURS, paired stats.
|
| 27 |
+
[9] tab:5000h_es ES 5000h vs 2500h ML deltas, and ES 5000h
|
| 28 |
+
vs Nemotron-3.5 ML (tab:supp:es5000h).
|
| 29 |
+
[10] fig:gap_powerlaw fit Δ(h) = a·h^(-β) at 160 ms;
|
| 30 |
+
language-bootstrap 95% CI on β; R².
|
| 31 |
+
[11] tab:hybrid hybrid-encoder 100h/560ms FLEURS table.
|
| 32 |
+
[12] tab:seed + sec:seed HR/PT main-grid seed deltas + 16-cell 100h
|
| 33 |
+
re-run @ 560 ms (FLEURS + VP); IS-EN excursion.
|
| 34 |
+
[13] streaming penalty per (tier, hours, init), FLEURS.
|
| 35 |
+
[14] tab:per_dataset per-dataset 160 ms WER appendix.
|
| 36 |
+
|
| 37 |
+
Usage:
|
| 38 |
+
# with wer_results.json sitting next to this script:
|
| 39 |
+
python3 aggregate.py
|
| 40 |
+
# or pass an explicit path to a results JSON:
|
| 41 |
+
python3 aggregate.py /path/to/wer_results.json
|
| 42 |
+
"""
|
| 43 |
+
from __future__ import annotations
|
| 44 |
+
|
| 45 |
+
import json
|
| 46 |
+
import statistics
|
| 47 |
+
import sys
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
|
| 50 |
+
HERE = Path(__file__).resolve().parent
|
| 51 |
+
# Default to wer_results.json sitting next to this script; fall back to
|
| 52 |
+
# the in-repository ``paper/`` layout when run from a full checkout.
|
| 53 |
+
DEFAULT_JSON = next(
|
| 54 |
+
(p for p in (HERE / "wer_results.json",
|
| 55 |
+
HERE.parent / "paper" / "wer_results.json")
|
| 56 |
+
if p.is_file()),
|
| 57 |
+
HERE / "wer_results.json",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
LANGS = ["de", "es", "fr", "hr", "is", "nl", "pl", "pt"]
|
| 61 |
+
SEEN = ["de", "es", "fr", "nl"]
|
| 62 |
+
UNSEEN = ["pt", "hr", "is", "pl"]
|
| 63 |
+
HOURS = ["100h", "250h", "500h", "1000h", "2500h"]
|
| 64 |
+
TIERS = ["160ms", "560ms", "1120ms", "offline"]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ---------------------------------------------------------------------------
|
| 68 |
+
# JSON helpers
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
def wer(d, lang, hours, init, tier, dataset):
|
| 71 |
+
"""Return the WER (float) at d[lang][hours][init][tier][dataset], or None."""
|
| 72 |
+
try:
|
| 73 |
+
cell = d[lang][hours][init][tier][dataset]
|
| 74 |
+
if isinstance(cell, dict):
|
| 75 |
+
v = cell.get("wer")
|
| 76 |
+
return float(v) if v is not None else None
|
| 77 |
+
except (KeyError, TypeError):
|
| 78 |
+
pass
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def delta(d, lang, hours, tier, dataset):
|
| 83 |
+
"""EN - ML WER gap; None if either side missing."""
|
| 84 |
+
ml = wer(d, lang, hours, "ml", tier, dataset)
|
| 85 |
+
en = wer(d, lang, hours, "enc", tier, dataset)
|
| 86 |
+
if ml is None or en is None:
|
| 87 |
+
return None
|
| 88 |
+
return en - ml
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def fmt(x, signed=False, w=7):
|
| 92 |
+
if x is None:
|
| 93 |
+
return f"{'--':>{w}s}"
|
| 94 |
+
return f"{x:+{w}.2f}" if signed else f"{x:{w}.2f}"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def mean(xs):
|
| 98 |
+
xs = [x for x in xs if x is not None]
|
| 99 |
+
return statistics.fmean(xs) if xs else None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def hr(title):
|
| 103 |
+
print()
|
| 104 |
+
print("=" * 78)
|
| 105 |
+
print(title)
|
| 106 |
+
print("=" * 78)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# ---------------------------------------------------------------------------
|
| 110 |
+
# [1] Table :main160 — FLEURS WER (%) at 160 ms streaming, per-(lang, hours)
|
| 111 |
+
# ---------------------------------------------------------------------------
|
| 112 |
+
def t_main160(d):
|
| 113 |
+
hr("[1] Table tab:main160 — FLEURS WER (%) @ 160 ms")
|
| 114 |
+
head = "lang " + "".join(f"{h:>27s}" for h in HOURS)
|
| 115 |
+
print(head)
|
| 116 |
+
sub = " " + "".join(f"{'ml':>9s}{'enc':>9s}{'Δ':>9s}" for _ in HOURS)
|
| 117 |
+
print(sub)
|
| 118 |
+
for lang in LANGS:
|
| 119 |
+
row = f"{lang.upper():<6s}"
|
| 120 |
+
for h in HOURS:
|
| 121 |
+
ml = wer(d, lang, h, "ml", "160ms", "fleurs")
|
| 122 |
+
en = wer(d, lang, h, "enc", "160ms", "fleurs")
|
| 123 |
+
dl = (en - ml) if (ml is not None and en is not None) else None
|
| 124 |
+
row += fmt(ml, w=9) + fmt(en, w=9) + fmt(dl, signed=True, w=9)
|
| 125 |
+
print(row)
|
| 126 |
+
print("-" * len(head))
|
| 127 |
+
# macro means
|
| 128 |
+
row = f"{'mean':<6s}"
|
| 129 |
+
for h in HOURS:
|
| 130 |
+
mls = [wer(d, l, h, "ml", "160ms", "fleurs") for l in LANGS]
|
| 131 |
+
ens = [wer(d, l, h, "enc", "160ms", "fleurs") for l in LANGS]
|
| 132 |
+
dls = [(e - m) for m, e in zip(mls, ens) if m is not None and e is not None]
|
| 133 |
+
row += fmt(mean(mls), w=9) + fmt(mean(ens), w=9) \
|
| 134 |
+
+ fmt(mean(dls) if dls else None, signed=True, w=9)
|
| 135 |
+
print(row)
|
| 136 |
+
n_per_h = {h: sum(1 for l in LANGS
|
| 137 |
+
if wer(d, l, h, "ml", "160ms", "fleurs") is not None
|
| 138 |
+
and wer(d, l, h, "enc", "160ms", "fleurs") is not None)
|
| 139 |
+
for h in HOURS}
|
| 140 |
+
print(" K per hours: " + ", ".join(f"{h}={n_per_h[h]}" for h in HOURS))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ---------------------------------------------------------------------------
|
| 144 |
+
# [2] sec:hours — seen / unseen group mean Δ trajectory, FLEURS @ 160 ms
|
| 145 |
+
# ---------------------------------------------------------------------------
|
| 146 |
+
def t_seen_unseen(d):
|
| 147 |
+
hr("[2] sec:hours — seen vs unseen group mean Δ, FLEURS @ 160 ms")
|
| 148 |
+
print(f" {'group':<10s}" + "".join(f"{h:>10s}" for h in HOURS))
|
| 149 |
+
for label, group in (("seen", SEEN), ("unseen", UNSEEN), ("all", LANGS)):
|
| 150 |
+
row = f" {label:<10s}"
|
| 151 |
+
for h in HOURS:
|
| 152 |
+
dls = [delta(d, l, h, "160ms", "fleurs") for l in group]
|
| 153 |
+
row += fmt(mean(dls), signed=True, w=10)
|
| 154 |
+
print(row)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ---------------------------------------------------------------------------
|
| 158 |
+
# [3] Table :latency_effect — mean EN-ML gap per (tier, hours), FLEURS
|
| 159 |
+
# ---------------------------------------------------------------------------
|
| 160 |
+
def t_latency_effect(d):
|
| 161 |
+
hr("[3] Table tab:latency_effect — mean Δ (EN-ML) per (tier, hours), FLEURS")
|
| 162 |
+
print(f" {'tier':<10s}" + "".join(f"{h:>10s}" for h in HOURS)
|
| 163 |
+
+ f"{'range':>10s}")
|
| 164 |
+
per_h = {h: [] for h in HOURS}
|
| 165 |
+
for tier in TIERS:
|
| 166 |
+
row = f" {tier:<10s}"
|
| 167 |
+
for h in HOURS:
|
| 168 |
+
dls = [delta(d, l, h, tier, "fleurs") for l in LANGS]
|
| 169 |
+
m = mean(dls)
|
| 170 |
+
per_h[h].append(m)
|
| 171 |
+
row += fmt(m, signed=True, w=10)
|
| 172 |
+
print(row)
|
| 173 |
+
# cross-tier range of mean Δ at each hours (paper sentence)
|
| 174 |
+
print(f" {'tier-range':<10s}", end="")
|
| 175 |
+
for h in HOURS:
|
| 176 |
+
vs = [v for v in per_h[h] if v is not None]
|
| 177 |
+
rng = max(vs) - min(vs) if vs else None
|
| 178 |
+
print(fmt(rng, w=10), end="")
|
| 179 |
+
print()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ---------------------------------------------------------------------------
|
| 183 |
+
# [4] Table :abs_wer — mean ML-init absolute FLEURS WER per (tier, hours)
|
| 184 |
+
# ---------------------------------------------------------------------------
|
| 185 |
+
def t_abs_wer(d):
|
| 186 |
+
hr("[4] Table tab:abs_wer — mean ML-init FLEURS WER (%) per (tier, hours)")
|
| 187 |
+
print(f" {'tier':<10s}" + "".join(f"{h:>10s}" for h in HOURS))
|
| 188 |
+
for tier in TIERS:
|
| 189 |
+
row = f" {tier:<10s}"
|
| 190 |
+
for h in HOURS:
|
| 191 |
+
mls = [wer(d, l, h, "ml", tier, "fleurs") for l in LANGS]
|
| 192 |
+
row += fmt(mean(mls), w=10)
|
| 193 |
+
print(row)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# ---------------------------------------------------------------------------
|
| 197 |
+
# [5] Table :lst — per-lang Δ + LST per hours; macro mean
|
| 198 |
+
# LST(lang, h) = max_tier Δ_tier(lang, h) - min_tier Δ_tier(lang, h)
|
| 199 |
+
# Δ(lang, h) = mean_tier Δ_tier(lang, h)
|
| 200 |
+
# Both are taken over the THREE streaming tiers only (160/560/1120 ms);
|
| 201 |
+
# offline is excluded by definition (eq. lst / Table tab:lst caption).
|
| 202 |
+
# ---------------------------------------------------------------------------
|
| 203 |
+
def t_lst(d):
|
| 204 |
+
hr("[5] Table tab:lst — per-lang Δ , LST on FLEURS (per hours)")
|
| 205 |
+
stream_tiers = ["160ms", "560ms", "1120ms"] # LST excludes offline
|
| 206 |
+
h_show = ["100h", "250h", "500h", "1000h"] # paper omits 2500h here
|
| 207 |
+
head = f" {'lang':<6s}" + "".join(f"{h:>20s}" for h in h_show)
|
| 208 |
+
print(head)
|
| 209 |
+
print(f" {'':<6s}" + "".join(f"{'Δ':>10s}{'LST':>10s}" for _ in h_show))
|
| 210 |
+
barD = {h: [] for h in h_show}
|
| 211 |
+
lst = {h: [] for h in h_show}
|
| 212 |
+
for lang in LANGS:
|
| 213 |
+
row = f" {lang.upper():<6s}"
|
| 214 |
+
for h in h_show:
|
| 215 |
+
ds = [delta(d, lang, h, t, "fleurs") for t in stream_tiers]
|
| 216 |
+
ds = [x for x in ds if x is not None]
|
| 217 |
+
if not ds:
|
| 218 |
+
row += fmt(None, w=10) + fmt(None, w=10); continue
|
| 219 |
+
bd = sum(ds) / len(ds)
|
| 220 |
+
ls = max(ds) - min(ds)
|
| 221 |
+
barD[h].append(bd); lst[h].append(ls)
|
| 222 |
+
row += fmt(bd, signed=True, w=10) + fmt(ls, w=10)
|
| 223 |
+
print(row)
|
| 224 |
+
print(" " + "-" * 76)
|
| 225 |
+
row = f" {'mean':<6s}"
|
| 226 |
+
for h in h_show:
|
| 227 |
+
row += fmt(mean(barD[h]), signed=True, w=10) + fmt(mean(lst[h]), w=10)
|
| 228 |
+
print(row)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# ---------------------------------------------------------------------------
|
| 232 |
+
# [6] Sec :from_pl — HR-from-PL pivot vs direct ML, 160 ms FLEURS/VP
|
| 233 |
+
# ---------------------------------------------------------------------------
|
| 234 |
+
def t_from_pl(d):
|
| 235 |
+
hr("[6] Sec sec:from_pl — HR PL-pivot vs direct ML (160 ms)")
|
| 236 |
+
rows = ["100h", "250h", "500h", "1000h"]
|
| 237 |
+
print(f" {'hours':<6s}{'direct ml FL':>14s}{'pivot ml FL':>14s}{'Δ FL':>8s}"
|
| 238 |
+
f"{'direct ml VP':>14s}{'pivot ml VP':>14s}{'Δ VP':>8s}")
|
| 239 |
+
for h in rows:
|
| 240 |
+
dml_fl = wer(d, "hr", h, "ml", "160ms", "fleurs")
|
| 241 |
+
piv_fl = wer(d, "hr", h, "from_pl_ml", "160ms", "fleurs")
|
| 242 |
+
dml_vp = wer(d, "hr", h, "ml", "160ms", "voxpopuli")
|
| 243 |
+
piv_vp = wer(d, "hr", h, "from_pl_ml", "160ms", "voxpopuli")
|
| 244 |
+
dfl = (piv_fl - dml_fl) if (dml_fl is not None and piv_fl is not None) else None
|
| 245 |
+
dvp = (piv_vp - dml_vp) if (dml_vp is not None and piv_vp is not None) else None
|
| 246 |
+
print(f" {h:<6s}{fmt(dml_fl,w=14)}{fmt(piv_fl,w=14)}{fmt(dfl,signed=True,w=8)}"
|
| 247 |
+
f"{fmt(dml_vp,w=14)}{fmt(piv_vp,w=14)}{fmt(dvp,signed=True,w=8)}")
|
| 248 |
+
# PL(EN) pivot only at 100h
|
| 249 |
+
piv_en_fl = wer(d, "hr", "100h", "from_pl_enc", "160ms", "fleurs")
|
| 250 |
+
den_fl = wer(d, "hr", "100h", "enc", "160ms", "fleurs")
|
| 251 |
+
if piv_en_fl is not None and den_fl is not None:
|
| 252 |
+
print(f" PL(EN) pivot @100h FLEURS: direct enc={den_fl:.2f} "
|
| 253 |
+
f"pivot={piv_en_fl:.2f} Δ={piv_en_fl - den_fl:+.2f} pp")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ---------------------------------------------------------------------------
|
| 257 |
+
# [7] Sec :reinitjoint — joiner re-init Δ at 100 h, 560 ms FLEURS/VP
|
| 258 |
+
# ---------------------------------------------------------------------------
|
| 259 |
+
def t_reinitjoint(d):
|
| 260 |
+
hr("[7] Sec sec:reinitjoint — joiner-reinit Δ vs baseline @ 100h, 560 ms")
|
| 261 |
+
deltas_fl = {"ml": [], "enc": []}
|
| 262 |
+
deltas_vp = {"ml": [], "enc": []}
|
| 263 |
+
rows = []
|
| 264 |
+
for lang in LANGS:
|
| 265 |
+
for init in ("ml", "enc"):
|
| 266 |
+
base_fl = wer(d, lang, "100h", init, "560ms", "fleurs")
|
| 267 |
+
rj_fl = wer(d, lang, "100h", f"{init}_reinitjoint", "560ms", "fleurs")
|
| 268 |
+
base_vp = wer(d, lang, "100h", init, "560ms", "voxpopuli")
|
| 269 |
+
rj_vp = wer(d, lang, "100h", f"{init}_reinitjoint", "560ms", "voxpopuli")
|
| 270 |
+
dfl = (rj_fl - base_fl) if (base_fl is not None and rj_fl is not None) else None
|
| 271 |
+
dvp = (rj_vp - base_vp) if (base_vp is not None and rj_vp is not None) else None
|
| 272 |
+
if dfl is not None: deltas_fl[init].append(dfl)
|
| 273 |
+
if dvp is not None: deltas_vp[init].append(dvp)
|
| 274 |
+
rows.append((lang, init, dfl, dvp))
|
| 275 |
+
if not (deltas_fl["ml"] or deltas_fl["enc"]):
|
| 276 |
+
print(" (no reinitjoint cells found in JSON)")
|
| 277 |
+
return
|
| 278 |
+
print(f" {'lang':<4s} {'init':<4s} {'Δ FL':>8s} {'Δ VP':>8s}")
|
| 279 |
+
for lang, init, dfl, dvp in rows:
|
| 280 |
+
print(f" {lang:<4s} {init:<4s} {fmt(dfl,signed=True,w=8)} {fmt(dvp,signed=True,w=8)}")
|
| 281 |
+
all_fl = deltas_fl["ml"] + deltas_fl["enc"]
|
| 282 |
+
all_vp = deltas_vp["ml"] + deltas_vp["enc"]
|
| 283 |
+
hurt_fl = sum(1 for x in all_fl if x > 0)
|
| 284 |
+
hurt_vp = sum(1 for x in all_vp if x > 0)
|
| 285 |
+
print(f"\n mean Δ FL (all 16): {mean(all_fl):+0.2f} pp ({hurt_fl}/{len(all_fl)} hurt)")
|
| 286 |
+
print(f" mean Δ FL (ml arm): {mean(deltas_fl['ml']):+0.2f} pp")
|
| 287 |
+
print(f" mean Δ FL (enc arm):{mean(deltas_fl['enc']):+0.2f} pp")
|
| 288 |
+
print(f" mean Δ VP (all): {mean(all_vp):+0.2f} pp ({hurt_vp}/{len(all_vp)} hurt)")
|
| 289 |
+
print(f" mean Δ VP (ml arm): {mean(deltas_vp['ml']):+0.2f} pp")
|
| 290 |
+
print(f" mean Δ VP (enc arm):{mean(deltas_vp['enc']):+0.2f} pp")
|
| 291 |
+
if deltas_fl["enc"] and deltas_fl["ml"]:
|
| 292 |
+
worst_enc = max(rows, key=lambda r: r[2] if r[1] == "enc" and r[2] is not None else -1)
|
| 293 |
+
worst_ml = max(rows, key=lambda r: r[2] if r[1] == "ml" and r[2] is not None else -1)
|
| 294 |
+
print(f" worst Δ FL enc: {worst_enc[0]}-{worst_enc[1]} {worst_enc[2]:+0.2f}")
|
| 295 |
+
print(f" worst Δ FL ml: {worst_ml[0]}-{worst_ml[1]} {worst_ml[2]:+0.2f}")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# ---------------------------------------------------------------------------
|
| 299 |
+
# [8] Table :quant — INT4 vs FP32 @ 560 ms FLEURS
|
| 300 |
+
# ---------------------------------------------------------------------------
|
| 301 |
+
def t_quant(d):
|
| 302 |
+
hr("[8] Table tab:quant — INT4 vs FP32 @ 560 ms FLEURS")
|
| 303 |
+
rows = {h: {"ml": [], "enc": []} for h in HOURS}
|
| 304 |
+
all_cells = [] # (lang, hours, init, Δ_int4-fp32)
|
| 305 |
+
paired = [] # (lang, hours, Δ_ml, Δ_enc)
|
| 306 |
+
for h in HOURS:
|
| 307 |
+
per_lang_paired = {}
|
| 308 |
+
for lang in LANGS:
|
| 309 |
+
for init in ("ml", "enc"):
|
| 310 |
+
i4 = wer(d, lang, h, init, "560ms", "fleurs_int4")
|
| 311 |
+
f3 = wer(d, lang, h, init, "560ms", "fleurs_fp32")
|
| 312 |
+
if i4 is None or f3 is None:
|
| 313 |
+
continue
|
| 314 |
+
dq = i4 - f3
|
| 315 |
+
rows[h][init].append(dq)
|
| 316 |
+
all_cells.append((lang, h, init, dq))
|
| 317 |
+
per_lang_paired.setdefault(lang, {})[init] = dq
|
| 318 |
+
for lang, cells in per_lang_paired.items():
|
| 319 |
+
if "ml" in cells and "enc" in cells:
|
| 320 |
+
paired.append((lang, h, cells["ml"], cells["enc"]))
|
| 321 |
+
|
| 322 |
+
print(f" {'hours':<6s}{'Δ_ml':>9s}{'n_ml':>6s}{'Δ_enc':>9s}{'n_enc':>6s}")
|
| 323 |
+
for h in HOURS:
|
| 324 |
+
ml = rows[h]["ml"]; en = rows[h]["enc"]
|
| 325 |
+
print(f" {h:<6s}{fmt(mean(ml),signed=True,w=9)}{len(ml):>6d}"
|
| 326 |
+
f"{fmt(mean(en),signed=True,w=9)}{len(en):>6d}")
|
| 327 |
+
|
| 328 |
+
# pooled stats over all (lang, hours, init)
|
| 329 |
+
dq_all = [c[3] for c in all_cells]
|
| 330 |
+
if dq_all:
|
| 331 |
+
dq_sorted = sorted(dq_all)
|
| 332 |
+
med = statistics.median(dq_sorted)
|
| 333 |
+
n = len(dq_all)
|
| 334 |
+
within05 = sum(1 for x in dq_all if abs(x) <= 0.5)
|
| 335 |
+
within10 = sum(1 for x in dq_all if abs(x) <= 1.0)
|
| 336 |
+
worse = sum(1 for x in dq_all if x > 0)
|
| 337 |
+
better = sum(1 for x in dq_all if x < 0)
|
| 338 |
+
print()
|
| 339 |
+
print(f" pooled (n={n}): mean={mean(dq_all):+0.2f} median={med:+0.2f}"
|
| 340 |
+
f" range=[{min(dq_all):+0.2f},{max(dq_all):+0.2f}]")
|
| 341 |
+
print(f" |Δ| ≤ 0.5 pp: {within05}/{n} |Δ| ≤ 1.0 pp: {within10}/{n}")
|
| 342 |
+
print(f" INT4 worse than FP32: {worse}/{n} INT4 better: {better}/{n}")
|
| 343 |
+
|
| 344 |
+
# paired ML vs EN quant cost
|
| 345 |
+
if paired:
|
| 346 |
+
diffs = [p[3] - p[2] for p in paired] # Δ_enc - Δ_ml
|
| 347 |
+
enc_costlier = sum(1 for x in diffs if x > 0)
|
| 348 |
+
print(f"\n paired ML vs EN (same lang, same hours, n={len(paired)}):")
|
| 349 |
+
print(f" mean (Δ_enc - Δ_ml) = {mean(diffs):+0.2f} pp")
|
| 350 |
+
print(f" EN costlier than ML in {enc_costlier}/{len(paired)} cells")
|
| 351 |
+
print(f" range = [{min(diffs):+0.2f}, {max(diffs):+0.2f}] pp")
|
| 352 |
+
# 100h breakdown (paper says 'weakest at 100h, EN costlier in 5 of 8')
|
| 353 |
+
for h in HOURS:
|
| 354 |
+
sub = [(p[2], p[3]) for p in paired if p[1] == h]
|
| 355 |
+
if not sub:
|
| 356 |
+
continue
|
| 357 |
+
sub_diffs = [b - a for a, b in sub]
|
| 358 |
+
print(f" {h}: paired n={len(sub)} mean Δ_enc-Δ_ml={mean(sub_diffs):+0.2f}"
|
| 359 |
+
f" EN costlier in {sum(1 for x in sub_diffs if x > 0)}/{len(sub)}")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# [9] ES 5000h ML deltas vs ES 2500h ML (tab:5000h_es), plus ES 5000h ML
|
| 364 |
+
# vs the Nemotron-3.5 ML baseline (tab:supp:es5000h); all four test
|
| 365 |
+
# sets, 560 ms streaming.
|
| 366 |
+
# ---------------------------------------------------------------------------
|
| 367 |
+
def t_es_5000h(d):
|
| 368 |
+
if "5000h" not in d.get("es", {}):
|
| 369 |
+
return
|
| 370 |
+
hr("[9] Sec sec:hours — ES 5000h vs 2500h ML, 560 ms streaming")
|
| 371 |
+
for dataset in ("fleurs", "cv", "mls", "voxpopuli"):
|
| 372 |
+
a = wer(d, "es", "5000h", "ml", "560ms", dataset)
|
| 373 |
+
b = wer(d, "es", "2500h", "ml", "560ms", dataset)
|
| 374 |
+
delta_ = (a - b) if (a is not None and b is not None) else None
|
| 375 |
+
print(f" {dataset:<10s} 5000h={fmt(a)} 2500h={fmt(b)}"
|
| 376 |
+
f" Δ={fmt(delta_, signed=True)}")
|
| 377 |
+
|
| 378 |
+
# tab:supp:es5000h — ES 5000h (ML) vs contemporaneous Nemotron-3.5 ML
|
| 379 |
+
# baseline, 560 ms streaming. Δ = WER_5000h − WER_Nemotron (negative:
|
| 380 |
+
# our 5000h model better).
|
| 381 |
+
if "nvidia-nemotron-3.5-asr" in d.get("es", {}).get("5000h", {}):
|
| 382 |
+
print(" -- tab:supp:es5000h — ES 5000h (ML) vs Nemotron-3.5 ML:")
|
| 383 |
+
for dataset in ("fleurs", "cv", "mls", "voxpopuli"):
|
| 384 |
+
a = wer(d, "es", "5000h", "ml", "560ms", dataset)
|
| 385 |
+
n = wer(d, "es", "5000h", "nvidia-nemotron-3.5-asr", "560ms", dataset)
|
| 386 |
+
delta_ = (a - n) if (a is not None and n is not None) else None
|
| 387 |
+
print(f" {dataset:<10s} 5000h={fmt(a)} nemotron={fmt(n)}"
|
| 388 |
+
f" Δ={fmt(delta_, signed=True)}")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# ---------------------------------------------------------------------------
|
| 392 |
+
# [10] fig:gap_powerlaw — fit Δ(h) = a · h^(-β) on the 160 ms macro means
|
| 393 |
+
# with a language-bootstrap 95% CI on β.
|
| 394 |
+
# ---------------------------------------------------------------------------
|
| 395 |
+
def t_powerlaw(d, B=10000, seed=0):
|
| 396 |
+
hr("[10] fig:gap_powerlaw — transfer-gap power-law fit (160 ms FLEURS)")
|
| 397 |
+
import math
|
| 398 |
+
import random as _rand
|
| 399 |
+
rng = _rand.Random(seed)
|
| 400 |
+
hours_int = [int(h[:-1]) for h in HOURS]
|
| 401 |
+
|
| 402 |
+
def fit(deltas_by_h):
|
| 403 |
+
"""Return (β, log_a, R²) from least-squares fit on log(h) vs log(Δ)
|
| 404 |
+
across hours where Δ > 0 (so log is defined)."""
|
| 405 |
+
xs, ys = [], []
|
| 406 |
+
for h, dl in zip(hours_int, deltas_by_h):
|
| 407 |
+
if dl is None or dl <= 0:
|
| 408 |
+
continue
|
| 409 |
+
xs.append(math.log(h)); ys.append(math.log(dl))
|
| 410 |
+
if len(xs) < 2:
|
| 411 |
+
return None, None, None
|
| 412 |
+
n = len(xs)
|
| 413 |
+
mx = sum(xs)/n; my = sum(ys)/n
|
| 414 |
+
sxy = sum((x-mx)*(y-my) for x, y in zip(xs, ys))
|
| 415 |
+
sxx = sum((x-mx)**2 for x in xs)
|
| 416 |
+
if sxx == 0:
|
| 417 |
+
return None, None, None
|
| 418 |
+
slope = sxy / sxx # = -β
|
| 419 |
+
intercept = my - slope * mx
|
| 420 |
+
beta = -slope
|
| 421 |
+
# R²
|
| 422 |
+
syy = sum((y-my)**2 for y in ys)
|
| 423 |
+
if syy == 0:
|
| 424 |
+
r2 = 1.0
|
| 425 |
+
else:
|
| 426 |
+
ss_res = sum((y - (slope*x + intercept))**2 for x, y in zip(xs, ys))
|
| 427 |
+
r2 = 1 - ss_res/syy
|
| 428 |
+
return beta, intercept, r2
|
| 429 |
+
|
| 430 |
+
# point estimate from the full 8-lang macro means
|
| 431 |
+
macro = [mean([delta(d, l, h, "160ms", "fleurs") for l in LANGS]) for h in HOURS]
|
| 432 |
+
beta, log_a, r2 = fit(macro)
|
| 433 |
+
if beta is None:
|
| 434 |
+
print(" (insufficient points for power-law fit)")
|
| 435 |
+
return
|
| 436 |
+
print(f" hours mean Δ (160 ms FLEURS)")
|
| 437 |
+
for h, m in zip(HOURS, macro):
|
| 438 |
+
print(f" {h:<8s} {fmt(m, signed=True)}")
|
| 439 |
+
print(f"\n β_TG = {beta:.3f} R² = {r2:.4f} "
|
| 440 |
+
f"(fit on log Δ vs log h, where Δ>0)")
|
| 441 |
+
|
| 442 |
+
# language-bootstrap CI: resample 8 languages with replacement, recompute
|
| 443 |
+
# macro means per hours, refit, collect β.
|
| 444 |
+
betas = []
|
| 445 |
+
n_lang = len(LANGS)
|
| 446 |
+
for _ in range(B):
|
| 447 |
+
sample = [LANGS[rng.randrange(n_lang)] for _ in range(n_lang)]
|
| 448 |
+
ms = [mean([delta(d, l, h, "160ms", "fleurs") for l in sample]) for h in HOURS]
|
| 449 |
+
b, _, _ = fit(ms)
|
| 450 |
+
if b is not None and math.isfinite(b):
|
| 451 |
+
betas.append(b)
|
| 452 |
+
if betas:
|
| 453 |
+
betas.sort()
|
| 454 |
+
lo = betas[int(0.025 * len(betas))]
|
| 455 |
+
hi = betas[int(0.975 * len(betas))]
|
| 456 |
+
frac_below = sum(1 for b in betas if b < 0.5) / len(betas)
|
| 457 |
+
print(f" language-bootstrap 95% CI on β (B={B}): [{lo:.2f}, {hi:.2f}]")
|
| 458 |
+
print(f" P(β < 0.5) = {frac_below:.4f} ({100 * frac_below:.2f}%)")
|
| 459 |
+
|
| 460 |
+
# off-tier residuals (paper Fig. fig:gap_powerlaw caption: 0.23/0.29/0.13 pp)
|
| 461 |
+
import math as _m
|
| 462 |
+
print("\n Off-tier residuals against the 160 ms-fitted curve:")
|
| 463 |
+
for tier in ("560ms", "1120ms", "offline"):
|
| 464 |
+
mac = [mean([delta(d, l, h, tier, "fleurs") for l in LANGS]) for h in HOURS]
|
| 465 |
+
res = []
|
| 466 |
+
for h, m in zip(hours_int, mac):
|
| 467 |
+
if m is None or m <= 0:
|
| 468 |
+
continue
|
| 469 |
+
pred = _m.exp(log_a + (-beta) * _m.log(h))
|
| 470 |
+
res.append((m - pred) ** 2)
|
| 471 |
+
if res:
|
| 472 |
+
rms = (sum(res) / len(res)) ** 0.5
|
| 473 |
+
print(f" {tier:<8s} RMS={rms:.2f} pp (n={len(res)})")
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
# ---------------------------------------------------------------------------
|
| 477 |
+
# [11] tab:hybrid — hybrid-encoder, 100h training, 560 ms FLEURS
|
| 478 |
+
# Splices: hybrid_0to12 / hybrid_last / hybrid_first / hybrid_middle
|
| 479 |
+
# Reference rows are seed-45 ml / enc (paper: same common seed).
|
| 480 |
+
# ---------------------------------------------------------------------------
|
| 481 |
+
def t_hybrid(d):
|
| 482 |
+
hr("[11] tab:hybrid — hybrid encoder @ 100h, 560 ms FLEURS")
|
| 483 |
+
rows = [
|
| 484 |
+
("ML (s45)", "ml_s45"),
|
| 485 |
+
("0:12", "hybrid_0to12"),
|
| 486 |
+
("last", "hybrid_last"),
|
| 487 |
+
("first", "hybrid_first"),
|
| 488 |
+
("middle", "hybrid_middle"),
|
| 489 |
+
("EN (s45)", "enc_s45"),
|
| 490 |
+
]
|
| 491 |
+
# header
|
| 492 |
+
print(f" {'row':<10s}" + "".join(f"{l.upper():>7s}" for l in LANGS)
|
| 493 |
+
+ f"{'mean':>9s}{'Δ vs ML':>10s}")
|
| 494 |
+
ml_row = None
|
| 495 |
+
table = []
|
| 496 |
+
for label, init in rows:
|
| 497 |
+
cells = [wer(d, l, "100h", init, "560ms", "fleurs") for l in LANGS]
|
| 498 |
+
mn = mean(cells)
|
| 499 |
+
table.append((label, init, cells, mn))
|
| 500 |
+
if init == "ml_s45":
|
| 501 |
+
ml_row = cells
|
| 502 |
+
for label, init, cells, mn in table:
|
| 503 |
+
if ml_row is None or any(c is None for c in cells) or any(m is None for m in ml_row):
|
| 504 |
+
d_vs_ml = None
|
| 505 |
+
else:
|
| 506 |
+
pairwise = [c - m for c, m in zip(cells, ml_row)]
|
| 507 |
+
d_vs_ml = sum(pairwise) / len(pairwise)
|
| 508 |
+
row = f" {label:<10s}" + "".join(fmt(c, w=7) for c in cells) + fmt(mn, w=9)
|
| 509 |
+
row += fmt(d_vs_ml, signed=True, w=10) if d_vs_ml is not None else f"{'--':>10s}"
|
| 510 |
+
print(row)
|
| 511 |
+
|
| 512 |
+
# seen / unseen group means
|
| 513 |
+
print("\n group means:")
|
| 514 |
+
for label, init, cells, _ in table:
|
| 515 |
+
seen_m = mean([wer(d, l, "100h", init, "560ms", "fleurs") for l in SEEN])
|
| 516 |
+
unseen_m = mean([wer(d, l, "100h", init, "560ms", "fleurs") for l in UNSEEN])
|
| 517 |
+
print(f" {label:<10s} seen={fmt(seen_m, w=7)} unseen={fmt(unseen_m, w=7)}")
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
# ---------------------------------------------------------------------------
|
| 521 |
+
# [12] tab:seed + sec:seed — seed comparison
|
| 522 |
+
# (a) HR/PT main-grid 160 ms FLEURS + VP, default seed vs seed 45
|
| 523 |
+
# (b) 16-cell 100h re-run @ 560 ms across all 8 langs × 2 inits;
|
| 524 |
+
# stats: mean |Δ|, median, max on FLEURS and VP
|
| 525 |
+
# (c) HR-100h FLEURS swing collapse at 560 ms
|
| 526 |
+
# (d) Largest seed-induced EN-ML gap excursion (IS at 100h)
|
| 527 |
+
# ---------------------------------------------------------------------------
|
| 528 |
+
def t_seed(d):
|
| 529 |
+
hr("[12] tab:seed + sec:seed — seed-default vs seed-45")
|
| 530 |
+
# (a) HR / PT main grid at 160 ms FLEURS + VP
|
| 531 |
+
print(" (a) HR / PT main-grid FLEURS@160ms and VP@160ms seed deltas:")
|
| 532 |
+
print(f" {'lang':<4s}{'init':<5s}{'hours':<6s}"
|
| 533 |
+
f"{'FL_s1':>8s}{'FL_s2':>8s}{'ΔFL':>8s}"
|
| 534 |
+
f"{'VP_s1':>8s}{'VP_s2':>8s}{'ΔVP':>8s}")
|
| 535 |
+
fl_abs, vp_abs = [], []
|
| 536 |
+
rows = []
|
| 537 |
+
for lang in ("hr", "pt"):
|
| 538 |
+
for init in ("ml", "enc"):
|
| 539 |
+
for h in HOURS:
|
| 540 |
+
a_fl = wer(d, lang, h, init, "160ms", "fleurs")
|
| 541 |
+
b_fl = wer(d, lang, h, init+"_s45","160ms", "fleurs")
|
| 542 |
+
a_vp = wer(d, lang, h, init, "160ms", "voxpopuli")
|
| 543 |
+
b_vp = wer(d, lang, h, init+"_s45","160ms", "voxpopuli")
|
| 544 |
+
if a_fl is None or b_fl is None:
|
| 545 |
+
continue
|
| 546 |
+
dfl = b_fl - a_fl
|
| 547 |
+
dvp = (b_vp - a_vp) if (a_vp is not None and b_vp is not None) else None
|
| 548 |
+
fl_abs.append(abs(dfl))
|
| 549 |
+
if dvp is not None: vp_abs.append(abs(dvp))
|
| 550 |
+
rows.append((lang, init, h, dfl, dvp))
|
| 551 |
+
print(f" {lang:<4s}{init:<5s}{h:<6s}"
|
| 552 |
+
f"{a_fl:>8.2f}{b_fl:>8.2f}{dfl:>+8.2f}"
|
| 553 |
+
f"{fmt(a_vp,w=8)}{fmt(b_vp,w=8)}{fmt(dvp,signed=True,w=8)}")
|
| 554 |
+
if fl_abs:
|
| 555 |
+
print(f"\n mean |ΔFL| = {sum(fl_abs)/len(fl_abs):.2f} pp"
|
| 556 |
+
f" (n={len(fl_abs)}, max={max(fl_abs):.2f})")
|
| 557 |
+
if vp_abs:
|
| 558 |
+
print(f" mean |ΔVP| = {sum(vp_abs)/len(vp_abs):.2f} pp"
|
| 559 |
+
f" (n={len(vp_abs)}, max={max(vp_abs):.2f})")
|
| 560 |
+
|
| 561 |
+
# (b) 16-cell 100h re-run @ 560 ms (all 8 langs × 2 inits)
|
| 562 |
+
print("\n (b) 100h × 8 langs × 2 inits @ 560 ms (FLEURS, VP):")
|
| 563 |
+
fl, vp = [], []
|
| 564 |
+
cells_fl, cells_vp = [], []
|
| 565 |
+
for lang in LANGS:
|
| 566 |
+
for init in ("ml", "enc"):
|
| 567 |
+
a_fl = wer(d, lang, "100h", init, "560ms", "fleurs")
|
| 568 |
+
b_fl = wer(d, lang, "100h", init+"_s45", "560ms", "fleurs")
|
| 569 |
+
a_vp = wer(d, lang, "100h", init, "560ms", "voxpopuli")
|
| 570 |
+
b_vp = wer(d, lang, "100h", init+"_s45", "560ms", "voxpopuli")
|
| 571 |
+
if a_fl is not None and b_fl is not None:
|
| 572 |
+
fl.append(abs(b_fl - a_fl))
|
| 573 |
+
cells_fl.append((lang, init, b_fl - a_fl))
|
| 574 |
+
if a_vp is not None and b_vp is not None:
|
| 575 |
+
vp.append(abs(b_vp - a_vp))
|
| 576 |
+
cells_vp.append((lang, init, b_vp - a_vp))
|
| 577 |
+
if fl:
|
| 578 |
+
s = sorted(fl)
|
| 579 |
+
worst = max(cells_fl, key=lambda x: abs(x[2]))
|
| 580 |
+
print(f" FLEURS: mean |Δ|={sum(fl)/len(fl):.2f} median={s[len(s)//2]:.2f}"
|
| 581 |
+
f" max={max(fl):.2f} ({worst[0]}-{worst[1]}) n={len(fl)}")
|
| 582 |
+
if vp:
|
| 583 |
+
s = sorted(vp)
|
| 584 |
+
worst = max(cells_vp, key=lambda x: abs(x[2]))
|
| 585 |
+
print(f" VoxPopuli: mean |Δ|={sum(vp)/len(vp):.2f} median={s[len(s)//2]:.2f}"
|
| 586 |
+
f" max={max(vp):.2f} ({worst[0]}-{worst[1]}) n={len(vp)}")
|
| 587 |
+
|
| 588 |
+
# (c) HR-100h FLEURS swing collapse at 560 ms vs 160 ms
|
| 589 |
+
print("\n (c) HR-100h FLEURS seed swing collapse 160 ms → 560 ms:")
|
| 590 |
+
for init in ("ml", "enc"):
|
| 591 |
+
for tier in ("160ms", "560ms"):
|
| 592 |
+
a = wer(d, "hr", "100h", init, tier, "fleurs")
|
| 593 |
+
b = wer(d, "hr", "100h", init+"_s45", tier, "fleurs")
|
| 594 |
+
if a is not None and b is not None:
|
| 595 |
+
print(f" hr-{init:<3s} @ {tier:<6s}: s1={a:.2f} s2={b:.2f} Δ={b-a:+.2f}")
|
| 596 |
+
|
| 597 |
+
# (d) Largest seed-induced EN-ML gap excursion at 100h / 560 ms
|
| 598 |
+
print("\n (d) Seed-induced EN-ML gap excursion at 100h / 560 ms FLEURS:")
|
| 599 |
+
print(f" {'lang':<4s}{'Δ(s1)':>10s}{'Δ(s2)':>10s}{'shift':>10s}{'sign?':>8s}")
|
| 600 |
+
biggest = (None, 0.0)
|
| 601 |
+
for lang in LANGS:
|
| 602 |
+
ml1 = wer(d, lang, "100h", "ml", "560ms", "fleurs")
|
| 603 |
+
en1 = wer(d, lang, "100h", "enc", "560ms", "fleurs")
|
| 604 |
+
ml2 = wer(d, lang, "100h", "ml_s45", "560ms", "fleurs")
|
| 605 |
+
en2 = wer(d, lang, "100h", "enc_s45", "560ms", "fleurs")
|
| 606 |
+
if any(x is None for x in (ml1, en1, ml2, en2)):
|
| 607 |
+
continue
|
| 608 |
+
d1 = en1 - ml1; d2 = en2 - ml2
|
| 609 |
+
sign_keep = "yes" if (d1 >= 0) == (d2 >= 0) else "NO"
|
| 610 |
+
shift = d2 - d1
|
| 611 |
+
print(f" {lang:<4s}{d1:>+10.2f}{d2:>+10.2f}{shift:>+10.2f}{sign_keep:>8s}")
|
| 612 |
+
if abs(shift) > abs(biggest[1]):
|
| 613 |
+
biggest = (lang, shift)
|
| 614 |
+
if biggest[0]:
|
| 615 |
+
print(f" largest shift: {biggest[0]} ({biggest[1]:+.2f} pp)")
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
# ---------------------------------------------------------------------------
|
| 619 |
+
# [13] Streaming penalty per (tier, hours, init) on FLEURS
|
| 620 |
+
# penalty = WER(tier) - WER(offline)
|
| 621 |
+
# ---------------------------------------------------------------------------
|
| 622 |
+
def t_streaming_penalty(d):
|
| 623 |
+
hr("[13] Streaming penalty (FLEURS): WER(tier) - WER(offline)")
|
| 624 |
+
print(f" {'init':<5s}{'tier':<10s}" + "".join(f"{h:>10s}" for h in HOURS))
|
| 625 |
+
for init in ("ml", "enc"):
|
| 626 |
+
for tier in ("160ms", "560ms", "1120ms"):
|
| 627 |
+
row = f" {init:<5s}{tier:<10s}"
|
| 628 |
+
for h in HOURS:
|
| 629 |
+
tier_wers = [wer(d, l, h, init, tier, "fleurs") for l in LANGS]
|
| 630 |
+
off_wers = [wer(d, l, h, init, "offline", "fleurs") for l in LANGS]
|
| 631 |
+
pairs = [(t - o) for t, o in zip(tier_wers, off_wers)
|
| 632 |
+
if t is not None and o is not None]
|
| 633 |
+
m = mean(pairs)
|
| 634 |
+
row += fmt(m, signed=True, w=10)
|
| 635 |
+
print(row)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
# ---------------------------------------------------------------------------
|
| 639 |
+
# [14] tab:per_dataset — 160 ms WER per (lang, hours, init, dataset)
|
| 640 |
+
# ---------------------------------------------------------------------------
|
| 641 |
+
def t_per_dataset(d):
|
| 642 |
+
hr("[14] tab:per_dataset — 160 ms WER per (lang, hours, init, dataset)")
|
| 643 |
+
datasets = ("cv", "mls", "voxpopuli", "fleurs")
|
| 644 |
+
print(f" {'lang':<5s}{'hours':<7s}"
|
| 645 |
+
+ "".join(f"{ds.upper() + ' ml':>10s}{ds.upper() + ' en':>10s}"
|
| 646 |
+
for ds in datasets))
|
| 647 |
+
for lang in LANGS:
|
| 648 |
+
for h in HOURS:
|
| 649 |
+
row = f" {lang:<5s}{h:<7s}"
|
| 650 |
+
for ds in datasets:
|
| 651 |
+
ml = wer(d, lang, h, "ml", "160ms", ds)
|
| 652 |
+
en = wer(d, lang, h, "enc", "160ms", ds)
|
| 653 |
+
row += fmt(ml, w=10) + fmt(en, w=10)
|
| 654 |
+
print(row)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
# ---------------------------------------------------------------------------
|
| 658 |
+
# main
|
| 659 |
+
# ---------------------------------------------------------------------------
|
| 660 |
+
def main(argv):
|
| 661 |
+
src = Path(argv[1]) if len(argv) > 1 else DEFAULT_JSON
|
| 662 |
+
if not src.is_file():
|
| 663 |
+
print(f"error: results file not found: {src}\n"
|
| 664 |
+
f" pass the path to wer_results.json as the first argument.",
|
| 665 |
+
file=sys.stderr)
|
| 666 |
+
return 2
|
| 667 |
+
d = json.loads(src.read_text())
|
| 668 |
+
print(f"Reading {src}")
|
| 669 |
+
t_main160(d)
|
| 670 |
+
t_seen_unseen(d)
|
| 671 |
+
t_latency_effect(d)
|
| 672 |
+
t_abs_wer(d)
|
| 673 |
+
t_lst(d)
|
| 674 |
+
t_from_pl(d)
|
| 675 |
+
t_reinitjoint(d)
|
| 676 |
+
t_quant(d)
|
| 677 |
+
t_es_5000h(d)
|
| 678 |
+
t_powerlaw(d)
|
| 679 |
+
t_hybrid(d)
|
| 680 |
+
t_seed(d)
|
| 681 |
+
t_streaming_penalty(d)
|
| 682 |
+
t_per_dataset(d)
|
| 683 |
+
return 0
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
if __name__ == "__main__":
|
| 687 |
+
sys.exit(main(sys.argv))
|
paper/wer_results.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Minimal suggested environment for the released scripts.
|
| 2 |
+
#
|
| 3 |
+
# This is intentionally not a full pip freeze / exact reproduction of the
|
| 4 |
+
# authors' local environment. CUDA, PyTorch and NeMo stacks can be
|
| 5 |
+
# platform-specific, so this file lists only the main direct dependencies
|
| 6 |
+
# needed to understand and run the code in a typical setup.
|
| 7 |
+
#
|
| 8 |
+
# Core training / .nemo evaluation dependencies
|
| 9 |
+
nemo_toolkit[asr]==2.6.2
|
| 10 |
+
numpy
|
| 11 |
+
torch
|
| 12 |
+
tqdm
|
| 13 |
+
soundfile
|
| 14 |
+
jiwer
|
| 15 |
+
sentencepiece
|
| 16 |
+
omegaconf
|
| 17 |
+
|
| 18 |
+
# Used by eval_fleurs.py
|
| 19 |
+
datasets
|
| 20 |
+
|
| 21 |
+
# Used by onnx_eval/eval_fleurs_onnx.py
|
| 22 |
+
onnxruntime-genai
|
| 23 |
+
|
| 24 |
+
# Note: the WER normalization code is imported from a clone of
|
| 25 |
+
# huggingface/open_asr_leaderboard via OPEN_ASR_LB_ROOT or PYTHONPATH.
|
train_multilingual_nemotron.py
ADDED
|
@@ -0,0 +1,1029 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_multilingual_nemotron.py
|
| 4 |
+
|
| 5 |
+
Multi-GPU training of Nemotron-Speech-Streaming for 5 European languages.
|
| 6 |
+
Based on distill_parakeet_to_nemotron_german.py, adapted for:
|
| 7 |
+
- Multi-GPU (torchrun + DDP)
|
| 8 |
+
- Multilingual (DE, ES, FR, IT, NL combined manifest)
|
| 9 |
+
- No distillation by default (Stage 1 = pure RNNT fine-tuning)
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
# Multilingual baseline (7 GPUs)
|
| 13 |
+
torchrun --nproc_per_node=7 train_multilingual_nemotron.py \
|
| 14 |
+
--train_manifest <DATA_ROOT>/combined_train.json \
|
| 15 |
+
--val_manifest <VAL_MANIFEST> \
|
| 16 |
+
--output_dir ./multilingual_baseline \
|
| 17 |
+
--epochs 30 --batch_size 32 --grad_accum 2 --lr 1e-4
|
| 18 |
+
|
| 19 |
+
Manifest format (one JSON object per line):
|
| 20 |
+
{"audio_filepath": "/abs/path/utt.wav", "duration": 8.4, "text": "reference transcript"}
|
| 21 |
+
`duration` (seconds) is required for min/max-duration filtering.
|
| 22 |
+
|
| 23 |
+
Requirements:
|
| 24 |
+
pip install nemo_toolkit[asr] soundfile jiwer tqdm
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import json
|
| 29 |
+
import math
|
| 30 |
+
import os
|
| 31 |
+
import random
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
import unicodedata
|
| 35 |
+
from collections import defaultdict
|
| 36 |
+
|
| 37 |
+
import numpy as np
|
| 38 |
+
import torch
|
| 39 |
+
import torch.distributed as dist
|
| 40 |
+
import torch.nn as nn
|
| 41 |
+
import torch.nn.functional as F
|
| 42 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 43 |
+
from torch.utils.data import DataLoader, DistributedSampler
|
| 44 |
+
from tqdm import tqdm
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# ═══════════════════════════════════════════════════════════
|
| 48 |
+
# DDP Utilities
|
| 49 |
+
# ═══════════════════════════════════════════════════════════
|
| 50 |
+
|
| 51 |
+
def setup_ddp():
|
| 52 |
+
"""Initialize distributed training. Returns (rank, world_size, is_distributed)."""
|
| 53 |
+
if "RANK" in os.environ:
|
| 54 |
+
rank = int(os.environ["RANK"])
|
| 55 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 56 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 57 |
+
dist.init_process_group("nccl")
|
| 58 |
+
torch.cuda.set_device(local_rank)
|
| 59 |
+
return rank, world_size, local_rank, True
|
| 60 |
+
else:
|
| 61 |
+
return 0, 1, 0, False
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def cleanup_ddp(is_distributed):
|
| 65 |
+
if is_distributed:
|
| 66 |
+
dist.destroy_process_group()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def is_main(rank):
|
| 70 |
+
return rank == 0
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def print_rank0(msg, rank=0):
|
| 74 |
+
if is_main(rank):
|
| 75 |
+
print(msg, flush=True)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ═══════════════════════════════════════════════════════════
|
| 79 |
+
# Configuration
|
| 80 |
+
# ═══════════════════════════════════════════════════════════
|
| 81 |
+
|
| 82 |
+
def parse_args():
|
| 83 |
+
p = argparse.ArgumentParser(
|
| 84 |
+
description="Multi-GPU Nemotron Streaming ASR Training (Multilingual)",
|
| 85 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 86 |
+
)
|
| 87 |
+
# Models
|
| 88 |
+
p.add_argument("--teacher", default="nvidia/parakeet-tdt-0.6b-v3",
|
| 89 |
+
help="Teacher model for tokenizer extraction")
|
| 90 |
+
p.add_argument("--student", default="nvidia/nemotron-speech-streaming-en-0.6b",
|
| 91 |
+
help="Student model (English, streaming)")
|
| 92 |
+
|
| 93 |
+
# Data — manifests directly
|
| 94 |
+
p.add_argument("--train_manifest", type=str, required=True,
|
| 95 |
+
help="Path to combined training manifest (JSONL)")
|
| 96 |
+
p.add_argument("--val_manifest", type=str, default=None,
|
| 97 |
+
help="Path to combined validation manifest (for best model selection)")
|
| 98 |
+
p.add_argument("--eval_dir", type=str, default=None,
|
| 99 |
+
help="Optional: base dir containing per-language eval/ dirs with "
|
| 100 |
+
"validation_manifest.json (used for the per-language WER "
|
| 101 |
+
"printout at eval time). Skipped if not set.")
|
| 102 |
+
|
| 103 |
+
# Training
|
| 104 |
+
p.add_argument("--output_dir", default="./multilingual_nemotron")
|
| 105 |
+
p.add_argument("--epochs", type=int, default=30)
|
| 106 |
+
p.add_argument("--batch_size", type=int, default=32,
|
| 107 |
+
help="Per-GPU batch size")
|
| 108 |
+
p.add_argument("--grad_accum", type=int, default=2,
|
| 109 |
+
help="Gradient accumulation steps")
|
| 110 |
+
p.add_argument("--lr", type=float, default=1e-4)
|
| 111 |
+
p.add_argument("--min_lr", type=float, default=4e-6)
|
| 112 |
+
p.add_argument("--weight_decay", type=float, default=1e-3)
|
| 113 |
+
p.add_argument("--warmup_epochs", type=int, default=1)
|
| 114 |
+
p.add_argument("--max_duration", type=float, default=20.0)
|
| 115 |
+
p.add_argument("--min_duration", type=float, default=0.3)
|
| 116 |
+
|
| 117 |
+
# SpecAugment
|
| 118 |
+
p.add_argument("--no_spec_augment", action="store_true", default=False)
|
| 119 |
+
p.add_argument("--freq_masks", type=int, default=2)
|
| 120 |
+
p.add_argument("--freq_width", type=int, default=27)
|
| 121 |
+
p.add_argument("--time_masks", type=int, default=10)
|
| 122 |
+
p.add_argument("--time_width", type=float, default=0.05)
|
| 123 |
+
|
| 124 |
+
# Speed perturbation
|
| 125 |
+
p.add_argument("--speed_perturb", action="store_true", default=True)
|
| 126 |
+
p.add_argument("--speed_perturb_factors", type=float, nargs='+', default=[0.9, 1.0, 1.1])
|
| 127 |
+
|
| 128 |
+
# Misc
|
| 129 |
+
p.add_argument("--freeze_encoder_epochs", type=int, default=0,
|
| 130 |
+
help="Freeze encoder for first N epochs")
|
| 131 |
+
p.add_argument("--constant_lr", action="store_true", default=False)
|
| 132 |
+
p.add_argument("--log_every", type=int, default=50)
|
| 133 |
+
p.add_argument("--eval_every_epoch", type=int, default=1)
|
| 134 |
+
p.add_argument("--save_every_epoch", type=int, default=5)
|
| 135 |
+
p.add_argument("--early_stop_patience", type=int, default=3,
|
| 136 |
+
help="Stop if WER doesn't improve for N evals (0=disabled)")
|
| 137 |
+
p.add_argument("--fp16", action="store_true", default=True)
|
| 138 |
+
p.add_argument("--num_workers", type=int, default=4)
|
| 139 |
+
p.add_argument("--seed", type=int, default=42)
|
| 140 |
+
p.add_argument("--resume_from", type=str, default=None,
|
| 141 |
+
help="Resume from .nemo checkpoint (skips tokenizer swap)")
|
| 142 |
+
|
| 143 |
+
return p.parse_args()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# ═══════════════════════════════════════════════════════════
|
| 147 |
+
# Tokenizer Extraction (from teacher)
|
| 148 |
+
# ═══════════════════════════════════════════════════════════
|
| 149 |
+
|
| 150 |
+
def extract_tokenizer(model, tokenizer_dir):
|
| 151 |
+
"""Extract tokenizer .model file from a NeMo ASR model."""
|
| 152 |
+
from pathlib import Path
|
| 153 |
+
import tarfile
|
| 154 |
+
|
| 155 |
+
os.makedirs(tokenizer_dir, exist_ok=True)
|
| 156 |
+
out_model = Path(tokenizer_dir) / "tokenizer.model"
|
| 157 |
+
|
| 158 |
+
tok = getattr(model, "tokenizer", None)
|
| 159 |
+
sp = getattr(tok, "tokenizer", None)
|
| 160 |
+
|
| 161 |
+
if sp is not None and hasattr(sp, "serialized_model_proto"):
|
| 162 |
+
blob = sp.serialized_model_proto()
|
| 163 |
+
if blob:
|
| 164 |
+
out_model.write_bytes(blob)
|
| 165 |
+
_generate_vocab_txt(tokenizer_dir)
|
| 166 |
+
vs = getattr(sp, "vocab_size", None)
|
| 167 |
+
if callable(vs):
|
| 168 |
+
vs = vs()
|
| 169 |
+
return str(Path(tokenizer_dir)), int(vs) if vs else 0
|
| 170 |
+
|
| 171 |
+
raise RuntimeError("Could not extract tokenizer from teacher model")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _generate_vocab_txt(tokenizer_dir):
|
| 175 |
+
import sentencepiece as spm_lib
|
| 176 |
+
model_path = os.path.join(tokenizer_dir, "tokenizer.model")
|
| 177 |
+
vocab_path = os.path.join(tokenizer_dir, "vocab.txt")
|
| 178 |
+
if os.path.exists(vocab_path):
|
| 179 |
+
return
|
| 180 |
+
sp = spm_lib.SentencePieceProcessor()
|
| 181 |
+
sp.load(model_path)
|
| 182 |
+
with open(vocab_path, "w", encoding="utf-8") as f:
|
| 183 |
+
for i in range(sp.get_piece_size()):
|
| 184 |
+
f.write(sp.id_to_piece(i) + "\n")
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ═══════════════════════════════════════════════════════════
|
| 188 |
+
# Model Setup
|
| 189 |
+
# ═══════════════════════════════════════════════════════════
|
| 190 |
+
|
| 191 |
+
def setup_spec_augment(student, args):
|
| 192 |
+
from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation
|
| 193 |
+
|
| 194 |
+
if args.no_spec_augment:
|
| 195 |
+
student.spec_augmentation = None
|
| 196 |
+
return
|
| 197 |
+
|
| 198 |
+
spec_aug = SpectrogramAugmentation(
|
| 199 |
+
freq_masks=args.freq_masks,
|
| 200 |
+
time_masks=args.time_masks,
|
| 201 |
+
freq_width=args.freq_width,
|
| 202 |
+
time_width=args.time_width,
|
| 203 |
+
)
|
| 204 |
+
student.spec_augmentation = spec_aug.to(next(student.parameters()).device)
|
| 205 |
+
|
| 206 |
+
from omegaconf import open_dict
|
| 207 |
+
with open_dict(student.cfg):
|
| 208 |
+
student.cfg.spec_augment.freq_masks = args.freq_masks
|
| 209 |
+
student.cfg.spec_augment.time_masks = args.time_masks
|
| 210 |
+
student.cfg.spec_augment.freq_width = args.freq_width
|
| 211 |
+
student.cfg.spec_augment.time_width = args.time_width
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def load_student(args, device, rank):
|
| 215 |
+
"""Load student model, optionally swap tokenizer."""
|
| 216 |
+
import nemo.collections.asr as nemo_asr
|
| 217 |
+
|
| 218 |
+
if args.resume_from:
|
| 219 |
+
print_rank0(f" Resuming student from: {args.resume_from}", rank)
|
| 220 |
+
student = nemo_asr.models.ASRModel.restore_from(args.resume_from, map_location='cpu')
|
| 221 |
+
print_rank0(f" Student vocab: {student.tokenizer.vocab_size} tokens", rank)
|
| 222 |
+
args.freeze_encoder_epochs = 0
|
| 223 |
+
else:
|
| 224 |
+
# Extract teacher tokenizer (only rank 0 does this, then all read from disk)
|
| 225 |
+
tokenizer_dir = os.path.join(args.output_dir, "teacher_tokenizer")
|
| 226 |
+
if is_main(rank):
|
| 227 |
+
print_rank0(f" Loading teacher for tokenizer: {args.teacher}", rank)
|
| 228 |
+
teacher = nemo_asr.models.ASRModel.from_pretrained(args.teacher)
|
| 229 |
+
tokenizer_dir, teacher_vocab_size = extract_tokenizer(teacher, tokenizer_dir)
|
| 230 |
+
print_rank0(f" Teacher vocab: {teacher_vocab_size}", rank)
|
| 231 |
+
del teacher
|
| 232 |
+
torch.cuda.empty_cache()
|
| 233 |
+
|
| 234 |
+
if dist.is_initialized():
|
| 235 |
+
dist.barrier()
|
| 236 |
+
|
| 237 |
+
# Load student
|
| 238 |
+
print_rank0(f" Loading student: {args.student}", rank)
|
| 239 |
+
student = nemo_asr.models.ASRModel.from_pretrained(args.student)
|
| 240 |
+
|
| 241 |
+
old_vocab = student.tokenizer.vocab_size
|
| 242 |
+
student.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type="bpe")
|
| 243 |
+
new_vocab = student.tokenizer.vocab_size
|
| 244 |
+
print_rank0(f" Tokenizer swap: {old_vocab} → {new_vocab}", rank)
|
| 245 |
+
|
| 246 |
+
student = student.to(device)
|
| 247 |
+
|
| 248 |
+
# SpecAugment
|
| 249 |
+
setup_spec_augment(student, args)
|
| 250 |
+
|
| 251 |
+
# Disable CUDA graphs and typecheck
|
| 252 |
+
from omegaconf import open_dict
|
| 253 |
+
from nemo.core.classes.common import typecheck
|
| 254 |
+
typecheck.set_typecheck_enabled(False)
|
| 255 |
+
with open_dict(student.cfg):
|
| 256 |
+
student.cfg.decoding.greedy.use_cuda_graph_decoder = False
|
| 257 |
+
student.change_decoding_strategy(student.cfg.decoding)
|
| 258 |
+
|
| 259 |
+
params = sum(p.numel() for p in student.parameters()) / 1e6
|
| 260 |
+
print_rank0(f" Student params: {params:.1f}M", rank)
|
| 261 |
+
|
| 262 |
+
return student
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# ═══════════════════════════════════════════════════════════
|
| 266 |
+
# Dataset & DataLoader
|
| 267 |
+
# ═══════════════════════════════════════════════════════════
|
| 268 |
+
|
| 269 |
+
class ASRManifestDataset(torch.utils.data.Dataset):
|
| 270 |
+
def __init__(self, manifest_path, tokenizer, min_duration=0.3, max_duration=20.0,
|
| 271 |
+
speed_perturb=False, speed_perturb_factors=None):
|
| 272 |
+
self.tokenizer = tokenizer
|
| 273 |
+
self.speed_perturb = speed_perturb
|
| 274 |
+
self.speed_perturb_factors = speed_perturb_factors or [0.9, 1.0, 1.1]
|
| 275 |
+
self.samples = []
|
| 276 |
+
|
| 277 |
+
with open(manifest_path) as f:
|
| 278 |
+
for line in f:
|
| 279 |
+
item = json.loads(line)
|
| 280 |
+
dur = item["duration"]
|
| 281 |
+
if min_duration <= dur <= max_duration:
|
| 282 |
+
self.samples.append(item)
|
| 283 |
+
|
| 284 |
+
def __len__(self):
|
| 285 |
+
return len(self.samples)
|
| 286 |
+
|
| 287 |
+
def __getitem__(self, idx):
|
| 288 |
+
import soundfile as sf
|
| 289 |
+
item = self.samples[idx]
|
| 290 |
+
try:
|
| 291 |
+
audio, sr = sf.read(item["audio_filepath"], dtype="float32")
|
| 292 |
+
except Exception as e:
|
| 293 |
+
print(f" Corrupt audio: {item['audio_filepath']} ({e})", flush=True)
|
| 294 |
+
return None
|
| 295 |
+
|
| 296 |
+
if sr != 16000:
|
| 297 |
+
ratio = 16000 / sr
|
| 298 |
+
new_len = int(len(audio) * ratio)
|
| 299 |
+
audio = np.interp(
|
| 300 |
+
np.linspace(0, len(audio) - 1, new_len),
|
| 301 |
+
np.arange(len(audio)), audio,
|
| 302 |
+
).astype(np.float32)
|
| 303 |
+
|
| 304 |
+
# Speed perturbation
|
| 305 |
+
if self.speed_perturb:
|
| 306 |
+
import random
|
| 307 |
+
speed = random.choice(self.speed_perturb_factors)
|
| 308 |
+
if speed != 1.0:
|
| 309 |
+
new_len = int(len(audio) / speed)
|
| 310 |
+
audio = np.interp(
|
| 311 |
+
np.linspace(0, len(audio) - 1, new_len),
|
| 312 |
+
np.arange(len(audio)), audio,
|
| 313 |
+
).astype(np.float32)
|
| 314 |
+
|
| 315 |
+
audio_tensor = torch.FloatTensor(audio)
|
| 316 |
+
|
| 317 |
+
text = unicodedata.normalize("NFKC", item["text"])
|
| 318 |
+
text = " ".join(text.split())
|
| 319 |
+
tokens = torch.LongTensor(self.tokenizer.text_to_ids(text))
|
| 320 |
+
|
| 321 |
+
return audio_tensor, tokens
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def collate_asr(batch):
|
| 325 |
+
batch = [b for b in batch if b is not None]
|
| 326 |
+
if len(batch) == 0:
|
| 327 |
+
return None
|
| 328 |
+
audios = [b[0] for b in batch]
|
| 329 |
+
tokens_list = [b[1] for b in batch]
|
| 330 |
+
|
| 331 |
+
audio_lens = torch.LongTensor([len(a) for a in audios])
|
| 332 |
+
token_lens = torch.LongTensor([len(t) for t in tokens_list])
|
| 333 |
+
|
| 334 |
+
max_audio = audio_lens.max().item()
|
| 335 |
+
max_tokens = token_lens.max().item()
|
| 336 |
+
B = len(audios)
|
| 337 |
+
|
| 338 |
+
padded_audio = torch.zeros(B, max_audio)
|
| 339 |
+
padded_tokens = torch.zeros(B, max_tokens, dtype=torch.long)
|
| 340 |
+
|
| 341 |
+
for i in range(B):
|
| 342 |
+
padded_audio[i, :audio_lens[i]] = audios[i]
|
| 343 |
+
padded_tokens[i, :token_lens[i]] = tokens_list[i]
|
| 344 |
+
|
| 345 |
+
return padded_audio, audio_lens, padded_tokens, token_lens
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ═══════════════════════════════════════════════════════════
|
| 349 |
+
# Training Step
|
| 350 |
+
# ═══════════════════════════════════════════════════════════
|
| 351 |
+
|
| 352 |
+
def train_step(student, batch, device):
|
| 353 |
+
"""Single forward/backward step: RNNT loss only."""
|
| 354 |
+
audio, audio_len, tokens, token_len = batch
|
| 355 |
+
audio = audio.to(device)
|
| 356 |
+
audio_len = audio_len.to(device)
|
| 357 |
+
tokens = tokens.to(device)
|
| 358 |
+
token_len = token_len.to(device)
|
| 359 |
+
|
| 360 |
+
# Get underlying model if wrapped in DDP
|
| 361 |
+
model = student.module if isinstance(student, DDP) else student
|
| 362 |
+
|
| 363 |
+
# Mel spectrogram
|
| 364 |
+
mel, mel_len = model.preprocessor(input_signal=audio, length=audio_len)
|
| 365 |
+
|
| 366 |
+
# Spec augmentation
|
| 367 |
+
if model.spec_augmentation is not None and model.training:
|
| 368 |
+
mel = model.spec_augmentation(input_spec=mel, length=mel_len)
|
| 369 |
+
|
| 370 |
+
# Encoder
|
| 371 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 372 |
+
|
| 373 |
+
# Decoder
|
| 374 |
+
dec_out = model.decoder(targets=tokens, target_length=token_len)
|
| 375 |
+
if isinstance(dec_out, tuple):
|
| 376 |
+
dec_out = dec_out[0]
|
| 377 |
+
|
| 378 |
+
# Joint + RNNT loss
|
| 379 |
+
if getattr(model.joint, 'fuse_loss_wer', False):
|
| 380 |
+
result = model.joint(
|
| 381 |
+
encoder_outputs=enc, decoder_outputs=dec_out,
|
| 382 |
+
encoder_lengths=enc_len, transcripts=tokens,
|
| 383 |
+
transcript_lengths=token_len, compute_wer=False,
|
| 384 |
+
)
|
| 385 |
+
loss = result[0]
|
| 386 |
+
else:
|
| 387 |
+
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
|
| 388 |
+
loss = model.loss(
|
| 389 |
+
log_probs=joint_out, targets=tokens,
|
| 390 |
+
input_lengths=enc_len, target_lengths=token_len,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# Ensure loss is scalar
|
| 394 |
+
if loss.dim() > 0:
|
| 395 |
+
loss = loss.mean()
|
| 396 |
+
|
| 397 |
+
return loss
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# ═══════════════════════════════════════════════════════════
|
| 401 |
+
# Evaluation
|
| 402 |
+
# ═══════════════════════════════════════════════════════════
|
| 403 |
+
|
| 404 |
+
@torch.no_grad()
|
| 405 |
+
def evaluate(student, manifest_path, device, max_samples=None):
|
| 406 |
+
"""Evaluate WER using streaming inference."""
|
| 407 |
+
import soundfile as sf_eval
|
| 408 |
+
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
|
| 409 |
+
|
| 410 |
+
model = student.module if isinstance(student, DDP) else student
|
| 411 |
+
model.eval()
|
| 412 |
+
|
| 413 |
+
def normalize_text(text):
|
| 414 |
+
text = unicodedata.normalize('NFKC', text)
|
| 415 |
+
text = text.lower()
|
| 416 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 417 |
+
return ' '.join(text.split())
|
| 418 |
+
|
| 419 |
+
def simple_wer(ref_words, hyp_words):
|
| 420 |
+
n, m = len(ref_words), len(hyp_words)
|
| 421 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 422 |
+
for i in range(n + 1): dp[i][0] = i
|
| 423 |
+
for j in range(m + 1): dp[0][j] = j
|
| 424 |
+
for i in range(1, n + 1):
|
| 425 |
+
for j in range(1, m + 1):
|
| 426 |
+
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
|
| 427 |
+
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
|
| 428 |
+
return dp[n][m]
|
| 429 |
+
|
| 430 |
+
right_context = 13
|
| 431 |
+
chunk_frames = 1 + right_context
|
| 432 |
+
model.encoder.setup_streaming_params(
|
| 433 |
+
chunk_size=chunk_frames,
|
| 434 |
+
shift_size=chunk_frames,
|
| 435 |
+
left_chunks=70 // max(chunk_frames, 1),
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
samples = []
|
| 439 |
+
with open(manifest_path) as f:
|
| 440 |
+
for line in f:
|
| 441 |
+
samples.append(json.loads(line))
|
| 442 |
+
if max_samples and len(samples) > max_samples:
|
| 443 |
+
samples = samples[:max_samples]
|
| 444 |
+
|
| 445 |
+
total_edits, total_words = 0, 0
|
| 446 |
+
examples = []
|
| 447 |
+
errors = 0
|
| 448 |
+
|
| 449 |
+
for s in samples:
|
| 450 |
+
try:
|
| 451 |
+
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
|
| 452 |
+
if len(audio.shape) > 1:
|
| 453 |
+
audio = audio.mean(axis=1)
|
| 454 |
+
|
| 455 |
+
buffer = CacheAwareStreamingAudioBuffer(model=model)
|
| 456 |
+
buffer.append_audio(audio)
|
| 457 |
+
|
| 458 |
+
cache_last_channel, cache_last_time, cache_last_channel_len = \
|
| 459 |
+
model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
|
| 460 |
+
previous_hypotheses = None
|
| 461 |
+
pred = ""
|
| 462 |
+
|
| 463 |
+
for chunk_audio, chunk_len in buffer:
|
| 464 |
+
if chunk_audio is None:
|
| 465 |
+
break
|
| 466 |
+
result = model.conformer_stream_step(
|
| 467 |
+
processed_signal=chunk_audio,
|
| 468 |
+
processed_signal_length=chunk_len,
|
| 469 |
+
cache_last_channel=cache_last_channel,
|
| 470 |
+
cache_last_time=cache_last_time,
|
| 471 |
+
cache_last_channel_len=cache_last_channel_len,
|
| 472 |
+
previous_hypotheses=previous_hypotheses,
|
| 473 |
+
return_transcription=True,
|
| 474 |
+
)
|
| 475 |
+
if isinstance(result, tuple) and len(result) >= 6:
|
| 476 |
+
cache_last_channel = result[2]
|
| 477 |
+
cache_last_time = result[3]
|
| 478 |
+
cache_last_channel_len = result[4]
|
| 479 |
+
previous_hypotheses = result[5]
|
| 480 |
+
if result[5] and len(result[5]) > 0:
|
| 481 |
+
hyp = result[5][0]
|
| 482 |
+
new_text = ""
|
| 483 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 484 |
+
new_text = hyp.text
|
| 485 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 486 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 487 |
+
if tids:
|
| 488 |
+
new_text = model.tokenizer.ids_to_text(tids)
|
| 489 |
+
if new_text and len(new_text) > len(pred):
|
| 490 |
+
pred = new_text
|
| 491 |
+
|
| 492 |
+
ref_n = normalize_text(s["text"])
|
| 493 |
+
pred_n = normalize_text(pred)
|
| 494 |
+
ref_words = ref_n.split()
|
| 495 |
+
pred_words = pred_n.split()
|
| 496 |
+
|
| 497 |
+
if ref_words:
|
| 498 |
+
edits = simple_wer(ref_words, pred_words)
|
| 499 |
+
total_edits += edits
|
| 500 |
+
total_words += len(ref_words)
|
| 501 |
+
|
| 502 |
+
if len(examples) < 5:
|
| 503 |
+
examples.append((s["text"][:55], pred[:55]))
|
| 504 |
+
|
| 505 |
+
except Exception as e:
|
| 506 |
+
errors += 1
|
| 507 |
+
if errors <= 3:
|
| 508 |
+
print(f" [eval error] {type(e).__name__}: {e}")
|
| 509 |
+
|
| 510 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 511 |
+
|
| 512 |
+
print(f"\n {'Reference':<55} | {'Prediction':<55}")
|
| 513 |
+
print(f" {'-'*55} | {'-'*55}")
|
| 514 |
+
for ref, pred in examples:
|
| 515 |
+
print(f" {ref:<55} | {pred:<55}")
|
| 516 |
+
if errors:
|
| 517 |
+
print(f" ({errors} samples failed)")
|
| 518 |
+
|
| 519 |
+
model.train()
|
| 520 |
+
return wer_score
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@torch.no_grad()
|
| 524 |
+
def evaluate_batch(student, manifest_path, device, max_samples=None):
|
| 525 |
+
"""Evaluate WER using batch (non-streaming) inference."""
|
| 526 |
+
import soundfile as sf_eval
|
| 527 |
+
|
| 528 |
+
model = student.module if isinstance(student, DDP) else student
|
| 529 |
+
model.eval()
|
| 530 |
+
|
| 531 |
+
def normalize_text(text):
|
| 532 |
+
text = unicodedata.normalize('NFKC', text)
|
| 533 |
+
text = text.lower()
|
| 534 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 535 |
+
return ' '.join(text.split())
|
| 536 |
+
|
| 537 |
+
def simple_wer(ref_words, hyp_words):
|
| 538 |
+
n, m = len(ref_words), len(hyp_words)
|
| 539 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 540 |
+
for i in range(n + 1): dp[i][0] = i
|
| 541 |
+
for j in range(m + 1): dp[0][j] = j
|
| 542 |
+
for i in range(1, n + 1):
|
| 543 |
+
for j in range(1, m + 1):
|
| 544 |
+
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
|
| 545 |
+
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
|
| 546 |
+
return dp[n][m]
|
| 547 |
+
|
| 548 |
+
samples = []
|
| 549 |
+
with open(manifest_path) as f:
|
| 550 |
+
for line in f:
|
| 551 |
+
samples.append(json.loads(line))
|
| 552 |
+
if max_samples and len(samples) > max_samples:
|
| 553 |
+
samples = samples[:max_samples]
|
| 554 |
+
|
| 555 |
+
total_edits, total_words = 0, 0
|
| 556 |
+
errors = 0
|
| 557 |
+
batch_size = 16
|
| 558 |
+
|
| 559 |
+
for start in range(0, len(samples), batch_size):
|
| 560 |
+
batch_samples = samples[start:start + batch_size]
|
| 561 |
+
try:
|
| 562 |
+
audios = []
|
| 563 |
+
for s in batch_samples:
|
| 564 |
+
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
|
| 565 |
+
if len(audio.shape) > 1:
|
| 566 |
+
audio = audio.mean(axis=1)
|
| 567 |
+
audios.append(torch.FloatTensor(audio))
|
| 568 |
+
|
| 569 |
+
audio_lens = torch.LongTensor([len(a) for a in audios])
|
| 570 |
+
max_len = audio_lens.max().item()
|
| 571 |
+
padded = torch.zeros(len(audios), max_len)
|
| 572 |
+
for i, a in enumerate(audios):
|
| 573 |
+
padded[i, :len(a)] = a
|
| 574 |
+
|
| 575 |
+
padded = padded.to(device)
|
| 576 |
+
audio_lens = audio_lens.to(device)
|
| 577 |
+
|
| 578 |
+
mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
|
| 579 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 580 |
+
|
| 581 |
+
# Greedy decode
|
| 582 |
+
best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
|
| 583 |
+
if isinstance(best_hyps, tuple):
|
| 584 |
+
best_hyps = best_hyps[0]
|
| 585 |
+
|
| 586 |
+
for s, hyp in zip(batch_samples, best_hyps):
|
| 587 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 588 |
+
pred = hyp.text
|
| 589 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 590 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 591 |
+
pred = model.tokenizer.ids_to_text(tids) if tids else ""
|
| 592 |
+
else:
|
| 593 |
+
pred = str(hyp)
|
| 594 |
+
|
| 595 |
+
ref_n = normalize_text(s["text"])
|
| 596 |
+
pred_n = normalize_text(pred)
|
| 597 |
+
ref_words = ref_n.split()
|
| 598 |
+
pred_words = pred_n.split()
|
| 599 |
+
if ref_words:
|
| 600 |
+
total_edits += simple_wer(ref_words, pred_words)
|
| 601 |
+
total_words += len(ref_words)
|
| 602 |
+
except Exception as e:
|
| 603 |
+
errors += 1
|
| 604 |
+
if errors <= 3:
|
| 605 |
+
print(f" [batch eval error] {type(e).__name__}: {e}")
|
| 606 |
+
|
| 607 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 608 |
+
if errors:
|
| 609 |
+
print(f" ({errors} batch eval errors)")
|
| 610 |
+
model.train()
|
| 611 |
+
return wer_score
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
@torch.no_grad()
|
| 615 |
+
def compute_val_loss(student, manifest_path, device, max_samples=500):
|
| 616 |
+
"""Compute RNNT loss on validation set (no decoding, fast)."""
|
| 617 |
+
import soundfile as sf_val
|
| 618 |
+
|
| 619 |
+
model = student.module if isinstance(student, DDP) else student
|
| 620 |
+
model.eval()
|
| 621 |
+
|
| 622 |
+
samples = []
|
| 623 |
+
with open(manifest_path) as f:
|
| 624 |
+
for line in f:
|
| 625 |
+
samples.append(json.loads(line))
|
| 626 |
+
if max_samples and len(samples) > max_samples:
|
| 627 |
+
samples = samples[:max_samples]
|
| 628 |
+
|
| 629 |
+
total_loss = 0.0
|
| 630 |
+
count = 0
|
| 631 |
+
|
| 632 |
+
for s in samples:
|
| 633 |
+
try:
|
| 634 |
+
audio, sr = sf_val.read(s["audio_filepath"], dtype="float32")
|
| 635 |
+
if len(audio.shape) > 1:
|
| 636 |
+
audio = audio.mean(axis=1)
|
| 637 |
+
|
| 638 |
+
text = unicodedata.normalize("NFKC", s["text"])
|
| 639 |
+
text = " ".join(text.split())
|
| 640 |
+
tokens = model.tokenizer.text_to_ids(text)
|
| 641 |
+
if not tokens:
|
| 642 |
+
continue
|
| 643 |
+
|
| 644 |
+
audio_tensor = torch.FloatTensor(audio).unsqueeze(0).to(device)
|
| 645 |
+
audio_len = torch.LongTensor([len(audio)]).to(device)
|
| 646 |
+
token_tensor = torch.LongTensor([tokens]).to(device)
|
| 647 |
+
token_len = torch.LongTensor([len(tokens)]).to(device)
|
| 648 |
+
|
| 649 |
+
mel, mel_len = model.preprocessor(input_signal=audio_tensor, length=audio_len)
|
| 650 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 651 |
+
dec_out = model.decoder(targets=token_tensor, target_length=token_len)
|
| 652 |
+
if isinstance(dec_out, tuple):
|
| 653 |
+
dec_out = dec_out[0]
|
| 654 |
+
|
| 655 |
+
if getattr(model.joint, 'fuse_loss_wer', False):
|
| 656 |
+
result = model.joint(
|
| 657 |
+
encoder_outputs=enc, decoder_outputs=dec_out,
|
| 658 |
+
encoder_lengths=enc_len, transcripts=token_tensor,
|
| 659 |
+
transcript_lengths=token_len, compute_wer=False,
|
| 660 |
+
)
|
| 661 |
+
loss = result[0]
|
| 662 |
+
else:
|
| 663 |
+
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
|
| 664 |
+
loss = model.loss(log_probs=joint_out, targets=token_tensor,
|
| 665 |
+
input_lengths=enc_len, target_lengths=token_len)
|
| 666 |
+
|
| 667 |
+
if loss.dim() > 0:
|
| 668 |
+
loss = loss.mean()
|
| 669 |
+
total_loss += loss.item()
|
| 670 |
+
count += 1
|
| 671 |
+
except Exception:
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
model.train()
|
| 675 |
+
return total_loss / max(count, 1)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
# ═══════════════════════════════════════════════════════════
|
| 679 |
+
# LR Schedule
|
| 680 |
+
# ═══════════════════════════════════════════════════════════
|
| 681 |
+
|
| 682 |
+
def get_cosine_schedule(optimizer, warmup_steps, total_steps, min_lr=5e-6):
|
| 683 |
+
base_lr = optimizer.defaults["lr"]
|
| 684 |
+
|
| 685 |
+
def lr_lambda(step):
|
| 686 |
+
if step < warmup_steps:
|
| 687 |
+
return max(1e-8 / base_lr, step / max(1, warmup_steps))
|
| 688 |
+
progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
|
| 689 |
+
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 690 |
+
return max(min_lr / base_lr, cosine)
|
| 691 |
+
|
| 692 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def get_constant_schedule(optimizer, warmup_steps):
|
| 696 |
+
base_lr = optimizer.defaults["lr"]
|
| 697 |
+
|
| 698 |
+
def lr_lambda(step):
|
| 699 |
+
if step < warmup_steps:
|
| 700 |
+
return max(1e-8 / base_lr, step / max(1, warmup_steps))
|
| 701 |
+
return 1.0
|
| 702 |
+
|
| 703 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
# ═══════════════════════════════════════════════════════════
|
| 707 |
+
# Main Training Loop
|
| 708 |
+
# ═══════════════════════════════════════════════════════════
|
| 709 |
+
|
| 710 |
+
def train(student, train_loader, train_sampler, val_manifest, device, args, rank,
|
| 711 |
+
is_distributed):
|
| 712 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 713 |
+
|
| 714 |
+
model = student.module if isinstance(student, DDP) else student
|
| 715 |
+
|
| 716 |
+
trainable_params = [p for p in student.parameters() if p.requires_grad]
|
| 717 |
+
optimizer = torch.optim.AdamW(
|
| 718 |
+
trainable_params,
|
| 719 |
+
lr=args.lr,
|
| 720 |
+
weight_decay=args.weight_decay,
|
| 721 |
+
betas=(0.9, 0.98),
|
| 722 |
+
eps=1e-9,
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
steps_per_epoch = len(train_loader) // args.grad_accum
|
| 726 |
+
total_steps = steps_per_epoch * args.epochs
|
| 727 |
+
warmup_steps = steps_per_epoch * args.warmup_epochs
|
| 728 |
+
|
| 729 |
+
if args.constant_lr:
|
| 730 |
+
scheduler = get_constant_schedule(optimizer, warmup_steps)
|
| 731 |
+
else:
|
| 732 |
+
scheduler = get_cosine_schedule(optimizer, warmup_steps, total_steps, args.min_lr)
|
| 733 |
+
|
| 734 |
+
scaler = torch.amp.GradScaler("cuda") if args.fp16 else None
|
| 735 |
+
|
| 736 |
+
effective_batch = args.batch_size * args.grad_accum
|
| 737 |
+
if is_distributed:
|
| 738 |
+
world_size = dist.get_world_size()
|
| 739 |
+
effective_batch *= world_size
|
| 740 |
+
else:
|
| 741 |
+
world_size = 1
|
| 742 |
+
|
| 743 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 744 |
+
print_rank0(f" Training Configuration", rank)
|
| 745 |
+
print_rank0(f"{'='*65}", rank)
|
| 746 |
+
print_rank0(f" GPUs: {world_size}", rank)
|
| 747 |
+
print_rank0(f" Train samples: {len(train_loader.dataset)}", rank)
|
| 748 |
+
print_rank0(f" Per-GPU batch: {args.batch_size}", rank)
|
| 749 |
+
print_rank0(f" Effective batch: {args.batch_size} x {args.grad_accum} x {world_size} = {effective_batch}", rank)
|
| 750 |
+
print_rank0(f" Steps/epoch: {steps_per_epoch}", rank)
|
| 751 |
+
print_rank0(f" Total steps: {total_steps}", rank)
|
| 752 |
+
print_rank0(f" Warmup steps: {warmup_steps}", rank)
|
| 753 |
+
print_rank0(f" Learning rate: {args.lr} ({'constant' if args.constant_lr else 'cosine decay'})", rank)
|
| 754 |
+
print_rank0(f" Freeze encoder: first {args.freeze_encoder_epochs} epochs", rank)
|
| 755 |
+
print_rank0(f" Mixed precision: {args.fp16}", rank)
|
| 756 |
+
print_rank0(f"{'='*65}\n", rank)
|
| 757 |
+
|
| 758 |
+
global_step = 0
|
| 759 |
+
best_wer = float("inf")
|
| 760 |
+
patience_counter = 0
|
| 761 |
+
|
| 762 |
+
import time as time_module
|
| 763 |
+
|
| 764 |
+
for epoch in range(args.epochs):
|
| 765 |
+
epoch_start = time_module.time()
|
| 766 |
+
student.train()
|
| 767 |
+
|
| 768 |
+
# Set epoch for distributed sampler (ensures different shuffling each epoch)
|
| 769 |
+
if train_sampler is not None:
|
| 770 |
+
train_sampler.set_epoch(epoch)
|
| 771 |
+
|
| 772 |
+
# Phase management
|
| 773 |
+
if epoch < args.freeze_encoder_epochs:
|
| 774 |
+
for p in model.encoder.parameters():
|
| 775 |
+
p.requires_grad = False
|
| 776 |
+
phase = f"Phase 1/{args.freeze_encoder_epochs} (encoder frozen)"
|
| 777 |
+
else:
|
| 778 |
+
for p in model.encoder.parameters():
|
| 779 |
+
p.requires_grad = True
|
| 780 |
+
phase = "Phase 2 (full training)"
|
| 781 |
+
|
| 782 |
+
# Update optimizer param groups
|
| 783 |
+
optimizer.param_groups[0]["params"] = [
|
| 784 |
+
p for p in student.parameters() if p.requires_grad
|
| 785 |
+
]
|
| 786 |
+
|
| 787 |
+
epoch_loss = 0.0
|
| 788 |
+
epoch_steps = 0
|
| 789 |
+
epoch_grad_norm = 0.0
|
| 790 |
+
grad_norm_steps = 0
|
| 791 |
+
|
| 792 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{args.epochs}",
|
| 793 |
+
leave=True, ncols=120, disable=not is_main(rank))
|
| 794 |
+
optimizer.zero_grad()
|
| 795 |
+
|
| 796 |
+
for batch_idx, batch in enumerate(pbar):
|
| 797 |
+
if batch is None:
|
| 798 |
+
continue
|
| 799 |
+
try:
|
| 800 |
+
if scaler:
|
| 801 |
+
with torch.amp.autocast("cuda"):
|
| 802 |
+
loss = train_step(student, batch, device)
|
| 803 |
+
scaled_loss = loss / args.grad_accum
|
| 804 |
+
scaler.scale(scaled_loss).backward()
|
| 805 |
+
else:
|
| 806 |
+
loss = train_step(student, batch, device)
|
| 807 |
+
(loss / args.grad_accum).backward()
|
| 808 |
+
|
| 809 |
+
except RuntimeError as e:
|
| 810 |
+
if "out of memory" in str(e).lower():
|
| 811 |
+
torch.cuda.empty_cache()
|
| 812 |
+
print_rank0(f"\n OOM at batch {batch_idx}, skipping", rank)
|
| 813 |
+
optimizer.zero_grad()
|
| 814 |
+
continue
|
| 815 |
+
raise
|
| 816 |
+
|
| 817 |
+
epoch_loss += loss.item()
|
| 818 |
+
epoch_steps += 1
|
| 819 |
+
|
| 820 |
+
if (batch_idx + 1) % args.grad_accum == 0:
|
| 821 |
+
if scaler:
|
| 822 |
+
scaler.unscale_(optimizer)
|
| 823 |
+
trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
|
| 824 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(trainable, 1.0).item()
|
| 825 |
+
if scaler:
|
| 826 |
+
scaler.step(optimizer)
|
| 827 |
+
scaler.update()
|
| 828 |
+
else:
|
| 829 |
+
optimizer.step()
|
| 830 |
+
|
| 831 |
+
epoch_grad_norm += grad_norm
|
| 832 |
+
grad_norm_steps += 1
|
| 833 |
+
scheduler.step()
|
| 834 |
+
optimizer.zero_grad()
|
| 835 |
+
global_step += 1
|
| 836 |
+
|
| 837 |
+
if epoch_steps % args.log_every == 0 and epoch_steps > 0 and is_main(rank):
|
| 838 |
+
avg_loss = epoch_loss / epoch_steps
|
| 839 |
+
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
|
| 840 |
+
lr = optimizer.param_groups[0]["lr"]
|
| 841 |
+
pbar.set_postfix(loss=f"{avg_loss:.3f}", gnorm=f"{avg_gnorm:.2f}",
|
| 842 |
+
lr=f"{lr:.1e}", step=global_step)
|
| 843 |
+
|
| 844 |
+
# End of epoch
|
| 845 |
+
epoch_time = time_module.time() - epoch_start
|
| 846 |
+
avg_loss = epoch_loss / max(1, epoch_steps)
|
| 847 |
+
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
|
| 848 |
+
samples_per_sec = (epoch_steps * args.batch_size) / epoch_time
|
| 849 |
+
gpu_mem = torch.cuda.max_memory_allocated(device) / 1e9 if torch.cuda.is_available() else 0
|
| 850 |
+
print_rank0(f"\n Epoch {epoch+1} | {phase} | loss={avg_loss:.4f} "
|
| 851 |
+
f"grad_norm={avg_gnorm:.3f} lr={optimizer.param_groups[0]['lr']:.2e}"
|
| 852 |
+
f" | {epoch_time/60:.1f}min | {samples_per_sec:.0f} samples/s | GPU mem: {gpu_mem:.1f}GB", rank)
|
| 853 |
+
|
| 854 |
+
# Evaluation (rank 0 only)
|
| 855 |
+
if is_main(rank) and val_manifest and (epoch + 1) % args.eval_every_epoch == 0:
|
| 856 |
+
try:
|
| 857 |
+
print_rank0(f"\n Evaluating...", rank)
|
| 858 |
+
|
| 859 |
+
# Per-language WER (batch only) and val loss
|
| 860 |
+
lang_wers_batch = {}
|
| 861 |
+
lang_val_losses = {}
|
| 862 |
+
if args.eval_dir:
|
| 863 |
+
for lang in ['de', 'es', 'fr', 'it', 'nl']:
|
| 864 |
+
lang_val = os.path.join(args.eval_dir, lang, 'eval', 'validation_manifest.json')
|
| 865 |
+
if os.path.exists(lang_val):
|
| 866 |
+
lang_wers_batch[lang] = evaluate_batch(student, lang_val, device)
|
| 867 |
+
lang_val_losses[lang] = compute_val_loss(student, lang_val, device)
|
| 868 |
+
|
| 869 |
+
if lang_wers_batch:
|
| 870 |
+
batch_strs = [f"{l.upper()}={w:.1f}%" for l, w in lang_wers_batch.items()]
|
| 871 |
+
loss_strs = [f"{l.upper()}={v:.3f}" for l, v in lang_val_losses.items()]
|
| 872 |
+
print_rank0(f" Batch WER: {' | '.join(batch_strs)}", rank)
|
| 873 |
+
print_rank0(f" Val loss: {' | '.join(loss_strs)}", rank)
|
| 874 |
+
|
| 875 |
+
# Combined val loss + batch WER (used for best model selection)
|
| 876 |
+
val_loss = compute_val_loss(student, val_manifest, device)
|
| 877 |
+
val_wer_batch = evaluate_batch(student, val_manifest, device)
|
| 878 |
+
print_rank0(f" Combined — Batch WER: {val_wer_batch:.2f}% | Val loss: {val_loss:.4f}", rank)
|
| 879 |
+
|
| 880 |
+
if val_wer_batch < best_wer:
|
| 881 |
+
best_wer = val_wer_batch
|
| 882 |
+
patience_counter = 0
|
| 883 |
+
save_path = os.path.join(args.output_dir, "best_model.nemo")
|
| 884 |
+
model.save_to(save_path)
|
| 885 |
+
print_rank0(f" New best! Batch WER={best_wer:.2f}% -> {save_path}", rank)
|
| 886 |
+
else:
|
| 887 |
+
patience_counter += 1
|
| 888 |
+
print_rank0(f" No improvement ({patience_counter}/{args.early_stop_patience})", rank)
|
| 889 |
+
if args.early_stop_patience > 0 and patience_counter >= args.early_stop_patience:
|
| 890 |
+
print_rank0(f"\n Early stopping! No improvement for {args.early_stop_patience} epochs.", rank)
|
| 891 |
+
break
|
| 892 |
+
except Exception as e:
|
| 893 |
+
print_rank0(f" [eval error] {type(e).__name__}: {e} — skipping evaluation this epoch", rank)
|
| 894 |
+
|
| 895 |
+
# Periodic checkpoint (rank 0 only)
|
| 896 |
+
if is_main(rank) and (epoch + 1) % args.save_every_epoch == 0:
|
| 897 |
+
save_path = os.path.join(args.output_dir, f"epoch_{epoch+1}.nemo")
|
| 898 |
+
model.save_to(save_path)
|
| 899 |
+
print_rank0(f" Checkpoint -> {save_path}", rank)
|
| 900 |
+
|
| 901 |
+
# Sync all ranks before next epoch
|
| 902 |
+
if is_distributed:
|
| 903 |
+
dist.barrier()
|
| 904 |
+
|
| 905 |
+
# Final save
|
| 906 |
+
if is_main(rank):
|
| 907 |
+
save_path = os.path.join(args.output_dir, "final_model.nemo")
|
| 908 |
+
model.save_to(save_path)
|
| 909 |
+
print_rank0(f"\n Final model -> {save_path}", rank)
|
| 910 |
+
print_rank0(f" Best WER: {best_wer:.2f}%", rank)
|
| 911 |
+
|
| 912 |
+
return student
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
# ═══════════════════════════════════════════════════════════
|
| 916 |
+
# Entry Point
|
| 917 |
+
# ═══════════════════════════════════════════════════════════
|
| 918 |
+
|
| 919 |
+
def _seed_everything(seed, rank):
|
| 920 |
+
"""Fully deterministic seeding for reproducibility (DDP-safe).
|
| 921 |
+
|
| 922 |
+
Each rank uses ``seed + rank`` so that DistributedSampler still shuffles
|
| 923 |
+
differently per worker, but the run is bit-exact reproducible given the
|
| 924 |
+
same hardware, library versions, and (rank, seed) pair.
|
| 925 |
+
"""
|
| 926 |
+
seed = int(seed) + int(rank)
|
| 927 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 928 |
+
random.seed(seed)
|
| 929 |
+
np.random.seed(seed)
|
| 930 |
+
torch.manual_seed(seed)
|
| 931 |
+
torch.cuda.manual_seed_all(seed)
|
| 932 |
+
torch.backends.cudnn.deterministic = True
|
| 933 |
+
torch.backends.cudnn.benchmark = False
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def _make_worker_init_fn(base_seed, rank):
|
| 937 |
+
"""DataLoader worker_init_fn: reseeds random/numpy/torch in each worker."""
|
| 938 |
+
def _init(worker_id):
|
| 939 |
+
s = int(base_seed) + int(rank) * 10_000 + int(worker_id)
|
| 940 |
+
random.seed(s)
|
| 941 |
+
np.random.seed(s)
|
| 942 |
+
torch.manual_seed(s)
|
| 943 |
+
return _init
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def main():
|
| 947 |
+
args = parse_args()
|
| 948 |
+
|
| 949 |
+
rank, world_size, local_rank, is_distributed = setup_ddp()
|
| 950 |
+
device = torch.device(f"cuda:{local_rank}")
|
| 951 |
+
|
| 952 |
+
_seed_everything(args.seed, rank)
|
| 953 |
+
|
| 954 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 955 |
+
|
| 956 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 957 |
+
print_rank0(f" Nemotron Streaming ASR — Multilingual Training", rank)
|
| 958 |
+
print_rank0(f"{'='*65}", rank)
|
| 959 |
+
print_rank0(f" GPUs: {world_size}", rank)
|
| 960 |
+
print_rank0(f" Student: {args.student}", rank)
|
| 961 |
+
if args.resume_from:
|
| 962 |
+
print_rank0(f" Resume: {args.resume_from}", rank)
|
| 963 |
+
print_rank0(f" Train: {args.train_manifest}", rank)
|
| 964 |
+
print_rank0(f"{'='*65}", rank)
|
| 965 |
+
|
| 966 |
+
# Load model
|
| 967 |
+
print_rank0(f"\n[1/3] Loading model...", rank)
|
| 968 |
+
student = load_student(args, device, rank)
|
| 969 |
+
|
| 970 |
+
# Wrap in DDP
|
| 971 |
+
if is_distributed:
|
| 972 |
+
student = DDP(student, device_ids=[local_rank], find_unused_parameters=True)
|
| 973 |
+
print_rank0(f" Wrapped in DDP (find_unused_parameters=True)", rank)
|
| 974 |
+
|
| 975 |
+
# Create dataloader
|
| 976 |
+
print_rank0(f"\n[2/3] Creating data loaders...", rank)
|
| 977 |
+
model_for_tok = student.module if isinstance(student, DDP) else student
|
| 978 |
+
train_dataset = ASRManifestDataset(
|
| 979 |
+
args.train_manifest,
|
| 980 |
+
model_for_tok.tokenizer,
|
| 981 |
+
min_duration=args.min_duration,
|
| 982 |
+
max_duration=args.max_duration,
|
| 983 |
+
speed_perturb=args.speed_perturb,
|
| 984 |
+
speed_perturb_factors=args.speed_perturb_factors,
|
| 985 |
+
)
|
| 986 |
+
print_rank0(f" Train dataset: {len(train_dataset)} samples", rank)
|
| 987 |
+
|
| 988 |
+
train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=args.seed) \
|
| 989 |
+
if is_distributed else None
|
| 990 |
+
train_loader = DataLoader(
|
| 991 |
+
train_dataset,
|
| 992 |
+
batch_size=args.batch_size,
|
| 993 |
+
shuffle=(train_sampler is None),
|
| 994 |
+
sampler=train_sampler,
|
| 995 |
+
num_workers=args.num_workers,
|
| 996 |
+
collate_fn=collate_asr,
|
| 997 |
+
pin_memory=True,
|
| 998 |
+
drop_last=True,
|
| 999 |
+
worker_init_fn=_make_worker_init_fn(args.seed, rank),
|
| 1000 |
+
generator=torch.Generator().manual_seed(int(args.seed) + int(rank)),
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
# Train
|
| 1004 |
+
print_rank0(f"\n[3/3] Starting training...", rank)
|
| 1005 |
+
student = train(
|
| 1006 |
+
student, train_loader, train_sampler,
|
| 1007 |
+
args.val_manifest, device, args, rank, is_distributed,
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
# Final eval (batch only — run streaming eval separately on best model)
|
| 1011 |
+
if is_main(rank):
|
| 1012 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1013 |
+
print_rank0(f" Final Evaluation (Batch WER)", rank)
|
| 1014 |
+
print_rank0(f"{'='*65}", rank)
|
| 1015 |
+
if args.eval_dir:
|
| 1016 |
+
for lang in ['de', 'es', 'fr', 'it', 'nl']:
|
| 1017 |
+
lang_val = os.path.join(args.eval_dir, lang, 'eval', 'validation_manifest.json')
|
| 1018 |
+
if os.path.exists(lang_val):
|
| 1019 |
+
b_wer = evaluate_batch(student, lang_val, device)
|
| 1020 |
+
print_rank0(f" {lang.upper()} — Batch WER: {b_wer:.2f}%", rank)
|
| 1021 |
+
if args.val_manifest:
|
| 1022 |
+
b_wer = evaluate_batch(student, args.val_manifest, device)
|
| 1023 |
+
print_rank0(f" Combined — Batch WER: {b_wer:.2f}%", rank)
|
| 1024 |
+
|
| 1025 |
+
cleanup_ddp(is_distributed)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
if __name__ == "__main__":
|
| 1029 |
+
main()
|
train_single_lang.py
ADDED
|
@@ -0,0 +1,1858 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_single_lang.py
|
| 4 |
+
|
| 5 |
+
Single-language fine-tuning of Nemotron-Speech-Streaming.
|
| 6 |
+
Adapted from train_multilingual_nemotron.py for per-language training.
|
| 7 |
+
|
| 8 |
+
This script is the entry point for every (language, hours, init) cell of
|
| 9 |
+
the main grid in the paper. The init arm is selected by the combination
|
| 10 |
+
of --resume_from and --encoder_from / --reinit_encoder; the multilingual
|
| 11 |
+
tokenizer, decoder and joint always come from the multilingual base.
|
| 12 |
+
|
| 13 |
+
ML init (paper's "ML" arm)
|
| 14 |
+
--resume_from <multilingual_base.nemo>
|
| 15 |
+
Encoder, decoder, joint and tokenizer all come from the multilingual
|
| 16 |
+
base checkpoint.
|
| 17 |
+
|
| 18 |
+
EN init (paper's "EN" arm)
|
| 19 |
+
--resume_from <multilingual_base.nemo>
|
| 20 |
+
--encoder_from nvidia/nemotron-speech-streaming-en-0.6b
|
| 21 |
+
The decoder, joint and tokenizer are kept from the multilingual base
|
| 22 |
+
(so the comparison isolates the encoder), and the encoder weights are
|
| 23 |
+
overwritten layer-for-layer with the English-only Nemotron encoder.
|
| 24 |
+
|
| 25 |
+
Random-encoder ablation (NOT the paper's EN arm)
|
| 26 |
+
--resume_from <multilingual_base.nemo>
|
| 27 |
+
--reinit_encoder
|
| 28 |
+
Same as ML init except the encoder is freshly random-initialized.
|
| 29 |
+
|
| 30 |
+
Direct from English checkpoint (legacy / not used in the main grid)
|
| 31 |
+
--student nvidia/nemotron-speech-streaming-en-0.6b
|
| 32 |
+
No --resume_from. Everything (encoder, decoder, joint, tokenizer) is
|
| 33 |
+
taken from the English checkpoint and only the prediction-network
|
| 34 |
+
output layer is resized to the target tokenizer.
|
| 35 |
+
|
| 36 |
+
Example usage (paper ML init for German, 100 h):
|
| 37 |
+
torchrun --nproc_per_node=1 train_single_lang.py \
|
| 38 |
+
--lang de \
|
| 39 |
+
--resume_from <CKPT_DIR>/multilingual_base.nemo \
|
| 40 |
+
--train_manifest <DATA_ROOT>/de/100h/train.jsonl \
|
| 41 |
+
--val_manifest <VAL_MANIFEST> \
|
| 42 |
+
--output_dir ./out/de_100h_ml \
|
| 43 |
+
--epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \
|
| 44 |
+
--early_stop_patience 8 --decay_spec_augment --seed 42
|
| 45 |
+
|
| 46 |
+
Example usage (paper EN init for the same cell):
|
| 47 |
+
torchrun --nproc_per_node=1 train_single_lang.py \
|
| 48 |
+
--lang de \
|
| 49 |
+
--resume_from <CKPT_DIR>/multilingual_base.nemo \
|
| 50 |
+
--encoder_from nvidia/nemotron-speech-streaming-en-0.6b \
|
| 51 |
+
--train_manifest <DATA_ROOT>/de/100h/train.jsonl \
|
| 52 |
+
--val_manifest <VAL_MANIFEST> \
|
| 53 |
+
--output_dir ./out/de_100h_en \
|
| 54 |
+
--epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \
|
| 55 |
+
--early_stop_patience 8 --decay_spec_augment --seed 42
|
| 56 |
+
|
| 57 |
+
Manifest format (one JSON object per line):
|
| 58 |
+
{"audio_filepath": "/abs/path/utt.wav", "duration": 8.4, "text": "reference transcript"}
|
| 59 |
+
`duration` (seconds) is required: it drives min/max-duration filtering and
|
| 60 |
+
the --max_train_hours subsampling.
|
| 61 |
+
|
| 62 |
+
Requirements:
|
| 63 |
+
pip install nemo_toolkit[asr] soundfile jiwer tqdm
|
| 64 |
+
Evaluation also requires Whisper's BasicMultilingualTextNormalizer from the
|
| 65 |
+
Open ASR Leaderboard repo (clone https://github.com/huggingface/open_asr_leaderboard
|
| 66 |
+
and add it to PYTHONPATH).
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
import argparse
|
| 70 |
+
import json
|
| 71 |
+
import math
|
| 72 |
+
import os
|
| 73 |
+
import gc
|
| 74 |
+
import re
|
| 75 |
+
import sys
|
| 76 |
+
import unicodedata
|
| 77 |
+
from collections import defaultdict
|
| 78 |
+
|
| 79 |
+
import numpy as np
|
| 80 |
+
import torch
|
| 81 |
+
import torch.distributed as dist
|
| 82 |
+
import torch.nn as nn
|
| 83 |
+
import torch.nn.functional as F
|
| 84 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 85 |
+
from torch.utils.data import DataLoader, DistributedSampler
|
| 86 |
+
from tqdm import tqdm
|
| 87 |
+
|
| 88 |
+
# Use Whisper's BasicMultilingualTextNormalizer for consistent eval
|
| 89 |
+
try:
|
| 90 |
+
from normalizer import BasicMultilingualTextNormalizer
|
| 91 |
+
_ml_normalizer = BasicMultilingualTextNormalizer()
|
| 92 |
+
_has_real_normalizer = True
|
| 93 |
+
except ImportError:
|
| 94 |
+
print(
|
| 95 |
+
"ERROR: could not import BasicMultilingualTextNormalizer. "
|
| 96 |
+
"This script requires Whisper's BasicMultilingualTextNormalizer, "
|
| 97 |
+
"shipped in the Open ASR Leaderboard repo. "
|
| 98 |
+
"Clone https://github.com/huggingface/open_asr_leaderboard and add it "
|
| 99 |
+
"to PYTHONPATH (or set OPEN_ASR_LB_ROOT).",
|
| 100 |
+
file=sys.stderr,
|
| 101 |
+
)
|
| 102 |
+
exit(1)
|
| 103 |
+
_ml_normalizer = None
|
| 104 |
+
_has_real_normalizer = False
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ═══════════════════════════════════════════════════════════
|
| 108 |
+
# DDP Utilities
|
| 109 |
+
# ═══════════════════════════════════════════════════════════
|
| 110 |
+
|
| 111 |
+
def setup_ddp():
|
| 112 |
+
"""Initialize distributed training. Returns (rank, world_size, local_rank, is_distributed)."""
|
| 113 |
+
if "RANK" in os.environ:
|
| 114 |
+
rank = int(os.environ["RANK"])
|
| 115 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 116 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 117 |
+
from datetime import timedelta
|
| 118 |
+
dist.init_process_group("nccl", timeout=timedelta(minutes=60))
|
| 119 |
+
torch.cuda.set_device(local_rank)
|
| 120 |
+
return rank, world_size, local_rank, True
|
| 121 |
+
else:
|
| 122 |
+
return 0, 1, 0, False
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def cleanup_ddp(is_distributed):
|
| 126 |
+
if is_distributed:
|
| 127 |
+
dist.destroy_process_group()
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def is_main(rank):
|
| 131 |
+
return rank == 0
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def print_rank0(msg, rank=0):
|
| 135 |
+
if is_main(rank):
|
| 136 |
+
print(msg, flush=True)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ═══════════════════════════════════════════════════════════
|
| 140 |
+
# Configuration
|
| 141 |
+
# ═══════════════════════════════════════════════════════════
|
| 142 |
+
|
| 143 |
+
def parse_args():
|
| 144 |
+
p = argparse.ArgumentParser(
|
| 145 |
+
description="Single-language Nemotron Streaming ASR Training",
|
| 146 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 147 |
+
)
|
| 148 |
+
# Language
|
| 149 |
+
p.add_argument("--lang", type=str, required=True,
|
| 150 |
+
help="Language code (e.g., de, es, fr, it, nl, sv, pt, pl)")
|
| 151 |
+
|
| 152 |
+
# Models
|
| 153 |
+
p.add_argument("--teacher", default="nvidia/parakeet-tdt-0.6b-v3",
|
| 154 |
+
help="Teacher model for tokenizer extraction")
|
| 155 |
+
p.add_argument("--student", default="nvidia/nemotron-speech-streaming-en-0.6b",
|
| 156 |
+
help="Student model (English, streaming)")
|
| 157 |
+
|
| 158 |
+
# Data
|
| 159 |
+
p.add_argument("--train_manifest", type=str, required=True,
|
| 160 |
+
help="Path to training manifest (JSONL)")
|
| 161 |
+
p.add_argument("--val_manifest", type=str, required=True,
|
| 162 |
+
help="Path to validation manifest (JSONL)")
|
| 163 |
+
|
| 164 |
+
# Training
|
| 165 |
+
p.add_argument("--output_dir", default="./nemotron_lang")
|
| 166 |
+
p.add_argument("--epochs", type=int, default=30)
|
| 167 |
+
p.add_argument("--batch_size", type=int, default=16,
|
| 168 |
+
help="Per-GPU batch size")
|
| 169 |
+
p.add_argument("--grad_accum", type=int, default=2,
|
| 170 |
+
help="Gradient accumulation steps")
|
| 171 |
+
p.add_argument("--lr", type=float, default=1e-4)
|
| 172 |
+
p.add_argument("--min_lr", type=float, default=1e-6)
|
| 173 |
+
p.add_argument("--weight_decay", type=float, default=1e-3)
|
| 174 |
+
p.add_argument("--warmup_epochs", type=int, default=1)
|
| 175 |
+
p.add_argument("--max_duration", type=float, default=20.0)
|
| 176 |
+
p.add_argument("--min_duration", type=float, default=0.3)
|
| 177 |
+
|
| 178 |
+
# SpecAugment
|
| 179 |
+
p.add_argument("--no_spec_augment", action="store_true", default=False)
|
| 180 |
+
p.add_argument("--freq_masks", type=int, default=2)
|
| 181 |
+
p.add_argument("--freq_width", type=int, default=27)
|
| 182 |
+
p.add_argument("--time_masks", type=int, default=10)
|
| 183 |
+
p.add_argument("--time_width", type=float, default=0.05)
|
| 184 |
+
|
| 185 |
+
# Speed perturbation
|
| 186 |
+
p.add_argument("--speed_perturb", action="store_true", default=True)
|
| 187 |
+
p.add_argument("--speed_perturb_factors", type=float, nargs='+', default=[0.9, 1.0, 1.1])
|
| 188 |
+
|
| 189 |
+
# Misc
|
| 190 |
+
p.add_argument("--freeze_encoder_epochs", type=int, default=0,
|
| 191 |
+
help="Freeze encoder for first N epochs")
|
| 192 |
+
p.add_argument("--reinit_encoder", action="store_true", default=False,
|
| 193 |
+
help="Randomly reinitialize all encoder weights (ablation). "
|
| 194 |
+
"NOT the paper's EN arm -- EN init uses --encoder_from "
|
| 195 |
+
"to copy the English encoder weights, not random init.")
|
| 196 |
+
p.add_argument("--reinit_joint", action="store_true", default=False,
|
| 197 |
+
help="Randomly reinitialize the RNNT joint network weights (ablation study). "
|
| 198 |
+
"Useful after swapping encoders so the joint relearns the encoder->vocab mapping.")
|
| 199 |
+
p.add_argument("--lr_decay_epochs", type=int, default=25,
|
| 200 |
+
help="Cosine decay reaches min_lr after N epochs (0=use total epochs)")
|
| 201 |
+
p.add_argument("--constant_lr", action="store_true", default=False)
|
| 202 |
+
p.add_argument("--log_every", type=int, default=50)
|
| 203 |
+
p.add_argument("--eval_every_epoch", type=int, default=1)
|
| 204 |
+
p.add_argument("--save_every_epoch", type=int, default=0,
|
| 205 |
+
help="Save training state every N epochs (0=disabled)")
|
| 206 |
+
p.add_argument("--early_stop_patience", type=int, default=30,
|
| 207 |
+
help="Stop if WER doesn't improve for N evals (0=disabled)")
|
| 208 |
+
p.add_argument("--grad_clip", type=float, default=1.0,
|
| 209 |
+
help="Gradient clipping max norm")
|
| 210 |
+
p.add_argument("--rnnt_clamp", type=float, default=-1.0,
|
| 211 |
+
help="RNNT loss per-frame clamping value (-1=disabled, 1.0=recommended)")
|
| 212 |
+
p.add_argument("--bf16", action="store_true", default=True)
|
| 213 |
+
p.add_argument("--fp16", action="store_true", default=False)
|
| 214 |
+
p.add_argument("--num_workers", type=int, default=4)
|
| 215 |
+
p.add_argument("--max_train_hours", type=float, default=0,
|
| 216 |
+
help="Limit training data to N hours (0=use all data). Samples randomly.")
|
| 217 |
+
p.add_argument("--data_seed", type=int, default=12345,
|
| 218 |
+
help="Seed for data subsampling (separate from training seed for reproducibility)")
|
| 219 |
+
p.add_argument("--seed", type=int, default=42)
|
| 220 |
+
p.add_argument("--resume_from", type=str, default=None,
|
| 221 |
+
help="Resume from .nemo checkpoint (the multilingual base for both "
|
| 222 |
+
"the ML and EN arms of the paper's main grid). Sets the "
|
| 223 |
+
"tokenizer, decoder and joint; the encoder is then either kept "
|
| 224 |
+
"(ML arm), overwritten via --encoder_from (EN arm), or "
|
| 225 |
+
"re-initialized via --reinit_encoder (ablation).")
|
| 226 |
+
p.add_argument("--encoder_from", type=str, default=None,
|
| 227 |
+
help="Overwrite encoder weights with those of this checkpoint after "
|
| 228 |
+
"--resume_from has loaded the multilingual base. This is how "
|
| 229 |
+
"the paper's EN arm is built: multilingual tokenizer/decoder/joint "
|
| 230 |
+
"+ English encoder (nvidia/nemotron-speech-streaming-en-0.6b).")
|
| 231 |
+
p.add_argument("--swap_joint_enc", action="store_true", default=False,
|
| 232 |
+
help="When using --encoder_from, also copy the joint network's encoder projection (enc linear + enc_hat) from the source model. Keeps encoder and joint.enc in sync.")
|
| 233 |
+
p.add_argument("--encoder_from_layers", type=str, default="all",
|
| 234 |
+
help="Which Conformer layer indices to copy from --encoder_from. "
|
| 235 |
+
"Examples: 'all' (default, full encoder), 'none' (skip layers, only use preencode/postnorm flags), "
|
| 236 |
+
"'0:8' (Python slice, layers 0..7), '-8:' (last 8 layers), '0:8,16:24' (multiple ranges). "
|
| 237 |
+
"Negative indices count from the end. Layers outside the slice stay from --resume_from/--student.")
|
| 238 |
+
p.add_argument("--encoder_from_preencode", type=str, default="off", choices=["auto", "on", "off"],
|
| 239 |
+
help="Copy the pre-encoder subsampling (conv frontend) and positional embeddings from --encoder_from. "
|
| 240 |
+
"Default 'off' keeps the destination model's preencode (ML baseline when --resume_from is set), "
|
| 241 |
+
"which is preferable for cross-lingual splices since the ML preencode has seen the target language. "
|
| 242 |
+
"'auto': on iff layer 0 is in --encoder_from_layers.")
|
| 243 |
+
p.add_argument("--encoder_from_postnorm", type=str, default="off", choices=["auto", "on", "off"],
|
| 244 |
+
help="Copy the final encoder norm/output projection from --encoder_from. "
|
| 245 |
+
"Default 'off' keeps the destination model's postnorm (ML baseline when --resume_from is set), "
|
| 246 |
+
"which is the natural pairing when the top layers also come from the destination. "
|
| 247 |
+
"'auto': on iff the last layer is in --encoder_from_layers.")
|
| 248 |
+
p.add_argument("--decay_spec_augment", action="store_true", default=False,
|
| 249 |
+
help="Linearly decay SpecAugment mask counts over training (time_masks: N->2, freq_masks: N->1)")
|
| 250 |
+
p.add_argument("--resume_training", type=str, default=None,
|
| 251 |
+
help="Resume training from a training_state.pt checkpoint (saved in output_dir). Restores optimizer, scheduler, epoch, and all training state.")
|
| 252 |
+
p.add_argument("--confidence_penalty", type=float, default=0.0,
|
| 253 |
+
help="Entropy regularization weight (0=off). Penalizes overconfident joint predictions. Try 0.1-0.3.")
|
| 254 |
+
p.add_argument("--streaming_chunk_sec", type=float, default=0,
|
| 255 |
+
help="Enable chunk-aware streaming training. Chunk duration in seconds (e.g., 1.2). 0=full context training.")
|
| 256 |
+
p.add_argument("--test_manifest", type=str, default=None,
|
| 257 |
+
help="Path to test manifest (JSONL) for final evaluation")
|
| 258 |
+
p.add_argument("--decoder_hidden", type=int, default=0,
|
| 259 |
+
help="Override RNNT decoder (prediction network) LSTM hidden size. 0=keep original (640). E.g., 860, 1024.")
|
| 260 |
+
p.add_argument("--decoder_layers", type=int, default=0,
|
| 261 |
+
help="Override RNNT decoder LSTM layer count. 0=keep original (2). E.g., 3, 4.")
|
| 262 |
+
|
| 263 |
+
return p.parse_args()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# ═══════════════════════════════════════════════════════════
|
| 267 |
+
# Tokenizer Extraction (from teacher)
|
| 268 |
+
# ═══════════════════════════════════════════════════════════
|
| 269 |
+
|
| 270 |
+
def extract_tokenizer(model, tokenizer_dir):
|
| 271 |
+
"""Extract tokenizer .model file from a NeMo ASR model."""
|
| 272 |
+
from pathlib import Path
|
| 273 |
+
|
| 274 |
+
os.makedirs(tokenizer_dir, exist_ok=True)
|
| 275 |
+
out_model = Path(tokenizer_dir) / "tokenizer.model"
|
| 276 |
+
|
| 277 |
+
tok = getattr(model, "tokenizer", None)
|
| 278 |
+
sp = getattr(tok, "tokenizer", None)
|
| 279 |
+
|
| 280 |
+
if sp is not None and hasattr(sp, "serialized_model_proto"):
|
| 281 |
+
blob = sp.serialized_model_proto()
|
| 282 |
+
if blob:
|
| 283 |
+
out_model.write_bytes(blob)
|
| 284 |
+
_generate_vocab_txt(tokenizer_dir)
|
| 285 |
+
vs = getattr(sp, "vocab_size", None)
|
| 286 |
+
if callable(vs):
|
| 287 |
+
vs = vs()
|
| 288 |
+
return str(Path(tokenizer_dir)), int(vs) if vs else 0
|
| 289 |
+
|
| 290 |
+
raise RuntimeError("Could not extract tokenizer from teacher model")
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _generate_vocab_txt(tokenizer_dir):
|
| 294 |
+
import sentencepiece as spm_lib
|
| 295 |
+
model_path = os.path.join(tokenizer_dir, "tokenizer.model")
|
| 296 |
+
vocab_path = os.path.join(tokenizer_dir, "vocab.txt")
|
| 297 |
+
if os.path.exists(vocab_path):
|
| 298 |
+
return
|
| 299 |
+
sp = spm_lib.SentencePieceProcessor()
|
| 300 |
+
sp.load(model_path)
|
| 301 |
+
with open(vocab_path, "w", encoding="utf-8") as f:
|
| 302 |
+
for i in range(sp.get_piece_size()):
|
| 303 |
+
f.write(sp.id_to_piece(i) + "\n")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ═══════════════════════════════════════════════════════════
|
| 307 |
+
# Model Setup
|
| 308 |
+
# ═══════════════════════════════════════════════════════════
|
| 309 |
+
|
| 310 |
+
def setup_spec_augment(student, args):
|
| 311 |
+
from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation
|
| 312 |
+
|
| 313 |
+
if args.no_spec_augment:
|
| 314 |
+
student.spec_augmentation = None
|
| 315 |
+
return
|
| 316 |
+
|
| 317 |
+
spec_aug = SpectrogramAugmentation(
|
| 318 |
+
freq_masks=args.freq_masks,
|
| 319 |
+
time_masks=args.time_masks,
|
| 320 |
+
freq_width=args.freq_width,
|
| 321 |
+
time_width=args.time_width,
|
| 322 |
+
)
|
| 323 |
+
student.spec_augmentation = spec_aug.to(next(student.parameters()).device)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def update_spec_augment(student, args, epoch, total_epochs, rank):
|
| 327 |
+
"""Linearly decay SpecAugment mask counts over training."""
|
| 328 |
+
if not args.decay_spec_augment or args.no_spec_augment:
|
| 329 |
+
return
|
| 330 |
+
from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation
|
| 331 |
+
|
| 332 |
+
progress = epoch / max(1, total_epochs - 1)
|
| 333 |
+
new_time_masks = max(2, round(args.time_masks * (1 - progress)))
|
| 334 |
+
new_freq_masks = max(1, round(args.freq_masks * (1 - 0.5 * progress)))
|
| 335 |
+
|
| 336 |
+
model = student.module if isinstance(student, DDP) else student
|
| 337 |
+
spec_aug = SpectrogramAugmentation(
|
| 338 |
+
freq_masks=new_freq_masks,
|
| 339 |
+
time_masks=new_time_masks,
|
| 340 |
+
freq_width=args.freq_width,
|
| 341 |
+
time_width=args.time_width,
|
| 342 |
+
)
|
| 343 |
+
model.spec_augmentation = spec_aug.to(next(model.parameters()).device)
|
| 344 |
+
print_rank0(f" SpecAug decay: freq={new_freq_masks}x{args.freq_width} time={new_time_masks}x{args.time_width}", rank)
|
| 345 |
+
|
| 346 |
+
from omegaconf import open_dict
|
| 347 |
+
with open_dict(model.cfg):
|
| 348 |
+
model.cfg.spec_augment.freq_masks = new_freq_masks
|
| 349 |
+
model.cfg.spec_augment.time_masks = new_time_masks
|
| 350 |
+
model.cfg.spec_augment.freq_width = args.freq_width
|
| 351 |
+
model.cfg.spec_augment.time_width = args.time_width
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _parse_layer_slice(spec, num_layers):
|
| 355 |
+
"""Parse a slice spec like 'all', 'none', '0:8', '-8:', '0:8,16:24' into a sorted set of indices.
|
| 356 |
+
|
| 357 |
+
Supports Python-style slice ranges, comma-separated. Negative indices count from num_layers.
|
| 358 |
+
Returns a set of ints in [0, num_layers).
|
| 359 |
+
"""
|
| 360 |
+
if spec is None:
|
| 361 |
+
return set()
|
| 362 |
+
s = spec.strip().lower()
|
| 363 |
+
if s in ("all", "*"):
|
| 364 |
+
return set(range(num_layers))
|
| 365 |
+
if s in ("none", ""):
|
| 366 |
+
return set()
|
| 367 |
+
out = set()
|
| 368 |
+
for part in s.split(","):
|
| 369 |
+
part = part.strip()
|
| 370 |
+
if not part:
|
| 371 |
+
continue
|
| 372 |
+
if ":" in part:
|
| 373 |
+
lo_s, hi_s = part.split(":", 1)
|
| 374 |
+
lo = int(lo_s) if lo_s else 0
|
| 375 |
+
hi = int(hi_s) if hi_s else num_layers
|
| 376 |
+
if lo < 0:
|
| 377 |
+
lo += num_layers
|
| 378 |
+
if hi < 0:
|
| 379 |
+
hi += num_layers
|
| 380 |
+
lo = max(0, min(num_layers, lo))
|
| 381 |
+
hi = max(0, min(num_layers, hi))
|
| 382 |
+
out.update(range(lo, hi))
|
| 383 |
+
else:
|
| 384 |
+
idx = int(part)
|
| 385 |
+
if idx < 0:
|
| 386 |
+
idx += num_layers
|
| 387 |
+
if 0 <= idx < num_layers:
|
| 388 |
+
out.add(idx)
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _splice_encoder(dst_encoder, src_encoder, layer_indices, include_preencode, include_postnorm, rank):
|
| 393 |
+
"""Merge src_encoder weights into dst_encoder for the given layer indices, plus optional
|
| 394 |
+
preencode (subsampling + positional encoding) and postnorm modules.
|
| 395 |
+
|
| 396 |
+
Layer keys are expected to start with 'layers.<i>.'. Everything else is treated as
|
| 397 |
+
'preencode-like' if its name matches pre_encode/pos_enc/embedding, or 'postnorm-like' otherwise.
|
| 398 |
+
"""
|
| 399 |
+
src_sd = src_encoder.state_dict()
|
| 400 |
+
dst_sd = dst_encoder.state_dict()
|
| 401 |
+
|
| 402 |
+
PREENC_PREFIXES = ("pre_encode", "pos_enc", "pos_embedding", "pos_embed", "embedding")
|
| 403 |
+
|
| 404 |
+
copied_layers = set()
|
| 405 |
+
copied_pre = []
|
| 406 |
+
copied_post = []
|
| 407 |
+
skipped_shape = []
|
| 408 |
+
skipped_missing = []
|
| 409 |
+
|
| 410 |
+
for k, v in src_sd.items():
|
| 411 |
+
if k.startswith("layers."):
|
| 412 |
+
try:
|
| 413 |
+
idx = int(k.split(".", 2)[1])
|
| 414 |
+
except (ValueError, IndexError):
|
| 415 |
+
continue
|
| 416 |
+
if idx not in layer_indices:
|
| 417 |
+
continue
|
| 418 |
+
target_key = k
|
| 419 |
+
bucket = ("layer", idx)
|
| 420 |
+
elif any(k.startswith(p) for p in PREENC_PREFIXES):
|
| 421 |
+
if not include_preencode:
|
| 422 |
+
continue
|
| 423 |
+
target_key = k
|
| 424 |
+
bucket = ("pre", k)
|
| 425 |
+
else:
|
| 426 |
+
if not include_postnorm:
|
| 427 |
+
continue
|
| 428 |
+
target_key = k
|
| 429 |
+
bucket = ("post", k)
|
| 430 |
+
|
| 431 |
+
if target_key not in dst_sd:
|
| 432 |
+
skipped_missing.append(target_key)
|
| 433 |
+
continue
|
| 434 |
+
if dst_sd[target_key].shape != v.shape:
|
| 435 |
+
skipped_shape.append((target_key, tuple(v.shape), tuple(dst_sd[target_key].shape)))
|
| 436 |
+
continue
|
| 437 |
+
|
| 438 |
+
dst_sd[target_key] = v
|
| 439 |
+
if bucket[0] == "layer":
|
| 440 |
+
copied_layers.add(bucket[1])
|
| 441 |
+
elif bucket[0] == "pre":
|
| 442 |
+
copied_pre.append(target_key)
|
| 443 |
+
else:
|
| 444 |
+
copied_post.append(target_key)
|
| 445 |
+
|
| 446 |
+
missing, unexpected = dst_encoder.load_state_dict(dst_sd, strict=False)
|
| 447 |
+
print_rank0(
|
| 448 |
+
f" Encoder splice: copied layers {sorted(copied_layers)} "
|
| 449 |
+
f"({len(copied_layers)} of {len(layer_indices)} requested)", rank
|
| 450 |
+
)
|
| 451 |
+
if copied_pre:
|
| 452 |
+
print_rank0(f" Encoder splice: copied {len(copied_pre)} preencode keys", rank)
|
| 453 |
+
if copied_post:
|
| 454 |
+
print_rank0(f" Encoder splice: copied {len(copied_post)} postnorm/other keys", rank)
|
| 455 |
+
if skipped_shape:
|
| 456 |
+
print_rank0(f" WARNING: skipped {len(skipped_shape)} keys due to shape mismatch (first: {skipped_shape[0]})", rank)
|
| 457 |
+
if skipped_missing:
|
| 458 |
+
print_rank0(f" WARNING: skipped {len(skipped_missing)} keys missing in dst encoder (first: {skipped_missing[0]})", rank)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def load_student(args, device, rank):
|
| 462 |
+
"""Load student model, optionally swap tokenizer."""
|
| 463 |
+
import nemo.collections.asr as nemo_asr
|
| 464 |
+
|
| 465 |
+
if args.resume_from:
|
| 466 |
+
print_rank0(f" Resuming from: {args.resume_from}", rank)
|
| 467 |
+
student = nemo_asr.models.ASRModel.restore_from(args.resume_from, map_location='cpu')
|
| 468 |
+
print_rank0(f" Vocab: {student.tokenizer.vocab_size} tokens", rank)
|
| 469 |
+
args.freeze_encoder_epochs = 0
|
| 470 |
+
|
| 471 |
+
# Optionally override encoder weights from a different model (e.g., English)
|
| 472 |
+
if args.encoder_from:
|
| 473 |
+
print_rank0(f" Loading encoder from: {args.encoder_from}", rank)
|
| 474 |
+
if args.encoder_from.endswith('.nemo'):
|
| 475 |
+
encoder_model = nemo_asr.models.ASRModel.restore_from(args.encoder_from, map_location='cpu')
|
| 476 |
+
else:
|
| 477 |
+
encoder_model = nemo_asr.models.ASRModel.from_pretrained(args.encoder_from, map_location='cpu')
|
| 478 |
+
|
| 479 |
+
# Determine number of Conformer layers from the source encoder
|
| 480 |
+
src_layers_attr = getattr(encoder_model.encoder, "layers", None)
|
| 481 |
+
num_layers = len(src_layers_attr) if src_layers_attr is not None else 0
|
| 482 |
+
dst_layers_attr = getattr(student.encoder, "layers", None)
|
| 483 |
+
dst_num_layers = len(dst_layers_attr) if dst_layers_attr is not None else 0
|
| 484 |
+
if num_layers == 0 or dst_num_layers == 0:
|
| 485 |
+
raise RuntimeError(
|
| 486 |
+
f"Could not locate '.encoder.layers' on src ({num_layers}) or dst ({dst_num_layers}); "
|
| 487 |
+
f"layer splicing requires a Conformer-style encoder with .layers nn.ModuleList."
|
| 488 |
+
)
|
| 489 |
+
if num_layers != dst_num_layers:
|
| 490 |
+
print_rank0(
|
| 491 |
+
f" WARNING: src encoder has {num_layers} layers but dst has {dst_num_layers}; "
|
| 492 |
+
f"only layers present in both will be copied.", rank
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
spec = args.encoder_from_layers or "all"
|
| 496 |
+
effective_layers = min(num_layers, dst_num_layers)
|
| 497 |
+
layer_indices = _parse_layer_slice(spec, effective_layers)
|
| 498 |
+
|
| 499 |
+
# Auto-detect: preencode if EN provides layer 0; postnorm if EN provides last layer.
|
| 500 |
+
auto_preencode = 0 in layer_indices
|
| 501 |
+
auto_postnorm = (effective_layers - 1) in layer_indices
|
| 502 |
+
|
| 503 |
+
def _resolve(flag, auto_value, name):
|
| 504 |
+
if flag == "on":
|
| 505 |
+
return True
|
| 506 |
+
if flag == "off":
|
| 507 |
+
return False
|
| 508 |
+
return auto_value # "auto"
|
| 509 |
+
|
| 510 |
+
include_preencode = _resolve(args.encoder_from_preencode, auto_preencode, "preencode")
|
| 511 |
+
include_postnorm = _resolve(args.encoder_from_postnorm, auto_postnorm, "postnorm")
|
| 512 |
+
|
| 513 |
+
# Fast path: entire encoder copied (all layers + both boundaries) -> direct load_state_dict.
|
| 514 |
+
full_copy = (
|
| 515 |
+
len(layer_indices) == effective_layers
|
| 516 |
+
and include_preencode
|
| 517 |
+
and include_postnorm
|
| 518 |
+
and num_layers == dst_num_layers
|
| 519 |
+
)
|
| 520 |
+
if full_copy:
|
| 521 |
+
student.encoder.load_state_dict(encoder_model.encoder.state_dict())
|
| 522 |
+
enc_params = sum(p.numel() for p in student.encoder.parameters()) / 1e6
|
| 523 |
+
print_rank0(f" Encoder fully swapped: {enc_params:.1f}M params from {args.encoder_from}", rank)
|
| 524 |
+
else:
|
| 525 |
+
print_rank0(
|
| 526 |
+
f" Encoder splice spec='{spec}' ({len(layer_indices)}/{effective_layers} layers); "
|
| 527 |
+
f"preencode={include_preencode} ({args.encoder_from_preencode}"
|
| 528 |
+
f"{' -> auto=' + str(auto_preencode) if args.encoder_from_preencode == 'auto' else ''}), "
|
| 529 |
+
f"postnorm={include_postnorm} ({args.encoder_from_postnorm}"
|
| 530 |
+
f"{' -> auto=' + str(auto_postnorm) if args.encoder_from_postnorm == 'auto' else ''})", rank
|
| 531 |
+
)
|
| 532 |
+
_splice_encoder(
|
| 533 |
+
student.encoder,
|
| 534 |
+
encoder_model.encoder,
|
| 535 |
+
layer_indices,
|
| 536 |
+
include_preencode=include_preencode,
|
| 537 |
+
include_postnorm=include_postnorm,
|
| 538 |
+
rank=rank,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
# Optionally also swap the joint network's encoder-side projection
|
| 542 |
+
if args.swap_joint_enc:
|
| 543 |
+
swapped_keys = []
|
| 544 |
+
src_joint_sd = encoder_model.joint.state_dict()
|
| 545 |
+
dst_joint_sd = student.joint.state_dict()
|
| 546 |
+
for key in src_joint_sd:
|
| 547 |
+
# Match encoder-side projection layers (enc, enc_hat, etc.)
|
| 548 |
+
if 'enc' in key and key in dst_joint_sd and src_joint_sd[key].shape == dst_joint_sd[key].shape:
|
| 549 |
+
dst_joint_sd[key] = src_joint_sd[key]
|
| 550 |
+
swapped_keys.append(key)
|
| 551 |
+
if swapped_keys:
|
| 552 |
+
student.joint.load_state_dict(dst_joint_sd)
|
| 553 |
+
print_rank0(f" Joint encoder projection swapped: {swapped_keys}", rank)
|
| 554 |
+
else:
|
| 555 |
+
print_rank0(f" WARNING: --swap_joint_enc set but no matching joint.enc keys found", rank)
|
| 556 |
+
|
| 557 |
+
del encoder_model
|
| 558 |
+
else:
|
| 559 |
+
# Extract teacher tokenizer (only rank 0 does this, then all read from disk)
|
| 560 |
+
tokenizer_dir = os.path.join(args.output_dir, "teacher_tokenizer")
|
| 561 |
+
if is_main(rank):
|
| 562 |
+
print_rank0(f" Loading teacher for tokenizer: {args.teacher}", rank)
|
| 563 |
+
teacher = nemo_asr.models.ASRModel.from_pretrained(args.teacher)
|
| 564 |
+
tokenizer_dir, teacher_vocab_size = extract_tokenizer(teacher, tokenizer_dir)
|
| 565 |
+
print_rank0(f" Teacher vocab: {teacher_vocab_size}", rank)
|
| 566 |
+
del teacher
|
| 567 |
+
torch.cuda.empty_cache()
|
| 568 |
+
|
| 569 |
+
if dist.is_initialized():
|
| 570 |
+
dist.barrier()
|
| 571 |
+
|
| 572 |
+
# Load student
|
| 573 |
+
print_rank0(f" Loading student: {args.student}", rank)
|
| 574 |
+
student = nemo_asr.models.ASRModel.from_pretrained(args.student)
|
| 575 |
+
|
| 576 |
+
old_vocab = student.tokenizer.vocab_size
|
| 577 |
+
student.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type="bpe")
|
| 578 |
+
new_vocab = student.tokenizer.vocab_size
|
| 579 |
+
print_rank0(f" Tokenizer swap: {old_vocab} → {new_vocab}", rank)
|
| 580 |
+
|
| 581 |
+
# Optionally resize decoder (prediction network)
|
| 582 |
+
if args.decoder_hidden > 0 or args.decoder_layers > 0:
|
| 583 |
+
from omegaconf import open_dict, OmegaConf
|
| 584 |
+
old_hidden = student.cfg.decoder.prednet.pred_hidden
|
| 585 |
+
old_layers = student.cfg.decoder.prednet.pred_rnn_layers
|
| 586 |
+
new_hidden = args.decoder_hidden if args.decoder_hidden > 0 else old_hidden
|
| 587 |
+
new_layers = args.decoder_layers if args.decoder_layers > 0 else old_layers
|
| 588 |
+
|
| 589 |
+
with open_dict(student.cfg):
|
| 590 |
+
student.cfg.decoder.prednet.pred_hidden = new_hidden
|
| 591 |
+
student.cfg.decoder.prednet.pred_rnn_layers = new_layers
|
| 592 |
+
|
| 593 |
+
# Rebuild decoder + joint with new dimensions
|
| 594 |
+
from nemo.collections.asr.modules import RNNTDecoder, RNNTJoint
|
| 595 |
+
student.decoder = RNNTDecoder(
|
| 596 |
+
prednet=OmegaConf.to_container(student.cfg.decoder.prednet, resolve=True),
|
| 597 |
+
vocab_size=student.tokenizer.vocab_size,
|
| 598 |
+
normalization_mode=student.cfg.decoder.get('normalization_mode', None),
|
| 599 |
+
random_state_sampling=student.cfg.decoder.get('random_state_sampling', False),
|
| 600 |
+
blank_as_pad=student.cfg.decoder.get('blank_as_pad', True),
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
# Rebuild joint network to match new decoder hidden
|
| 604 |
+
with open_dict(student.cfg):
|
| 605 |
+
student.cfg.joint.jointnet.pred_hidden = new_hidden
|
| 606 |
+
student.cfg.joint.jointnet.encoder_hidden = student.cfg.encoder.d_model
|
| 607 |
+
student.cfg.joint.num_classes = student.tokenizer.vocab_size
|
| 608 |
+
joint_cfg = OmegaConf.to_container(student.cfg.joint, resolve=True)
|
| 609 |
+
joint_cfg.pop('_target_', None)
|
| 610 |
+
joint_cfg.pop('vocabulary', None)
|
| 611 |
+
student.joint = RNNTJoint(**joint_cfg)
|
| 612 |
+
|
| 613 |
+
dec_params = sum(p.numel() for p in student.decoder.parameters()) / 1e6
|
| 614 |
+
joint_params = sum(p.numel() for p in student.joint.parameters()) / 1e6
|
| 615 |
+
print_rank0(f" Decoder resized: hidden {old_hidden}->{new_hidden}, layers {old_layers}->{new_layers}", rank)
|
| 616 |
+
print_rank0(f" New decoder params: {dec_params:.1f}M, joint params: {joint_params:.1f}M", rank)
|
| 617 |
+
|
| 618 |
+
student = student.to(device)
|
| 619 |
+
|
| 620 |
+
# Optionally reinitialize encoder weights (ablation study)
|
| 621 |
+
if args.reinit_encoder:
|
| 622 |
+
print_rank0(" REINITIALIZING ENCODER WEIGHTS (random init)", rank)
|
| 623 |
+
for name, param in student.encoder.named_parameters():
|
| 624 |
+
if param.dim() >= 2:
|
| 625 |
+
torch.nn.init.xavier_uniform_(param)
|
| 626 |
+
else:
|
| 627 |
+
torch.nn.init.zeros_(param)
|
| 628 |
+
# Also reinit batch norm running stats
|
| 629 |
+
for module in student.encoder.modules():
|
| 630 |
+
if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)):
|
| 631 |
+
module.reset_running_stats()
|
| 632 |
+
enc_params = sum(p.numel() for p in student.encoder.parameters())
|
| 633 |
+
print_rank0(f" Reinitialized {enc_params/1e6:.1f}M encoder parameters", rank)
|
| 634 |
+
|
| 635 |
+
# Optionally reinitialize joint network weights (ablation study)
|
| 636 |
+
if args.reinit_joint:
|
| 637 |
+
print_rank0(" REINITIALIZING JOINT NETWORK WEIGHTS (random init)", rank)
|
| 638 |
+
# Re-seed RNG with a fixed value so ML and EN arms get IDENTICAL joint init
|
| 639 |
+
# (independent of prior RNG state consumed by different checkpoint loads).
|
| 640 |
+
# Using args.seed (not args.seed+rank) ensures same init across DDP ranks too.
|
| 641 |
+
_joint_seed = args.seed
|
| 642 |
+
_gen_state_cpu = torch.random.get_rng_state()
|
| 643 |
+
_gen_state_cuda = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None
|
| 644 |
+
torch.manual_seed(_joint_seed)
|
| 645 |
+
if torch.cuda.is_available():
|
| 646 |
+
torch.cuda.manual_seed_all(_joint_seed)
|
| 647 |
+
print_rank0(f" Joint reinit RNG seeded with {_joint_seed} (identical across ML/EN arms)", rank)
|
| 648 |
+
for name, param in student.joint.named_parameters():
|
| 649 |
+
if param.dim() >= 2:
|
| 650 |
+
torch.nn.init.xavier_uniform_(param)
|
| 651 |
+
else:
|
| 652 |
+
torch.nn.init.zeros_(param)
|
| 653 |
+
for module in student.joint.modules():
|
| 654 |
+
if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)):
|
| 655 |
+
module.reset_running_stats()
|
| 656 |
+
# Restore prior RNG state so training stochasticity is unaffected
|
| 657 |
+
torch.random.set_rng_state(_gen_state_cpu)
|
| 658 |
+
if _gen_state_cuda is not None:
|
| 659 |
+
torch.cuda.set_rng_state_all(_gen_state_cuda)
|
| 660 |
+
joint_params = sum(p.numel() for p in student.joint.parameters())
|
| 661 |
+
print_rank0(f" Reinitialized {joint_params/1e6:.1f}M joint parameters", rank)
|
| 662 |
+
|
| 663 |
+
# SpecAugment
|
| 664 |
+
setup_spec_augment(student, args)
|
| 665 |
+
|
| 666 |
+
# Streaming chunk-aware training: restrict attention context
|
| 667 |
+
if args.streaming_chunk_sec > 0:
|
| 668 |
+
# Force single attention context mode [70, 13] instead of random multi-context
|
| 669 |
+
# Default model has 4 modes: [70,13], [70,6], [70,1], [70,0] sampled randomly
|
| 670 |
+
# This forces always using [70, 13] (largest context, lowest latency mode)
|
| 671 |
+
student.encoder.att_context_size = [70, 13]
|
| 672 |
+
student.encoder.att_context_size_all = [[70, 13]]
|
| 673 |
+
student.encoder.att_context_probs = [1.0]
|
| 674 |
+
print_rank0(f" Streaming training: forced att_context=[70,13] only (no multi-context)", rank)
|
| 675 |
+
|
| 676 |
+
# Disable CUDA graphs and typecheck
|
| 677 |
+
from omegaconf import open_dict
|
| 678 |
+
from nemo.core.classes.common import typecheck
|
| 679 |
+
typecheck.set_typecheck_enabled(False)
|
| 680 |
+
with open_dict(student.cfg):
|
| 681 |
+
student.cfg.decoding.greedy.use_cuda_graph_decoder = False
|
| 682 |
+
student.change_decoding_strategy(student.cfg.decoding)
|
| 683 |
+
|
| 684 |
+
# Override RNNT loss clamping if requested
|
| 685 |
+
if args.rnnt_clamp > 0:
|
| 686 |
+
from nemo.collections.asr.losses.rnnt import RNNTLoss
|
| 687 |
+
with open_dict(student.cfg):
|
| 688 |
+
student.cfg.loss.warprnnt_numba_kwargs.clamp = args.rnnt_clamp
|
| 689 |
+
student.loss = RNNTLoss(num_classes=student.decoder.vocab_size, loss_name='default',
|
| 690 |
+
loss_kwargs=dict(student.cfg.loss.warprnnt_numba_kwargs))
|
| 691 |
+
print_rank0(f" RNNT loss clamping: {args.rnnt_clamp}", rank)
|
| 692 |
+
|
| 693 |
+
params = sum(p.numel() for p in student.parameters()) / 1e6
|
| 694 |
+
print_rank0(f" Student params: {params:.1f}M", rank)
|
| 695 |
+
|
| 696 |
+
return student
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ═══════════════════════════════════════════════════════════
|
| 700 |
+
# Dataset & DataLoader
|
| 701 |
+
# ═══════════════════════════════════════════════════════════
|
| 702 |
+
|
| 703 |
+
class ASRManifestDataset(torch.utils.data.Dataset):
|
| 704 |
+
def __init__(self, manifest_path, tokenizer, min_duration=0.3, max_duration=20.0,
|
| 705 |
+
speed_perturb=False, speed_perturb_factors=None,
|
| 706 |
+
max_train_hours=0, seed=42):
|
| 707 |
+
self.tokenizer = tokenizer
|
| 708 |
+
self.speed_perturb = speed_perturb
|
| 709 |
+
self.speed_perturb_factors = speed_perturb_factors or [0.9, 1.0, 1.1]
|
| 710 |
+
self.samples = []
|
| 711 |
+
|
| 712 |
+
with open(manifest_path) as f:
|
| 713 |
+
for line in f:
|
| 714 |
+
item = json.loads(line)
|
| 715 |
+
dur = item["duration"]
|
| 716 |
+
if min_duration <= dur <= max_duration:
|
| 717 |
+
self.samples.append(item)
|
| 718 |
+
|
| 719 |
+
# Subsample to max_train_hours if specified
|
| 720 |
+
if max_train_hours > 0:
|
| 721 |
+
target_seconds = max_train_hours * 3600
|
| 722 |
+
rng = np.random.RandomState(seed)
|
| 723 |
+
rng.shuffle(self.samples)
|
| 724 |
+
selected = []
|
| 725 |
+
total_dur = 0.0
|
| 726 |
+
for s in self.samples:
|
| 727 |
+
if total_dur >= target_seconds:
|
| 728 |
+
break
|
| 729 |
+
selected.append(s)
|
| 730 |
+
total_dur += s["duration"]
|
| 731 |
+
self.samples = selected
|
| 732 |
+
self.total_hours = total_dur / 3600
|
| 733 |
+
|
| 734 |
+
def __len__(self):
|
| 735 |
+
return len(self.samples)
|
| 736 |
+
|
| 737 |
+
def __getitem__(self, idx):
|
| 738 |
+
import soundfile as sf
|
| 739 |
+
item = self.samples[idx]
|
| 740 |
+
try:
|
| 741 |
+
audio, sr = sf.read(item["audio_filepath"], dtype="float32")
|
| 742 |
+
except Exception as e:
|
| 743 |
+
print(f" Corrupt audio: {item['audio_filepath']} ({e})", flush=True)
|
| 744 |
+
return None
|
| 745 |
+
|
| 746 |
+
if sr != 16000:
|
| 747 |
+
ratio = 16000 / sr
|
| 748 |
+
new_len = int(len(audio) * ratio)
|
| 749 |
+
audio = np.interp(
|
| 750 |
+
np.linspace(0, len(audio) - 1, new_len),
|
| 751 |
+
np.arange(len(audio)), audio,
|
| 752 |
+
).astype(np.float32)
|
| 753 |
+
|
| 754 |
+
# Speed perturbation
|
| 755 |
+
if self.speed_perturb:
|
| 756 |
+
import random
|
| 757 |
+
speed = random.choice(self.speed_perturb_factors)
|
| 758 |
+
if speed != 1.0:
|
| 759 |
+
new_len = int(len(audio) / speed)
|
| 760 |
+
audio = np.interp(
|
| 761 |
+
np.linspace(0, len(audio) - 1, new_len),
|
| 762 |
+
np.arange(len(audio)), audio,
|
| 763 |
+
).astype(np.float32)
|
| 764 |
+
|
| 765 |
+
audio_tensor = torch.FloatTensor(audio)
|
| 766 |
+
|
| 767 |
+
text = unicodedata.normalize("NFKC", item["text"])
|
| 768 |
+
text = " ".join(text.split())
|
| 769 |
+
tokens = torch.LongTensor(self.tokenizer.text_to_ids(text))
|
| 770 |
+
|
| 771 |
+
return audio_tensor, tokens
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def collate_asr(batch):
|
| 775 |
+
batch = [b for b in batch if b is not None]
|
| 776 |
+
if len(batch) == 0:
|
| 777 |
+
return None
|
| 778 |
+
audios = [b[0] for b in batch]
|
| 779 |
+
tokens_list = [b[1] for b in batch]
|
| 780 |
+
|
| 781 |
+
audio_lens = torch.LongTensor([len(a) for a in audios])
|
| 782 |
+
token_lens = torch.LongTensor([len(t) for t in tokens_list])
|
| 783 |
+
|
| 784 |
+
max_audio = audio_lens.max().item()
|
| 785 |
+
max_tokens = token_lens.max().item()
|
| 786 |
+
B = len(audios)
|
| 787 |
+
|
| 788 |
+
padded_audio = torch.zeros(B, max_audio)
|
| 789 |
+
padded_tokens = torch.zeros(B, max_tokens, dtype=torch.long)
|
| 790 |
+
|
| 791 |
+
for i in range(B):
|
| 792 |
+
padded_audio[i, :audio_lens[i]] = audios[i]
|
| 793 |
+
padded_tokens[i, :token_lens[i]] = tokens_list[i]
|
| 794 |
+
|
| 795 |
+
return padded_audio, audio_lens, padded_tokens, token_lens
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
# ═══════════════════════════════════════════════════════════
|
| 799 |
+
# Training Step
|
| 800 |
+
# ═══════════════════════════════════════════════════════════
|
| 801 |
+
|
| 802 |
+
def train_step(student, batch, device, confidence_penalty=0.0):
|
| 803 |
+
"""Single forward/backward step: RNNT loss + optional entropy regularization."""
|
| 804 |
+
audio, audio_len, tokens, token_len = batch
|
| 805 |
+
audio = audio.to(device)
|
| 806 |
+
audio_len = audio_len.to(device)
|
| 807 |
+
tokens = tokens.to(device)
|
| 808 |
+
token_len = token_len.to(device)
|
| 809 |
+
|
| 810 |
+
model = student.module if isinstance(student, DDP) else student
|
| 811 |
+
|
| 812 |
+
# Mel spectrogram
|
| 813 |
+
mel, mel_len = model.preprocessor(input_signal=audio, length=audio_len)
|
| 814 |
+
|
| 815 |
+
# Spec augmentation
|
| 816 |
+
if model.spec_augmentation is not None and model.training:
|
| 817 |
+
mel = model.spec_augmentation(input_spec=mel, length=mel_len)
|
| 818 |
+
|
| 819 |
+
# Encoder
|
| 820 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 821 |
+
|
| 822 |
+
# Decoder
|
| 823 |
+
dec_out = model.decoder(targets=tokens, target_length=token_len)
|
| 824 |
+
if isinstance(dec_out, tuple):
|
| 825 |
+
dec_out = dec_out[0]
|
| 826 |
+
|
| 827 |
+
# Joint + RNNT loss
|
| 828 |
+
if getattr(model.joint, 'fuse_loss_wer', False):
|
| 829 |
+
result = model.joint(
|
| 830 |
+
encoder_outputs=enc, decoder_outputs=dec_out,
|
| 831 |
+
encoder_lengths=enc_len, transcripts=tokens,
|
| 832 |
+
transcript_lengths=token_len, compute_wer=False,
|
| 833 |
+
)
|
| 834 |
+
loss = result[0]
|
| 835 |
+
else:
|
| 836 |
+
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
|
| 837 |
+
loss = model.loss(
|
| 838 |
+
log_probs=joint_out, targets=tokens,
|
| 839 |
+
input_lengths=enc_len, target_lengths=token_len,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
if loss.dim() > 0:
|
| 843 |
+
loss = loss.mean()
|
| 844 |
+
|
| 845 |
+
# Confidence penalty: negative entropy regularization on joint output
|
| 846 |
+
# Encourages less confident (more spread) predictions, acts like label smoothing
|
| 847 |
+
if confidence_penalty > 0.0:
|
| 848 |
+
# Extra forward pass through joint to get logits (works with fuse_loss_wer too)
|
| 849 |
+
joint_logits = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
|
| 850 |
+
# joint_logits: (B, T, U, V) log-probabilities
|
| 851 |
+
probs = torch.exp(joint_logits)
|
| 852 |
+
entropy = -(probs * joint_logits).sum(dim=-1) # (B, T, U)
|
| 853 |
+
# Maximize entropy = minimize negative entropy = subtract from loss
|
| 854 |
+
loss = loss - confidence_penalty * entropy.mean()
|
| 855 |
+
|
| 856 |
+
return loss
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
# ═══════════════════════════════════════════════════════════
|
| 860 |
+
# Evaluation
|
| 861 |
+
# ═══════════════════════════════════════════════════════════
|
| 862 |
+
|
| 863 |
+
def normalize_text(text):
|
| 864 |
+
if _ml_normalizer is not None:
|
| 865 |
+
return _ml_normalizer(text)
|
| 866 |
+
text = unicodedata.normalize('NFKC', text)
|
| 867 |
+
text = text.lower()
|
| 868 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 869 |
+
return ' '.join(text.split())
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def normalize_text_fallback(text):
|
| 873 |
+
"""Always use fallback normalizer for consistency with older runs."""
|
| 874 |
+
text = unicodedata.normalize('NFKC', text)
|
| 875 |
+
text = text.lower()
|
| 876 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 877 |
+
return ' '.join(text.split())
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def simple_wer(ref_words, hyp_words):
|
| 881 |
+
n, m = len(ref_words), len(hyp_words)
|
| 882 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 883 |
+
for i in range(n + 1): dp[i][0] = i
|
| 884 |
+
for j in range(m + 1): dp[0][j] = j
|
| 885 |
+
for i in range(1, n + 1):
|
| 886 |
+
for j in range(1, m + 1):
|
| 887 |
+
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
|
| 888 |
+
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
|
| 889 |
+
return dp[n][m]
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def compute_wer_ids(ref_words, hyp_words):
|
| 893 |
+
"""Edit distance with backtrace to get S/D/I counts."""
|
| 894 |
+
n, m = len(ref_words), len(hyp_words)
|
| 895 |
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
| 896 |
+
for i in range(n + 1): dp[i][0] = i
|
| 897 |
+
for j in range(m + 1): dp[0][j] = j
|
| 898 |
+
for i in range(1, n + 1):
|
| 899 |
+
for j in range(1, m + 1):
|
| 900 |
+
if ref_words[i - 1] == hyp_words[j - 1]:
|
| 901 |
+
dp[i][j] = dp[i - 1][j - 1]
|
| 902 |
+
else:
|
| 903 |
+
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
|
| 904 |
+
subs, dels, ins = 0, 0, 0
|
| 905 |
+
i, j = n, m
|
| 906 |
+
while i > 0 or j > 0:
|
| 907 |
+
if i > 0 and j > 0 and ref_words[i - 1] == hyp_words[j - 1]:
|
| 908 |
+
i -= 1; j -= 1
|
| 909 |
+
elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1:
|
| 910 |
+
subs += 1; i -= 1; j -= 1
|
| 911 |
+
elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
|
| 912 |
+
dels += 1; i -= 1
|
| 913 |
+
else:
|
| 914 |
+
ins += 1; j -= 1
|
| 915 |
+
return subs, dels, ins
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
@torch.no_grad()
|
| 919 |
+
def evaluate_batch(student, manifest_path, device, max_samples=None, normalizer_fn=None, rank=0):
|
| 920 |
+
"""Evaluate WER using batch (non-streaming) inference."""
|
| 921 |
+
import soundfile as sf_eval
|
| 922 |
+
|
| 923 |
+
if normalizer_fn is None:
|
| 924 |
+
normalizer_fn = normalize_text
|
| 925 |
+
|
| 926 |
+
model = student.module if isinstance(student, DDP) else student
|
| 927 |
+
model.eval()
|
| 928 |
+
|
| 929 |
+
samples = []
|
| 930 |
+
with open(manifest_path) as f:
|
| 931 |
+
for line in f:
|
| 932 |
+
samples.append(json.loads(line))
|
| 933 |
+
if max_samples and len(samples) > max_samples:
|
| 934 |
+
samples = samples[:max_samples]
|
| 935 |
+
|
| 936 |
+
total_edits, total_words = 0, 0
|
| 937 |
+
total_subs, total_dels, total_ins = 0, 0, 0
|
| 938 |
+
errors = 0
|
| 939 |
+
batch_size = 16
|
| 940 |
+
examples = []
|
| 941 |
+
|
| 942 |
+
total_batches = (len(samples) + batch_size - 1) // batch_size
|
| 943 |
+
for start in range(0, len(samples), batch_size):
|
| 944 |
+
batch_samples = samples[start:start + batch_size]
|
| 945 |
+
batch_num = start // batch_size + 1
|
| 946 |
+
if (batch_num % 10 == 0 or batch_num == 1) and rank == 0:
|
| 947 |
+
print(f" [eval batch {batch_num}/{total_batches}]", flush=True)
|
| 948 |
+
try:
|
| 949 |
+
audios = []
|
| 950 |
+
for s in batch_samples:
|
| 951 |
+
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
|
| 952 |
+
if len(audio.shape) > 1:
|
| 953 |
+
audio = audio.mean(axis=1)
|
| 954 |
+
audios.append(torch.FloatTensor(audio))
|
| 955 |
+
|
| 956 |
+
audio_lens = torch.LongTensor([len(a) for a in audios])
|
| 957 |
+
max_len = audio_lens.max().item()
|
| 958 |
+
padded = torch.zeros(len(audios), max_len)
|
| 959 |
+
for i, a in enumerate(audios):
|
| 960 |
+
padded[i, :len(a)] = a
|
| 961 |
+
|
| 962 |
+
padded = padded.to(device)
|
| 963 |
+
audio_lens = audio_lens.to(device)
|
| 964 |
+
|
| 965 |
+
mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
|
| 966 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 967 |
+
|
| 968 |
+
best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
|
| 969 |
+
if isinstance(best_hyps, tuple):
|
| 970 |
+
best_hyps = best_hyps[0]
|
| 971 |
+
|
| 972 |
+
for s, hyp in zip(batch_samples, best_hyps):
|
| 973 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 974 |
+
pred = hyp.text
|
| 975 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 976 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 977 |
+
pred = model.tokenizer.ids_to_text(tids) if tids else ""
|
| 978 |
+
else:
|
| 979 |
+
pred = str(hyp)
|
| 980 |
+
|
| 981 |
+
ref_n = normalizer_fn(s["text"])
|
| 982 |
+
pred_n = normalizer_fn(pred)
|
| 983 |
+
ref_words = ref_n.split()
|
| 984 |
+
pred_words = pred_n.split()
|
| 985 |
+
if ref_words:
|
| 986 |
+
sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words)
|
| 987 |
+
total_subs += sub_c
|
| 988 |
+
total_dels += del_c
|
| 989 |
+
total_ins += ins_c
|
| 990 |
+
total_edits += sub_c + del_c + ins_c
|
| 991 |
+
total_words += len(ref_words)
|
| 992 |
+
|
| 993 |
+
if len(examples) < 5:
|
| 994 |
+
examples.append((s["text"][:55], pred[:55]))
|
| 995 |
+
|
| 996 |
+
except Exception as e:
|
| 997 |
+
errors += 1
|
| 998 |
+
if errors <= 3 and rank == 0:
|
| 999 |
+
print(f" [batch eval error] {type(e).__name__}: {e}")
|
| 1000 |
+
|
| 1001 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 1002 |
+
|
| 1003 |
+
if normalizer_fn is normalize_text and rank == 0: # Only print examples for primary eval
|
| 1004 |
+
print(f"\n {'Reference':<55} | {'Prediction':<55}")
|
| 1005 |
+
print(f" {'-'*55} | {'-'*55}")
|
| 1006 |
+
for ref, pred in examples:
|
| 1007 |
+
print(f" {ref:<55} | {pred:<55}")
|
| 1008 |
+
if errors:
|
| 1009 |
+
print(f" ({errors} batch eval errors)")
|
| 1010 |
+
|
| 1011 |
+
model.train()
|
| 1012 |
+
return wer_score, total_subs, total_dels, total_ins, total_words
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
@torch.no_grad()
|
| 1016 |
+
def evaluate_streaming(student, manifest_path, device, max_samples=None, rank=0):
|
| 1017 |
+
"""Evaluate WER using streaming inference."""
|
| 1018 |
+
import soundfile as sf_eval
|
| 1019 |
+
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
|
| 1020 |
+
|
| 1021 |
+
model = student.module if isinstance(student, DDP) else student
|
| 1022 |
+
model.eval()
|
| 1023 |
+
|
| 1024 |
+
right_context = 13
|
| 1025 |
+
chunk_frames = 1 + right_context
|
| 1026 |
+
model.encoder.setup_streaming_params(
|
| 1027 |
+
chunk_size=chunk_frames,
|
| 1028 |
+
shift_size=chunk_frames,
|
| 1029 |
+
left_chunks=70 // max(chunk_frames, 1),
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
samples = []
|
| 1033 |
+
with open(manifest_path) as f:
|
| 1034 |
+
for line in f:
|
| 1035 |
+
samples.append(json.loads(line))
|
| 1036 |
+
if max_samples and len(samples) > max_samples:
|
| 1037 |
+
samples = samples[:max_samples]
|
| 1038 |
+
|
| 1039 |
+
total_edits, total_words = 0, 0
|
| 1040 |
+
total_subs, total_dels, total_ins = 0, 0, 0
|
| 1041 |
+
examples = []
|
| 1042 |
+
errors = 0
|
| 1043 |
+
|
| 1044 |
+
for s in samples:
|
| 1045 |
+
try:
|
| 1046 |
+
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
|
| 1047 |
+
if len(audio.shape) > 1:
|
| 1048 |
+
audio = audio.mean(axis=1)
|
| 1049 |
+
|
| 1050 |
+
buffer = CacheAwareStreamingAudioBuffer(model=model)
|
| 1051 |
+
buffer.append_audio(audio)
|
| 1052 |
+
|
| 1053 |
+
cache_last_channel, cache_last_time, cache_last_channel_len = \
|
| 1054 |
+
model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
|
| 1055 |
+
previous_hypotheses = None
|
| 1056 |
+
pred = ""
|
| 1057 |
+
|
| 1058 |
+
for chunk_audio, chunk_len in buffer:
|
| 1059 |
+
if chunk_audio is None:
|
| 1060 |
+
break
|
| 1061 |
+
result = model.conformer_stream_step(
|
| 1062 |
+
processed_signal=chunk_audio,
|
| 1063 |
+
processed_signal_length=chunk_len,
|
| 1064 |
+
cache_last_channel=cache_last_channel,
|
| 1065 |
+
cache_last_time=cache_last_time,
|
| 1066 |
+
cache_last_channel_len=cache_last_channel_len,
|
| 1067 |
+
previous_hypotheses=previous_hypotheses,
|
| 1068 |
+
return_transcription=True,
|
| 1069 |
+
)
|
| 1070 |
+
if isinstance(result, tuple) and len(result) >= 6:
|
| 1071 |
+
cache_last_channel = result[2]
|
| 1072 |
+
cache_last_time = result[3]
|
| 1073 |
+
cache_last_channel_len = result[4]
|
| 1074 |
+
previous_hypotheses = result[5]
|
| 1075 |
+
if result[5] and len(result[5]) > 0:
|
| 1076 |
+
hyp = result[5][0]
|
| 1077 |
+
new_text = ""
|
| 1078 |
+
if hasattr(hyp, 'text') and hyp.text:
|
| 1079 |
+
new_text = hyp.text
|
| 1080 |
+
elif hasattr(hyp, 'y_sequence'):
|
| 1081 |
+
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
|
| 1082 |
+
if tids:
|
| 1083 |
+
new_text = model.tokenizer.ids_to_text(tids)
|
| 1084 |
+
if new_text and len(new_text) > len(pred):
|
| 1085 |
+
pred = new_text
|
| 1086 |
+
|
| 1087 |
+
ref_n = normalize_text(s["text"])
|
| 1088 |
+
pred_n = normalize_text(pred)
|
| 1089 |
+
ref_words = ref_n.split()
|
| 1090 |
+
pred_words = pred_n.split()
|
| 1091 |
+
|
| 1092 |
+
if ref_words:
|
| 1093 |
+
sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words)
|
| 1094 |
+
total_subs += sub_c
|
| 1095 |
+
total_dels += del_c
|
| 1096 |
+
total_ins += ins_c
|
| 1097 |
+
total_edits += sub_c + del_c + ins_c
|
| 1098 |
+
total_words += len(ref_words)
|
| 1099 |
+
|
| 1100 |
+
if len(examples) < 5:
|
| 1101 |
+
examples.append((s["text"][:55], pred[:55]))
|
| 1102 |
+
|
| 1103 |
+
except Exception as e:
|
| 1104 |
+
errors += 1
|
| 1105 |
+
if errors <= 3 and rank == 0:
|
| 1106 |
+
print(f" [streaming eval error] {type(e).__name__}: {e}")
|
| 1107 |
+
|
| 1108 |
+
wer_score = total_edits / max(total_words, 1) * 100
|
| 1109 |
+
|
| 1110 |
+
if rank == 0:
|
| 1111 |
+
print(f"\n {'Reference':<55} | {'Prediction':<55}")
|
| 1112 |
+
print(f" {'-'*55} | {'-'*55}")
|
| 1113 |
+
for ref, pred in examples:
|
| 1114 |
+
print(f" {ref:<55} | {pred:<55}")
|
| 1115 |
+
if errors:
|
| 1116 |
+
print(f" ({errors} samples failed)")
|
| 1117 |
+
|
| 1118 |
+
model.train()
|
| 1119 |
+
return wer_score, total_subs, total_dels, total_ins, total_words
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
@torch.no_grad()
|
| 1123 |
+
def compute_val_loss(student, manifest_path, device, max_samples=500):
|
| 1124 |
+
"""Compute RNNT loss on validation set."""
|
| 1125 |
+
import soundfile as sf_val
|
| 1126 |
+
|
| 1127 |
+
model = student.module if isinstance(student, DDP) else student
|
| 1128 |
+
model.eval()
|
| 1129 |
+
|
| 1130 |
+
samples = []
|
| 1131 |
+
with open(manifest_path) as f:
|
| 1132 |
+
for line in f:
|
| 1133 |
+
samples.append(json.loads(line))
|
| 1134 |
+
if max_samples and len(samples) > max_samples:
|
| 1135 |
+
samples = samples[:max_samples]
|
| 1136 |
+
|
| 1137 |
+
total_loss = 0.0
|
| 1138 |
+
count = 0
|
| 1139 |
+
|
| 1140 |
+
for s in samples:
|
| 1141 |
+
try:
|
| 1142 |
+
audio, sr = sf_val.read(s["audio_filepath"], dtype="float32")
|
| 1143 |
+
if len(audio.shape) > 1:
|
| 1144 |
+
audio = audio.mean(axis=1)
|
| 1145 |
+
|
| 1146 |
+
text = unicodedata.normalize("NFKC", s["text"])
|
| 1147 |
+
text = " ".join(text.split())
|
| 1148 |
+
tokens = model.tokenizer.text_to_ids(text)
|
| 1149 |
+
if not tokens:
|
| 1150 |
+
continue
|
| 1151 |
+
|
| 1152 |
+
audio_tensor = torch.FloatTensor(audio).unsqueeze(0).to(device)
|
| 1153 |
+
audio_len = torch.LongTensor([len(audio)]).to(device)
|
| 1154 |
+
token_tensor = torch.LongTensor([tokens]).to(device)
|
| 1155 |
+
token_len = torch.LongTensor([len(tokens)]).to(device)
|
| 1156 |
+
|
| 1157 |
+
mel, mel_len = model.preprocessor(input_signal=audio_tensor, length=audio_len)
|
| 1158 |
+
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
|
| 1159 |
+
dec_out = model.decoder(targets=token_tensor, target_length=token_len)
|
| 1160 |
+
if isinstance(dec_out, tuple):
|
| 1161 |
+
dec_out = dec_out[0]
|
| 1162 |
+
|
| 1163 |
+
if getattr(model.joint, 'fuse_loss_wer', False):
|
| 1164 |
+
result = model.joint(
|
| 1165 |
+
encoder_outputs=enc, decoder_outputs=dec_out,
|
| 1166 |
+
encoder_lengths=enc_len, transcripts=token_tensor,
|
| 1167 |
+
transcript_lengths=token_len, compute_wer=False,
|
| 1168 |
+
)
|
| 1169 |
+
loss = result[0]
|
| 1170 |
+
else:
|
| 1171 |
+
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
|
| 1172 |
+
loss = model.loss(log_probs=joint_out, targets=token_tensor,
|
| 1173 |
+
input_lengths=enc_len, target_lengths=token_len)
|
| 1174 |
+
|
| 1175 |
+
if loss.dim() > 0:
|
| 1176 |
+
loss = loss.mean()
|
| 1177 |
+
total_loss += loss.item()
|
| 1178 |
+
count += 1
|
| 1179 |
+
except Exception:
|
| 1180 |
+
continue
|
| 1181 |
+
|
| 1182 |
+
model.train()
|
| 1183 |
+
return total_loss / max(count, 1)
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
# ═══════════════════════════════════════════════════════════
|
| 1187 |
+
# LR Schedule
|
| 1188 |
+
# ═══════════════════════════════════════════════════════════
|
| 1189 |
+
|
| 1190 |
+
def get_cosine_schedule(optimizer, warmup_steps, total_steps, min_lr=1e-6):
|
| 1191 |
+
base_lr = optimizer.defaults["lr"]
|
| 1192 |
+
|
| 1193 |
+
def lr_lambda(step):
|
| 1194 |
+
if step < warmup_steps:
|
| 1195 |
+
return max(1e-8 / base_lr, step / max(1, warmup_steps))
|
| 1196 |
+
progress = min(1.0, (step - warmup_steps) / max(1, total_steps - warmup_steps))
|
| 1197 |
+
return (min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * progress))) / base_lr
|
| 1198 |
+
|
| 1199 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
def get_constant_schedule(optimizer, warmup_steps):
|
| 1203 |
+
base_lr = optimizer.defaults["lr"]
|
| 1204 |
+
|
| 1205 |
+
def lr_lambda(step):
|
| 1206 |
+
if step < warmup_steps:
|
| 1207 |
+
return max(1e-8 / base_lr, step / max(1, warmup_steps))
|
| 1208 |
+
return 1.0
|
| 1209 |
+
|
| 1210 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 1211 |
+
|
| 1212 |
+
|
| 1213 |
+
# ═══════════════════════════════════════════════════════════
|
| 1214 |
+
# Main Training Loop
|
| 1215 |
+
# ═══════════════════════════════════════════════════════════
|
| 1216 |
+
|
| 1217 |
+
def train(student, train_loader, train_sampler, args, device, rank, is_distributed):
|
| 1218 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 1219 |
+
|
| 1220 |
+
lang = args.lang.upper()
|
| 1221 |
+
model = student.module if isinstance(student, DDP) else student
|
| 1222 |
+
|
| 1223 |
+
trainable_params = [p for p in student.parameters() if p.requires_grad]
|
| 1224 |
+
optimizer = torch.optim.AdamW(
|
| 1225 |
+
trainable_params,
|
| 1226 |
+
lr=args.lr,
|
| 1227 |
+
weight_decay=args.weight_decay,
|
| 1228 |
+
betas=(0.9, 0.98),
|
| 1229 |
+
eps=1e-9,
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
steps_per_epoch = len(train_loader) // args.grad_accum
|
| 1233 |
+
total_steps = steps_per_epoch * args.epochs
|
| 1234 |
+
warmup_steps = steps_per_epoch * args.warmup_epochs
|
| 1235 |
+
|
| 1236 |
+
if args.constant_lr:
|
| 1237 |
+
scheduler = get_constant_schedule(optimizer, warmup_steps)
|
| 1238 |
+
else:
|
| 1239 |
+
decay_epochs = args.lr_decay_epochs if args.lr_decay_epochs > 0 else args.epochs
|
| 1240 |
+
cosine_total_steps = steps_per_epoch * decay_epochs
|
| 1241 |
+
scheduler = get_cosine_schedule(optimizer, warmup_steps, cosine_total_steps, args.min_lr)
|
| 1242 |
+
|
| 1243 |
+
use_amp = args.bf16 or args.fp16
|
| 1244 |
+
amp_dtype = torch.bfloat16 if args.bf16 else torch.float16
|
| 1245 |
+
scaler = torch.amp.GradScaler("cuda") if args.fp16 else None
|
| 1246 |
+
|
| 1247 |
+
effective_batch = args.batch_size * args.grad_accum
|
| 1248 |
+
if is_distributed:
|
| 1249 |
+
world_size = dist.get_world_size()
|
| 1250 |
+
effective_batch *= world_size
|
| 1251 |
+
else:
|
| 1252 |
+
world_size = 1
|
| 1253 |
+
|
| 1254 |
+
starting_from = args.resume_from if args.resume_from else args.student
|
| 1255 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1256 |
+
print_rank0(f" {lang} Training Configuration", rank)
|
| 1257 |
+
print_rank0(f"{'='*65}", rank)
|
| 1258 |
+
print_rank0(f" Language: {lang}", rank)
|
| 1259 |
+
print_rank0(f" Starting from: {starting_from}", rank)
|
| 1260 |
+
print_rank0(f" GPUs: {world_size}", rank)
|
| 1261 |
+
print_rank0(f" Train samples: {len(train_loader.dataset)}", rank)
|
| 1262 |
+
print_rank0(f" Per-GPU batch: {args.batch_size}", rank)
|
| 1263 |
+
print_rank0(f" Effective batch: {args.batch_size} x {args.grad_accum} x {world_size} = {effective_batch}", rank)
|
| 1264 |
+
print_rank0(f" Steps/epoch: {steps_per_epoch}", rank)
|
| 1265 |
+
print_rank0(f" Total steps: {total_steps}", rank)
|
| 1266 |
+
print_rank0(f" Warmup steps: {warmup_steps}", rank)
|
| 1267 |
+
print_rank0(f" Learning rate: {args.lr} ({'constant' if args.constant_lr else 'cosine decay'})", rank)
|
| 1268 |
+
print_rank0(f" Min LR: {args.min_lr}", rank)
|
| 1269 |
+
print_rank0(f" Freeze encoder: first {args.freeze_encoder_epochs} epochs", rank)
|
| 1270 |
+
print_rank0(f" Mixed precision: {'bf16' if args.bf16 else 'fp16' if args.fp16 else 'off'}", rank)
|
| 1271 |
+
print_rank0(f" Weight decay: {args.weight_decay}", rank)
|
| 1272 |
+
print_rank0(f" Grad clip norm: {args.grad_clip}", rank)
|
| 1273 |
+
if args.no_spec_augment:
|
| 1274 |
+
print_rank0(f" SpecAugment: OFF", rank)
|
| 1275 |
+
else:
|
| 1276 |
+
print_rank0(f" SpecAugment: freq={args.freq_masks}x{args.freq_width} time={args.time_masks}x{args.time_width}", rank)
|
| 1277 |
+
print_rank0(f" Speed perturb: {args.speed_perturb_factors if args.speed_perturb else 'OFF'}", rank)
|
| 1278 |
+
print_rank0(f" LR decay epochs: {args.lr_decay_epochs}", rank)
|
| 1279 |
+
print_rank0(f" Early stop: {args.early_stop_patience} epochs", rank)
|
| 1280 |
+
if args.confidence_penalty > 0:
|
| 1281 |
+
print_rank0(f" Confidence penalty: {args.confidence_penalty}", rank)
|
| 1282 |
+
if args.streaming_chunk_sec > 0:
|
| 1283 |
+
print_rank0(f" Streaming train: forced att_context=[70,13] only", rank)
|
| 1284 |
+
print_rank0(f" Val manifest: {args.val_manifest}", rank)
|
| 1285 |
+
print_rank0(f"{'='*65}\n", rank)
|
| 1286 |
+
|
| 1287 |
+
global_step = 0
|
| 1288 |
+
best_wer = float("inf")
|
| 1289 |
+
best_val_loss = float("inf")
|
| 1290 |
+
patience_counter = 0
|
| 1291 |
+
start_epoch = 0
|
| 1292 |
+
|
| 1293 |
+
# Track top-K best WER checkpoints
|
| 1294 |
+
top_k_wer = 3
|
| 1295 |
+
top_k_checkpoints = [] # list of (wer, epoch, path)
|
| 1296 |
+
|
| 1297 |
+
# Track WER per epoch for convergence analysis
|
| 1298 |
+
wer_history = []
|
| 1299 |
+
|
| 1300 |
+
import time as time_module
|
| 1301 |
+
|
| 1302 |
+
# Resume from training checkpoint if specified
|
| 1303 |
+
if args.resume_training:
|
| 1304 |
+
ckpt_path = args.resume_training
|
| 1305 |
+
if os.path.isdir(ckpt_path):
|
| 1306 |
+
# Load latest model weights if available
|
| 1307 |
+
latest_model_path = os.path.join(ckpt_path, "latest_model.pt")
|
| 1308 |
+
if os.path.exists(latest_model_path):
|
| 1309 |
+
print_rank0(f" Loading latest model weights from: {latest_model_path}", rank)
|
| 1310 |
+
sd = torch.load(latest_model_path, map_location=device, weights_only=False)
|
| 1311 |
+
model.load_state_dict(sd)
|
| 1312 |
+
del sd
|
| 1313 |
+
torch.cuda.empty_cache()
|
| 1314 |
+
ckpt_path = os.path.join(ckpt_path, "training_state.pt")
|
| 1315 |
+
if os.path.exists(ckpt_path):
|
| 1316 |
+
print_rank0(f" Resuming training state from: {ckpt_path}", rank)
|
| 1317 |
+
ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
|
| 1318 |
+
optimizer.load_state_dict(ckpt["optimizer"])
|
| 1319 |
+
scheduler.load_state_dict(ckpt["scheduler"])
|
| 1320 |
+
start_epoch = ckpt["epoch"]
|
| 1321 |
+
global_step = ckpt["global_step"]
|
| 1322 |
+
best_wer = ckpt["best_wer"]
|
| 1323 |
+
best_val_loss = ckpt["best_val_loss"]
|
| 1324 |
+
patience_counter = ckpt["patience_counter"]
|
| 1325 |
+
wer_history = ckpt.get("wer_history", [])
|
| 1326 |
+
if scaler and "scaler" in ckpt:
|
| 1327 |
+
scaler.load_state_dict(ckpt["scaler"])
|
| 1328 |
+
print_rank0(f" Resumed at epoch {start_epoch}, step {global_step}, best_wer={best_wer:.2f}%", rank)
|
| 1329 |
+
del ckpt
|
| 1330 |
+
torch.cuda.empty_cache()
|
| 1331 |
+
else:
|
| 1332 |
+
print_rank0(f" WARNING: resume_training path not found: {ckpt_path}", rank)
|
| 1333 |
+
|
| 1334 |
+
if is_distributed:
|
| 1335 |
+
dist.barrier()
|
| 1336 |
+
|
| 1337 |
+
# ── Epoch 0: evaluate before any training ──
|
| 1338 |
+
if start_epoch == 0:
|
| 1339 |
+
print_rank0(f"\n === Epoch 0 (pre-training baseline) ===", rank)
|
| 1340 |
+
import sys as _sys
|
| 1341 |
+
|
| 1342 |
+
# Compute initial train loss + grad norm on first few batches (all ranks)
|
| 1343 |
+
student.train()
|
| 1344 |
+
e0_loss = 0.0
|
| 1345 |
+
e0_gnorm = 0.0
|
| 1346 |
+
e0_steps = 0
|
| 1347 |
+
e0_max_batches = 20
|
| 1348 |
+
for batch_idx, batch in enumerate(train_loader):
|
| 1349 |
+
if batch is None:
|
| 1350 |
+
continue
|
| 1351 |
+
if batch_idx >= e0_max_batches:
|
| 1352 |
+
break
|
| 1353 |
+
try:
|
| 1354 |
+
if use_amp:
|
| 1355 |
+
with torch.amp.autocast("cuda", dtype=amp_dtype):
|
| 1356 |
+
loss = train_step(student, batch, device, confidence_penalty=0.0)
|
| 1357 |
+
loss.backward()
|
| 1358 |
+
else:
|
| 1359 |
+
loss = train_step(student, batch, device, confidence_penalty=0.0)
|
| 1360 |
+
loss.backward()
|
| 1361 |
+
trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
|
| 1362 |
+
gnorm = torch.nn.utils.clip_grad_norm_(trainable, 1e6).item()
|
| 1363 |
+
e0_loss += loss.item()
|
| 1364 |
+
if math.isfinite(gnorm):
|
| 1365 |
+
e0_gnorm += gnorm
|
| 1366 |
+
e0_steps += 1
|
| 1367 |
+
optimizer.zero_grad()
|
| 1368 |
+
except Exception:
|
| 1369 |
+
optimizer.zero_grad()
|
| 1370 |
+
continue
|
| 1371 |
+
|
| 1372 |
+
if e0_steps > 0:
|
| 1373 |
+
print_rank0(f" Epoch 0 train_loss={e0_loss/e0_steps:.4f} gnorm={e0_gnorm/e0_steps:.3f} (avg over {e0_steps} batches)", rank)
|
| 1374 |
+
|
| 1375 |
+
# Tear down DDP before eval (same as regular epoch eval)
|
| 1376 |
+
if is_distributed:
|
| 1377 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1378 |
+
del student
|
| 1379 |
+
student = None
|
| 1380 |
+
torch.cuda.empty_cache()
|
| 1381 |
+
dist.barrier()
|
| 1382 |
+
|
| 1383 |
+
# Free GPU memory before eval
|
| 1384 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1385 |
+
opt_state_backup_e0 = {}
|
| 1386 |
+
for k, v in optimizer.state.items():
|
| 1387 |
+
opt_state_backup_e0[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()}
|
| 1388 |
+
optimizer.state.clear()
|
| 1389 |
+
torch.cuda.empty_cache()
|
| 1390 |
+
gc.collect()
|
| 1391 |
+
|
| 1392 |
+
# Evaluate WER + val_loss (all ranks run forward passes)
|
| 1393 |
+
print_rank0(f"\n Evaluating {lang} (epoch 0)...", rank)
|
| 1394 |
+
_sys.stdout.flush()
|
| 1395 |
+
val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank)
|
| 1396 |
+
print_rank0(f" [eval] WER done", rank); _sys.stdout.flush()
|
| 1397 |
+
val_loss = compute_val_loss(model, args.val_manifest, device)
|
| 1398 |
+
print_rank0(f" [eval] val_loss done", rank); _sys.stdout.flush()
|
| 1399 |
+
|
| 1400 |
+
if is_main(rank):
|
| 1401 |
+
print_rank0(f" Epoch 0 WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank)
|
| 1402 |
+
wer_history.append({
|
| 1403 |
+
'epoch': 0,
|
| 1404 |
+
'wer': val_wer,
|
| 1405 |
+
'val_loss': val_loss,
|
| 1406 |
+
'lr': 0.0,
|
| 1407 |
+
'train_loss': e0_loss / max(1, e0_steps),
|
| 1408 |
+
})
|
| 1409 |
+
_sys.stdout.flush()
|
| 1410 |
+
|
| 1411 |
+
# Restore optimizer states from CPU
|
| 1412 |
+
for k, v in opt_state_backup_e0.items():
|
| 1413 |
+
optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()}
|
| 1414 |
+
del opt_state_backup_e0
|
| 1415 |
+
torch.cuda.empty_cache()
|
| 1416 |
+
|
| 1417 |
+
# Rebuild DDP for training
|
| 1418 |
+
if is_distributed:
|
| 1419 |
+
student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True)
|
| 1420 |
+
optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad]
|
| 1421 |
+
|
| 1422 |
+
# Reset dataloader state
|
| 1423 |
+
if train_sampler is not None:
|
| 1424 |
+
train_sampler.set_epoch(0)
|
| 1425 |
+
|
| 1426 |
+
for epoch in range(start_epoch, args.epochs):
|
| 1427 |
+
epoch_start = time_module.time()
|
| 1428 |
+
student.train()
|
| 1429 |
+
|
| 1430 |
+
# Decay SpecAugment if enabled (all ranks need updated module)
|
| 1431 |
+
if args.decay_spec_augment:
|
| 1432 |
+
update_spec_augment(student, args, epoch, args.epochs, rank)
|
| 1433 |
+
|
| 1434 |
+
if train_sampler is not None:
|
| 1435 |
+
train_sampler.set_epoch(epoch)
|
| 1436 |
+
|
| 1437 |
+
# Phase management
|
| 1438 |
+
if epoch < args.freeze_encoder_epochs:
|
| 1439 |
+
for p in model.encoder.parameters():
|
| 1440 |
+
p.requires_grad = False
|
| 1441 |
+
phase = f"Encoder frozen ({epoch+1}/{args.freeze_encoder_epochs})"
|
| 1442 |
+
else:
|
| 1443 |
+
for p in model.encoder.parameters():
|
| 1444 |
+
p.requires_grad = True
|
| 1445 |
+
phase = "Full training"
|
| 1446 |
+
|
| 1447 |
+
optimizer.param_groups[0]["params"] = [
|
| 1448 |
+
p for p in student.parameters() if p.requires_grad
|
| 1449 |
+
]
|
| 1450 |
+
|
| 1451 |
+
epoch_loss = 0.0
|
| 1452 |
+
epoch_steps = 0
|
| 1453 |
+
epoch_grad_norm = 0.0
|
| 1454 |
+
grad_norm_steps = 0
|
| 1455 |
+
inf_grad_steps = 0
|
| 1456 |
+
|
| 1457 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{args.epochs} [{lang}]",
|
| 1458 |
+
leave=True, ncols=120, disable=not is_main(rank) or not sys.stderr.isatty())
|
| 1459 |
+
optimizer.zero_grad()
|
| 1460 |
+
|
| 1461 |
+
max_batch_audio_sec = 0.0
|
| 1462 |
+
batch_lengths = []
|
| 1463 |
+
|
| 1464 |
+
for batch_idx, batch in enumerate(pbar):
|
| 1465 |
+
if batch is None:
|
| 1466 |
+
continue
|
| 1467 |
+
|
| 1468 |
+
# Track batch audio lengths
|
| 1469 |
+
audio, audio_len_t, _, _ = batch
|
| 1470 |
+
max_audio_samples = audio_len_t.max().item()
|
| 1471 |
+
total_audio_samples = audio_len_t.sum().item()
|
| 1472 |
+
max_sec = max_audio_samples / 16000
|
| 1473 |
+
total_sec = total_audio_samples / 16000
|
| 1474 |
+
batch_lengths.append(max_sec)
|
| 1475 |
+
if max_sec > max_batch_audio_sec:
|
| 1476 |
+
max_batch_audio_sec = max_sec
|
| 1477 |
+
|
| 1478 |
+
try:
|
| 1479 |
+
if use_amp:
|
| 1480 |
+
with torch.amp.autocast("cuda", dtype=amp_dtype):
|
| 1481 |
+
loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty)
|
| 1482 |
+
if scaler:
|
| 1483 |
+
scaled_loss = loss / args.grad_accum
|
| 1484 |
+
scaler.scale(scaled_loss).backward()
|
| 1485 |
+
else:
|
| 1486 |
+
(loss / args.grad_accum).backward()
|
| 1487 |
+
else:
|
| 1488 |
+
loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty)
|
| 1489 |
+
(loss / args.grad_accum).backward()
|
| 1490 |
+
|
| 1491 |
+
except RuntimeError as e:
|
| 1492 |
+
if "out of memory" in str(e).lower():
|
| 1493 |
+
torch.cuda.empty_cache()
|
| 1494 |
+
print_rank0(f"\n OOM at batch {batch_idx} (max_audio={max_sec:.1f}s, total={total_sec:.1f}s, batch_size={len(audio_len_t)}), skipping", rank)
|
| 1495 |
+
optimizer.zero_grad()
|
| 1496 |
+
continue
|
| 1497 |
+
raise
|
| 1498 |
+
|
| 1499 |
+
epoch_loss += loss.item()
|
| 1500 |
+
epoch_steps += 1
|
| 1501 |
+
|
| 1502 |
+
if (batch_idx + 1) % args.grad_accum == 0:
|
| 1503 |
+
if scaler:
|
| 1504 |
+
scaler.unscale_(optimizer)
|
| 1505 |
+
trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
|
| 1506 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(trainable, args.grad_clip).item()
|
| 1507 |
+
if scaler:
|
| 1508 |
+
scaler.step(optimizer)
|
| 1509 |
+
scaler.update()
|
| 1510 |
+
else:
|
| 1511 |
+
optimizer.step()
|
| 1512 |
+
|
| 1513 |
+
if math.isfinite(grad_norm):
|
| 1514 |
+
epoch_grad_norm += grad_norm
|
| 1515 |
+
grad_norm_steps += 1
|
| 1516 |
+
else:
|
| 1517 |
+
inf_grad_steps += 1
|
| 1518 |
+
scheduler.step()
|
| 1519 |
+
optimizer.zero_grad()
|
| 1520 |
+
global_step += 1
|
| 1521 |
+
|
| 1522 |
+
if epoch_steps % args.log_every == 0 and epoch_steps > 0 and is_main(rank):
|
| 1523 |
+
avg_loss = epoch_loss / epoch_steps
|
| 1524 |
+
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
|
| 1525 |
+
lr = optimizer.param_groups[0]["lr"]
|
| 1526 |
+
gnorm_str = f"{avg_gnorm:.2f}" if grad_norm_steps > 0 else "n/a"
|
| 1527 |
+
if inf_grad_steps > 0:
|
| 1528 |
+
gnorm_str += f" ({inf_grad_steps} skipped)"
|
| 1529 |
+
pbar.set_postfix(loss=f"{avg_loss:.3f}", gnorm=gnorm_str,
|
| 1530 |
+
lr=f"{lr:.1e}", step=global_step)
|
| 1531 |
+
|
| 1532 |
+
# End of epoch
|
| 1533 |
+
epoch_time = time_module.time() - epoch_start
|
| 1534 |
+
avg_loss = epoch_loss / max(1, epoch_steps)
|
| 1535 |
+
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
|
| 1536 |
+
gnorm_display = f"{avg_gnorm:.3f}" if grad_norm_steps > 0 else "n/a"
|
| 1537 |
+
if inf_grad_steps > 0:
|
| 1538 |
+
gnorm_display += f" ({inf_grad_steps} inf-skipped)"
|
| 1539 |
+
samples_per_sec = (epoch_steps * args.batch_size) / epoch_time
|
| 1540 |
+
gpu_mem = torch.cuda.max_memory_allocated(device) / 1e9 if torch.cuda.is_available() else 0
|
| 1541 |
+
|
| 1542 |
+
# Batch length stats
|
| 1543 |
+
if batch_lengths:
|
| 1544 |
+
avg_max_sec = sum(batch_lengths) / len(batch_lengths)
|
| 1545 |
+
p95 = sorted(batch_lengths)[int(0.95 * len(batch_lengths))]
|
| 1546 |
+
print_rank0(f" [batch stats] max_audio={max_batch_audio_sec:.1f}s avg_max={avg_max_sec:.1f}s p95={p95:.1f}s", rank)
|
| 1547 |
+
|
| 1548 |
+
print_rank0(f"\n Epoch {epoch+1} [{lang}] | {phase} | loss={avg_loss:.4f} "
|
| 1549 |
+
f"gnorm={gnorm_display} lr={optimizer.param_groups[0]['lr']:.2e}"
|
| 1550 |
+
f" | {epoch_time/60:.1f}min | {samples_per_sec:.0f} samples/s | GPU: {gpu_mem:.1f}GB", rank)
|
| 1551 |
+
|
| 1552 |
+
# Tear down DDP before eval to remove forward hooks from model.
|
| 1553 |
+
# DDP with find_unused_parameters=True registers hooks on the underlying
|
| 1554 |
+
# model, so calling model.forward() during rank-0-only eval would trigger
|
| 1555 |
+
# DDP communication and deadlock the other ranks.
|
| 1556 |
+
if is_distributed:
|
| 1557 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1558 |
+
del student
|
| 1559 |
+
student = None
|
| 1560 |
+
torch.cuda.empty_cache()
|
| 1561 |
+
dist.barrier()
|
| 1562 |
+
|
| 1563 |
+
# Free GPU memory before eval: offload optimizer states to CPU
|
| 1564 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1565 |
+
opt_state_backup = {}
|
| 1566 |
+
for k, v in optimizer.state.items():
|
| 1567 |
+
opt_state_backup[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()}
|
| 1568 |
+
optimizer.state.clear()
|
| 1569 |
+
torch.cuda.empty_cache()
|
| 1570 |
+
gc.collect()
|
| 1571 |
+
|
| 1572 |
+
mem_after = torch.cuda.memory_allocated(device) / 1e9
|
| 1573 |
+
print_rank0(f" [pre-eval] GPU mem after offload: {mem_after:.1f}GB", rank)
|
| 1574 |
+
import sys as _sys; _sys.stdout.flush()
|
| 1575 |
+
|
| 1576 |
+
# Evaluation — ALL ranks run forward passes (needed for SyncBatchNorm / distributed
|
| 1577 |
+
# layers inside NeMo encoder), but only rank 0 uses the results.
|
| 1578 |
+
if (epoch + 1) % args.eval_every_epoch == 0:
|
| 1579 |
+
try:
|
| 1580 |
+
print_rank0(f"\n Evaluating {lang}...", rank)
|
| 1581 |
+
_sys.stdout.flush()
|
| 1582 |
+
|
| 1583 |
+
val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank)
|
| 1584 |
+
print_rank0(f" [eval] WER done", rank); _sys.stdout.flush()
|
| 1585 |
+
val_loss = compute_val_loss(model, args.val_manifest, device)
|
| 1586 |
+
print_rank0(f" [eval] val_loss done", rank); _sys.stdout.flush()
|
| 1587 |
+
|
| 1588 |
+
if is_main(rank):
|
| 1589 |
+
print_rank0(f" {lang} Batch WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank)
|
| 1590 |
+
|
| 1591 |
+
wer_history.append({
|
| 1592 |
+
'epoch': epoch + 1,
|
| 1593 |
+
'wer': val_wer,
|
| 1594 |
+
'val_loss': val_loss,
|
| 1595 |
+
'lr': optimizer.param_groups[0]["lr"],
|
| 1596 |
+
'train_loss': avg_loss,
|
| 1597 |
+
})
|
| 1598 |
+
|
| 1599 |
+
if val_wer < best_wer:
|
| 1600 |
+
best_wer = val_wer
|
| 1601 |
+
patience_counter = 0
|
| 1602 |
+
save_path = os.path.join(args.output_dir, "best_model.nemo")
|
| 1603 |
+
print_rank0(f" [saving] best_model.nemo...", rank); _sys.stdout.flush()
|
| 1604 |
+
model.save_to(save_path)
|
| 1605 |
+
print_rank0(f" New best WER! WER={best_wer:.2f}% -> {save_path}", rank)
|
| 1606 |
+
else:
|
| 1607 |
+
patience_counter += 1
|
| 1608 |
+
print_rank0(f" No WER improvement ({patience_counter}/{args.early_stop_patience})", rank)
|
| 1609 |
+
|
| 1610 |
+
# Save top-K best WER checkpoints for post-hoc evaluation
|
| 1611 |
+
should_save_topk = len(top_k_checkpoints) < top_k_wer or val_wer < top_k_checkpoints[-1][0]
|
| 1612 |
+
if should_save_topk:
|
| 1613 |
+
topk_path = os.path.join(args.output_dir, f"best_model_wer_ep{epoch+1}.nemo")
|
| 1614 |
+
print_rank0(f" [saving] top-{top_k_wer} checkpoint (WER={val_wer:.2f}%)...", rank); _sys.stdout.flush()
|
| 1615 |
+
model.save_to(topk_path)
|
| 1616 |
+
top_k_checkpoints.append((val_wer, epoch + 1, topk_path))
|
| 1617 |
+
top_k_checkpoints.sort(key=lambda x: x[0]) # sort by WER ascending
|
| 1618 |
+
# Remove worst checkpoint if we exceed top_k_wer
|
| 1619 |
+
while len(top_k_checkpoints) > top_k_wer:
|
| 1620 |
+
_, _, old_path = top_k_checkpoints.pop()
|
| 1621 |
+
if os.path.exists(old_path):
|
| 1622 |
+
os.remove(old_path)
|
| 1623 |
+
print_rank0(f" [removed] {os.path.basename(old_path)}", rank)
|
| 1624 |
+
|
| 1625 |
+
if args.early_stop_patience > 0 and patience_counter >= args.early_stop_patience:
|
| 1626 |
+
print_rank0(f"\n Early stopping! No improvement for {args.early_stop_patience} epochs.", rank)
|
| 1627 |
+
break
|
| 1628 |
+
|
| 1629 |
+
if val_loss < best_val_loss:
|
| 1630 |
+
best_val_loss = val_loss
|
| 1631 |
+
save_path = os.path.join(args.output_dir, "best_model_loss.nemo")
|
| 1632 |
+
print_rank0(f" [saving] best_model_loss.nemo...", rank); _sys.stdout.flush()
|
| 1633 |
+
model.save_to(save_path)
|
| 1634 |
+
print_rank0(f" New best loss! loss={best_val_loss:.4f} -> {save_path}", rank)
|
| 1635 |
+
except Exception as e:
|
| 1636 |
+
print_rank0(f" [eval error] {type(e).__name__}: {e} — skipping", rank)
|
| 1637 |
+
|
| 1638 |
+
print_rank0(f" [post-eval] reaching barrier...", rank); sys.stdout.flush()
|
| 1639 |
+
|
| 1640 |
+
# Restore optimizer states from CPU
|
| 1641 |
+
for k, v in opt_state_backup.items():
|
| 1642 |
+
optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()}
|
| 1643 |
+
del opt_state_backup
|
| 1644 |
+
torch.cuda.empty_cache()
|
| 1645 |
+
|
| 1646 |
+
# Rebuild DDP for next training epoch (after eval is done)
|
| 1647 |
+
if is_distributed:
|
| 1648 |
+
student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True)
|
| 1649 |
+
optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad]
|
| 1650 |
+
|
| 1651 |
+
# Save full training state for resumability
|
| 1652 |
+
if is_main(rank) and args.save_every_epoch > 0 and (epoch + 1) % args.save_every_epoch == 0:
|
| 1653 |
+
# Save latest model weights as raw state dict (fast, avoids NeMo save_to overhead)
|
| 1654 |
+
latest_path = os.path.join(args.output_dir, "latest_model.pt")
|
| 1655 |
+
torch.save(model.state_dict(), latest_path + ".tmp")
|
| 1656 |
+
os.replace(latest_path + ".tmp", latest_path)
|
| 1657 |
+
|
| 1658 |
+
state = {
|
| 1659 |
+
"epoch": epoch + 1,
|
| 1660 |
+
"global_step": global_step,
|
| 1661 |
+
"optimizer": optimizer.state_dict(),
|
| 1662 |
+
"scheduler": scheduler.state_dict(),
|
| 1663 |
+
"best_wer": best_wer,
|
| 1664 |
+
"best_val_loss": best_val_loss,
|
| 1665 |
+
"patience_counter": patience_counter,
|
| 1666 |
+
"wer_history": wer_history,
|
| 1667 |
+
}
|
| 1668 |
+
if scaler:
|
| 1669 |
+
state["scaler"] = scaler.state_dict()
|
| 1670 |
+
state_path = os.path.join(args.output_dir, "training_state.pt")
|
| 1671 |
+
torch.save(state, state_path + ".tmp")
|
| 1672 |
+
os.replace(state_path + ".tmp", state_path)
|
| 1673 |
+
|
| 1674 |
+
# Clear GPU memory fragmentation from eval/save before next training epoch
|
| 1675 |
+
torch.cuda.empty_cache()
|
| 1676 |
+
|
| 1677 |
+
if is_distributed:
|
| 1678 |
+
dist.barrier()
|
| 1679 |
+
|
| 1680 |
+
# Save WER history for convergence analysis
|
| 1681 |
+
if is_main(rank):
|
| 1682 |
+
history_path = os.path.join(args.output_dir, "wer_history.json")
|
| 1683 |
+
with open(history_path, "w") as f:
|
| 1684 |
+
json.dump(wer_history, f, indent=2)
|
| 1685 |
+
print_rank0(f"\n WER history saved to {history_path}", rank)
|
| 1686 |
+
|
| 1687 |
+
# Final save
|
| 1688 |
+
save_path = os.path.join(args.output_dir, "final_model.nemo")
|
| 1689 |
+
model.save_to(save_path)
|
| 1690 |
+
print_rank0(f" Final model -> {save_path}", rank)
|
| 1691 |
+
print_rank0(f" Best {lang} WER: {best_wer:.2f}%", rank)
|
| 1692 |
+
|
| 1693 |
+
return student
|
| 1694 |
+
|
| 1695 |
+
|
| 1696 |
+
# ═══════════════════════════════════════════════════════════
|
| 1697 |
+
# Entry Point
|
| 1698 |
+
# ═══════════════════════════════════════════════════════════
|
| 1699 |
+
|
| 1700 |
+
def main():
|
| 1701 |
+
args = parse_args()
|
| 1702 |
+
|
| 1703 |
+
rank, world_size, local_rank, is_distributed = setup_ddp()
|
| 1704 |
+
device = torch.device(f"cuda:{local_rank}")
|
| 1705 |
+
|
| 1706 |
+
torch.manual_seed(args.seed + rank)
|
| 1707 |
+
np.random.seed(args.seed + rank)
|
| 1708 |
+
torch.cuda.manual_seed_all(args.seed + rank)
|
| 1709 |
+
import random
|
| 1710 |
+
random.seed(args.seed + rank)
|
| 1711 |
+
|
| 1712 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 1713 |
+
|
| 1714 |
+
lang = args.lang.upper()
|
| 1715 |
+
starting_from = "multilingual base" if args.resume_from else "English checkpoint"
|
| 1716 |
+
|
| 1717 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1718 |
+
print_rank0(f" Nemotron Streaming ASR — {lang} Training", rank)
|
| 1719 |
+
print_rank0(f"{'='*65}", rank)
|
| 1720 |
+
print_rank0(f" Language: {lang}", rank)
|
| 1721 |
+
print_rank0(f" Path: {starting_from}", rank)
|
| 1722 |
+
print_rank0(f" GPUs: {world_size}", rank)
|
| 1723 |
+
if args.resume_from:
|
| 1724 |
+
print_rank0(f" Base: {args.resume_from}", rank)
|
| 1725 |
+
else:
|
| 1726 |
+
print_rank0(f" Student: {args.student}", rank)
|
| 1727 |
+
print_rank0(f" Train: {args.train_manifest}", rank)
|
| 1728 |
+
print_rank0(f" Val: {args.val_manifest}", rank)
|
| 1729 |
+
print_rank0(f"{'='*65}", rank)
|
| 1730 |
+
|
| 1731 |
+
# Load model
|
| 1732 |
+
print_rank0(f"\n[1/3] Loading model...", rank)
|
| 1733 |
+
student = load_student(args, device, rank)
|
| 1734 |
+
|
| 1735 |
+
# Wrap in DDP
|
| 1736 |
+
if is_distributed:
|
| 1737 |
+
student = DDP(student, device_ids=[local_rank], find_unused_parameters=True)
|
| 1738 |
+
print_rank0(f" Wrapped in DDP (find_unused_parameters=True)", rank)
|
| 1739 |
+
|
| 1740 |
+
# Create dataloader
|
| 1741 |
+
print_rank0(f"\n[2/3] Creating data loaders...", rank)
|
| 1742 |
+
model_for_tok = student.module if isinstance(student, DDP) else student
|
| 1743 |
+
train_dataset = ASRManifestDataset(
|
| 1744 |
+
args.train_manifest,
|
| 1745 |
+
model_for_tok.tokenizer,
|
| 1746 |
+
min_duration=args.min_duration,
|
| 1747 |
+
max_duration=args.max_duration,
|
| 1748 |
+
speed_perturb=args.speed_perturb,
|
| 1749 |
+
speed_perturb_factors=args.speed_perturb_factors,
|
| 1750 |
+
max_train_hours=args.max_train_hours,
|
| 1751 |
+
seed=args.data_seed,
|
| 1752 |
+
)
|
| 1753 |
+
print_rank0(f" Train dataset: {len(train_dataset)} samples", rank)
|
| 1754 |
+
if args.max_train_hours > 0:
|
| 1755 |
+
print_rank0(f" Subsampled to {train_dataset.total_hours:.1f}h (requested {args.max_train_hours}h)", rank)
|
| 1756 |
+
|
| 1757 |
+
# Offset by -42 so --seed=42 (default) keeps PyTorch's default sampler seed=0
|
| 1758 |
+
# for backward compat with prior runs. --seed=43 -> sampler seed=1, etc.
|
| 1759 |
+
train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=args.seed - 42) if is_distributed else None
|
| 1760 |
+
train_loader = DataLoader(
|
| 1761 |
+
train_dataset,
|
| 1762 |
+
batch_size=args.batch_size,
|
| 1763 |
+
shuffle=(train_sampler is None),
|
| 1764 |
+
sampler=train_sampler,
|
| 1765 |
+
num_workers=args.num_workers,
|
| 1766 |
+
collate_fn=collate_asr,
|
| 1767 |
+
pin_memory=True,
|
| 1768 |
+
drop_last=True,
|
| 1769 |
+
)
|
| 1770 |
+
|
| 1771 |
+
# Train
|
| 1772 |
+
print_rank0(f"\n[3/3] Starting {lang} training...", rank)
|
| 1773 |
+
student = train(
|
| 1774 |
+
student, train_loader, train_sampler,
|
| 1775 |
+
args, device, rank, is_distributed,
|
| 1776 |
+
)
|
| 1777 |
+
|
| 1778 |
+
# Final eval on best model — all ranks run eval (NeMo model has distributed internals),
|
| 1779 |
+
# only rank 0 prints/uses results
|
| 1780 |
+
import nemo.collections.asr as nemo_asr
|
| 1781 |
+
|
| 1782 |
+
best_path = os.path.join(args.output_dir, "best_model.nemo")
|
| 1783 |
+
if os.path.exists(best_path):
|
| 1784 |
+
print_rank0(f"\n Loading best model from {best_path}...", rank)
|
| 1785 |
+
best_model = nemo_asr.models.ASRModel.restore_from(best_path, map_location=device)
|
| 1786 |
+
best_model = best_model.to(device)
|
| 1787 |
+
best_model.eval()
|
| 1788 |
+
else:
|
| 1789 |
+
print_rank0(f"\n Best model not found, using final model.", rank)
|
| 1790 |
+
best_model = model
|
| 1791 |
+
|
| 1792 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1793 |
+
print_rank0(f" Final Evaluation — {lang} (best checkpoint)", rank)
|
| 1794 |
+
print_rank0(f"{'='*65}", rank)
|
| 1795 |
+
|
| 1796 |
+
batch_wer, b_s, b_d, b_i, b_w = evaluate_batch(best_model, args.val_manifest, device, rank=rank)
|
| 1797 |
+
if is_main(rank):
|
| 1798 |
+
print_rank0(f" {lang} Val Batch WER: {batch_wer:.2f}% (S={b_s/max(b_w,1)*100:.2f}% D={b_d/max(b_w,1)*100:.2f}% I={b_i/max(b_w,1)*100:.2f}%)", rank)
|
| 1799 |
+
print_rank0(f" Counts: subs={b_s} dels={b_d} ins={b_i} / {b_w} ref words", rank)
|
| 1800 |
+
|
| 1801 |
+
print_rank0(f"\n Running streaming eval...", rank)
|
| 1802 |
+
stream_wer, s_s, s_d, s_i, s_w = evaluate_streaming(best_model, args.val_manifest, device, rank=rank)
|
| 1803 |
+
if is_main(rank):
|
| 1804 |
+
print_rank0(f" {lang} Val Streaming WER: {stream_wer:.2f}% (S={s_s/max(s_w,1)*100:.2f}% D={s_d/max(s_w,1)*100:.2f}% I={s_i/max(s_w,1)*100:.2f}%)", rank)
|
| 1805 |
+
print_rank0(f" Counts: subs={s_s} dels={s_d} ins={s_i} / {s_w} ref words", rank)
|
| 1806 |
+
|
| 1807 |
+
if args.test_manifest:
|
| 1808 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1809 |
+
print_rank0(f" Test Evaluation — {lang} (best checkpoint)", rank)
|
| 1810 |
+
print_rank0(f"{'='*65}", rank)
|
| 1811 |
+
|
| 1812 |
+
test_batch_wer, tb_s, tb_d, tb_i, tb_w = evaluate_batch(best_model, args.test_manifest, device, rank=rank)
|
| 1813 |
+
if is_main(rank):
|
| 1814 |
+
print_rank0(f" {lang} Test Batch WER: {test_batch_wer:.2f}% (S={tb_s/max(tb_w,1)*100:.2f}% D={tb_d/max(tb_w,1)*100:.2f}% I={tb_i/max(tb_w,1)*100:.2f}%)", rank)
|
| 1815 |
+
print_rank0(f" Counts: subs={tb_s} dels={tb_d} ins={tb_i} / {tb_w} ref words", rank)
|
| 1816 |
+
|
| 1817 |
+
print_rank0(f"\n Running streaming test eval...", rank)
|
| 1818 |
+
test_stream_wer, ts_s, ts_d, ts_i, ts_w = evaluate_streaming(best_model, args.test_manifest, device, rank=rank)
|
| 1819 |
+
if is_main(rank):
|
| 1820 |
+
print_rank0(f" {lang} Test Streaming WER: {test_stream_wer:.2f}% (S={ts_s/max(ts_w,1)*100:.2f}% D={ts_d/max(ts_w,1)*100:.2f}% I={ts_i/max(ts_w,1)*100:.2f}%)", rank)
|
| 1821 |
+
print_rank0(f" Counts: subs={ts_s} dels={ts_d} ins={ts_i} / {ts_w} ref words", rank)
|
| 1822 |
+
|
| 1823 |
+
del best_model
|
| 1824 |
+
torch.cuda.empty_cache()
|
| 1825 |
+
|
| 1826 |
+
# Evaluate best-by-loss model if it exists
|
| 1827 |
+
best_loss_path = os.path.join(args.output_dir, "best_model_loss.nemo")
|
| 1828 |
+
if os.path.exists(best_loss_path):
|
| 1829 |
+
print_rank0(f"\n{'='*65}", rank)
|
| 1830 |
+
print_rank0(f" Final Evaluation — {lang} (best loss checkpoint)", rank)
|
| 1831 |
+
print_rank0(f"{'='*65}", rank)
|
| 1832 |
+
|
| 1833 |
+
print_rank0(f" Loading best-by-loss model from {best_loss_path}...", rank)
|
| 1834 |
+
best_loss_model = nemo_asr.models.ASRModel.restore_from(best_loss_path, map_location=device)
|
| 1835 |
+
best_loss_model = best_loss_model.to(device)
|
| 1836 |
+
best_loss_model.eval()
|
| 1837 |
+
|
| 1838 |
+
bl_wer, bl_s, bl_d, bl_i, bl_w = evaluate_batch(best_loss_model, args.val_manifest, device, rank=rank)
|
| 1839 |
+
if is_main(rank):
|
| 1840 |
+
print_rank0(f" {lang} Val Batch WER (loss-best): {bl_wer:.2f}% (S={bl_s/max(bl_w,1)*100:.2f}% D={bl_d/max(bl_w,1)*100:.2f}% I={bl_i/max(bl_w,1)*100:.2f}%)", rank)
|
| 1841 |
+
|
| 1842 |
+
if args.test_manifest:
|
| 1843 |
+
tbl_wer, tbl_s, tbl_d, tbl_i, tbl_w = evaluate_batch(best_loss_model, args.test_manifest, device, rank=rank)
|
| 1844 |
+
if is_main(rank):
|
| 1845 |
+
print_rank0(f" {lang} Test Batch WER (loss-best): {tbl_wer:.2f}% (S={tbl_s/max(tbl_w,1)*100:.2f}% D={tbl_d/max(tbl_w,1)*100:.2f}% I={tbl_i/max(tbl_w,1)*100:.2f}%)", rank)
|
| 1846 |
+
|
| 1847 |
+
del best_loss_model
|
| 1848 |
+
torch.cuda.empty_cache()
|
| 1849 |
+
|
| 1850 |
+
# All ranks must wait for rank 0's final eval before destroying process group
|
| 1851 |
+
if is_distributed:
|
| 1852 |
+
dist.barrier()
|
| 1853 |
+
|
| 1854 |
+
cleanup_ddp(is_distributed)
|
| 1855 |
+
|
| 1856 |
+
|
| 1857 |
+
if __name__ == "__main__":
|
| 1858 |
+
main()
|