File size: 42,411 Bytes
0b3b2a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 | #!/usr/bin/env python3
"""
train_multilingual_nemotron.py
Multi-GPU training of Nemotron-Speech-Streaming for 5 European languages.
Based on distill_parakeet_to_nemotron_german.py, adapted for:
- Multi-GPU (torchrun + DDP)
- Multilingual (DE, ES, FR, IT, NL combined manifest)
- No distillation by default (Stage 1 = pure RNNT fine-tuning)
Usage:
# Multilingual baseline (7 GPUs)
torchrun --nproc_per_node=7 train_multilingual_nemotron.py \
--train_manifest <DATA_ROOT>/combined_train.json \
--val_manifest <VAL_MANIFEST> \
--output_dir ./multilingual_baseline \
--epochs 30 --batch_size 32 --grad_accum 2 --lr 1e-4
Manifest format (one JSON object per line):
{"audio_filepath": "/abs/path/utt.wav", "duration": 8.4, "text": "reference transcript"}
`duration` (seconds) is required for min/max-duration filtering.
Requirements:
pip install nemo_toolkit[asr] soundfile jiwer tqdm
"""
import argparse
import json
import math
import os
import random
import re
import sys
import unicodedata
from collections import defaultdict
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from tqdm import tqdm
# ═══════════════════════════════════════════════════════════
# DDP Utilities
# ═══════════════════════════════════════════════════════════
def setup_ddp():
"""Initialize distributed training. Returns (rank, world_size, is_distributed)."""
if "RANK" in os.environ:
rank = int(os.environ["RANK"])
world_size = int(os.environ["WORLD_SIZE"])
local_rank = int(os.environ["LOCAL_RANK"])
dist.init_process_group("nccl")
torch.cuda.set_device(local_rank)
return rank, world_size, local_rank, True
else:
return 0, 1, 0, False
def cleanup_ddp(is_distributed):
if is_distributed:
dist.destroy_process_group()
def is_main(rank):
return rank == 0
def print_rank0(msg, rank=0):
if is_main(rank):
print(msg, flush=True)
# ═══════════════════════════════════════════════════════════
# Configuration
# ═══════════════════════════════════════════════════════════
def parse_args():
p = argparse.ArgumentParser(
description="Multi-GPU Nemotron Streaming ASR Training (Multilingual)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Models
p.add_argument("--teacher", default="nvidia/parakeet-tdt-0.6b-v3",
help="Teacher model for tokenizer extraction")
p.add_argument("--student", default="nvidia/nemotron-speech-streaming-en-0.6b",
help="Student model (English, streaming)")
# Data — manifests directly
p.add_argument("--train_manifest", type=str, required=True,
help="Path to combined training manifest (JSONL)")
p.add_argument("--val_manifest", type=str, default=None,
help="Path to combined validation manifest (for best model selection)")
p.add_argument("--eval_dir", type=str, default=None,
help="Optional: base dir containing per-language eval/ dirs with "
"validation_manifest.json (used for the per-language WER "
"printout at eval time). Skipped if not set.")
# Training
p.add_argument("--output_dir", default="./multilingual_nemotron")
p.add_argument("--epochs", type=int, default=30)
p.add_argument("--batch_size", type=int, default=32,
help="Per-GPU batch size")
p.add_argument("--grad_accum", type=int, default=2,
help="Gradient accumulation steps")
p.add_argument("--lr", type=float, default=1e-4)
p.add_argument("--min_lr", type=float, default=4e-6)
p.add_argument("--weight_decay", type=float, default=1e-3)
p.add_argument("--warmup_epochs", type=int, default=1)
p.add_argument("--max_duration", type=float, default=20.0)
p.add_argument("--min_duration", type=float, default=0.3)
# SpecAugment
p.add_argument("--no_spec_augment", action="store_true", default=False)
p.add_argument("--freq_masks", type=int, default=2)
p.add_argument("--freq_width", type=int, default=27)
p.add_argument("--time_masks", type=int, default=10)
p.add_argument("--time_width", type=float, default=0.05)
# Speed perturbation
p.add_argument("--speed_perturb", action="store_true", default=True)
p.add_argument("--speed_perturb_factors", type=float, nargs='+', default=[0.9, 1.0, 1.1])
# Misc
p.add_argument("--freeze_encoder_epochs", type=int, default=0,
help="Freeze encoder for first N epochs")
p.add_argument("--constant_lr", action="store_true", default=False)
p.add_argument("--log_every", type=int, default=50)
p.add_argument("--eval_every_epoch", type=int, default=1)
p.add_argument("--save_every_epoch", type=int, default=5)
p.add_argument("--early_stop_patience", type=int, default=3,
help="Stop if WER doesn't improve for N evals (0=disabled)")
p.add_argument("--fp16", action="store_true", default=True)
p.add_argument("--num_workers", type=int, default=4)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--resume_from", type=str, default=None,
help="Resume from .nemo checkpoint (skips tokenizer swap)")
return p.parse_args()
# ═══════════════════════════════════════════════════════════
# Tokenizer Extraction (from teacher)
# ═══════════════════════════════════════════════════════════
def extract_tokenizer(model, tokenizer_dir):
"""Extract tokenizer .model file from a NeMo ASR model."""
from pathlib import Path
import tarfile
os.makedirs(tokenizer_dir, exist_ok=True)
out_model = Path(tokenizer_dir) / "tokenizer.model"
tok = getattr(model, "tokenizer", None)
sp = getattr(tok, "tokenizer", None)
if sp is not None and hasattr(sp, "serialized_model_proto"):
blob = sp.serialized_model_proto()
if blob:
out_model.write_bytes(blob)
_generate_vocab_txt(tokenizer_dir)
vs = getattr(sp, "vocab_size", None)
if callable(vs):
vs = vs()
return str(Path(tokenizer_dir)), int(vs) if vs else 0
raise RuntimeError("Could not extract tokenizer from teacher model")
def _generate_vocab_txt(tokenizer_dir):
import sentencepiece as spm_lib
model_path = os.path.join(tokenizer_dir, "tokenizer.model")
vocab_path = os.path.join(tokenizer_dir, "vocab.txt")
if os.path.exists(vocab_path):
return
sp = spm_lib.SentencePieceProcessor()
sp.load(model_path)
with open(vocab_path, "w", encoding="utf-8") as f:
for i in range(sp.get_piece_size()):
f.write(sp.id_to_piece(i) + "\n")
# ═══════════════════════════════════════════════════════════
# Model Setup
# ═══════════════════════════════════════════════════════════
def setup_spec_augment(student, args):
from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation
if args.no_spec_augment:
student.spec_augmentation = None
return
spec_aug = SpectrogramAugmentation(
freq_masks=args.freq_masks,
time_masks=args.time_masks,
freq_width=args.freq_width,
time_width=args.time_width,
)
student.spec_augmentation = spec_aug.to(next(student.parameters()).device)
from omegaconf import open_dict
with open_dict(student.cfg):
student.cfg.spec_augment.freq_masks = args.freq_masks
student.cfg.spec_augment.time_masks = args.time_masks
student.cfg.spec_augment.freq_width = args.freq_width
student.cfg.spec_augment.time_width = args.time_width
def load_student(args, device, rank):
"""Load student model, optionally swap tokenizer."""
import nemo.collections.asr as nemo_asr
if args.resume_from:
print_rank0(f" Resuming student from: {args.resume_from}", rank)
student = nemo_asr.models.ASRModel.restore_from(args.resume_from, map_location='cpu')
print_rank0(f" Student vocab: {student.tokenizer.vocab_size} tokens", rank)
args.freeze_encoder_epochs = 0
else:
# Extract teacher tokenizer (only rank 0 does this, then all read from disk)
tokenizer_dir = os.path.join(args.output_dir, "teacher_tokenizer")
if is_main(rank):
print_rank0(f" Loading teacher for tokenizer: {args.teacher}", rank)
teacher = nemo_asr.models.ASRModel.from_pretrained(args.teacher)
tokenizer_dir, teacher_vocab_size = extract_tokenizer(teacher, tokenizer_dir)
print_rank0(f" Teacher vocab: {teacher_vocab_size}", rank)
del teacher
torch.cuda.empty_cache()
if dist.is_initialized():
dist.barrier()
# Load student
print_rank0(f" Loading student: {args.student}", rank)
student = nemo_asr.models.ASRModel.from_pretrained(args.student)
old_vocab = student.tokenizer.vocab_size
student.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type="bpe")
new_vocab = student.tokenizer.vocab_size
print_rank0(f" Tokenizer swap: {old_vocab} → {new_vocab}", rank)
student = student.to(device)
# SpecAugment
setup_spec_augment(student, args)
# Disable CUDA graphs and typecheck
from omegaconf import open_dict
from nemo.core.classes.common import typecheck
typecheck.set_typecheck_enabled(False)
with open_dict(student.cfg):
student.cfg.decoding.greedy.use_cuda_graph_decoder = False
student.change_decoding_strategy(student.cfg.decoding)
params = sum(p.numel() for p in student.parameters()) / 1e6
print_rank0(f" Student params: {params:.1f}M", rank)
return student
# ═══════════════════════════════════════════════════════════
# Dataset & DataLoader
# ═══════════════════════════════════════════════════════════
class ASRManifestDataset(torch.utils.data.Dataset):
def __init__(self, manifest_path, tokenizer, min_duration=0.3, max_duration=20.0,
speed_perturb=False, speed_perturb_factors=None):
self.tokenizer = tokenizer
self.speed_perturb = speed_perturb
self.speed_perturb_factors = speed_perturb_factors or [0.9, 1.0, 1.1]
self.samples = []
with open(manifest_path) as f:
for line in f:
item = json.loads(line)
dur = item["duration"]
if min_duration <= dur <= max_duration:
self.samples.append(item)
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
import soundfile as sf
item = self.samples[idx]
try:
audio, sr = sf.read(item["audio_filepath"], dtype="float32")
except Exception as e:
print(f" Corrupt audio: {item['audio_filepath']} ({e})", flush=True)
return None
if sr != 16000:
ratio = 16000 / sr
new_len = int(len(audio) * ratio)
audio = np.interp(
np.linspace(0, len(audio) - 1, new_len),
np.arange(len(audio)), audio,
).astype(np.float32)
# Speed perturbation
if self.speed_perturb:
import random
speed = random.choice(self.speed_perturb_factors)
if speed != 1.0:
new_len = int(len(audio) / speed)
audio = np.interp(
np.linspace(0, len(audio) - 1, new_len),
np.arange(len(audio)), audio,
).astype(np.float32)
audio_tensor = torch.FloatTensor(audio)
text = unicodedata.normalize("NFKC", item["text"])
text = " ".join(text.split())
tokens = torch.LongTensor(self.tokenizer.text_to_ids(text))
return audio_tensor, tokens
def collate_asr(batch):
batch = [b for b in batch if b is not None]
if len(batch) == 0:
return None
audios = [b[0] for b in batch]
tokens_list = [b[1] for b in batch]
audio_lens = torch.LongTensor([len(a) for a in audios])
token_lens = torch.LongTensor([len(t) for t in tokens_list])
max_audio = audio_lens.max().item()
max_tokens = token_lens.max().item()
B = len(audios)
padded_audio = torch.zeros(B, max_audio)
padded_tokens = torch.zeros(B, max_tokens, dtype=torch.long)
for i in range(B):
padded_audio[i, :audio_lens[i]] = audios[i]
padded_tokens[i, :token_lens[i]] = tokens_list[i]
return padded_audio, audio_lens, padded_tokens, token_lens
# ═══════════════════════════════════════════════════════════
# Training Step
# ═══════════════════════════════════════════════════════════
def train_step(student, batch, device):
"""Single forward/backward step: RNNT loss only."""
audio, audio_len, tokens, token_len = batch
audio = audio.to(device)
audio_len = audio_len.to(device)
tokens = tokens.to(device)
token_len = token_len.to(device)
# Get underlying model if wrapped in DDP
model = student.module if isinstance(student, DDP) else student
# Mel spectrogram
mel, mel_len = model.preprocessor(input_signal=audio, length=audio_len)
# Spec augmentation
if model.spec_augmentation is not None and model.training:
mel = model.spec_augmentation(input_spec=mel, length=mel_len)
# Encoder
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
# Decoder
dec_out = model.decoder(targets=tokens, target_length=token_len)
if isinstance(dec_out, tuple):
dec_out = dec_out[0]
# Joint + RNNT loss
if getattr(model.joint, 'fuse_loss_wer', False):
result = model.joint(
encoder_outputs=enc, decoder_outputs=dec_out,
encoder_lengths=enc_len, transcripts=tokens,
transcript_lengths=token_len, compute_wer=False,
)
loss = result[0]
else:
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
loss = model.loss(
log_probs=joint_out, targets=tokens,
input_lengths=enc_len, target_lengths=token_len,
)
# Ensure loss is scalar
if loss.dim() > 0:
loss = loss.mean()
return loss
# ═══════════════════════════════════════════════════════════
# Evaluation
# ═══════════════════════════════════════════════════════════
@torch.no_grad()
def evaluate(student, manifest_path, device, max_samples=None):
"""Evaluate WER using streaming inference."""
import soundfile as sf_eval
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
model = student.module if isinstance(student, DDP) else student
model.eval()
def normalize_text(text):
text = unicodedata.normalize('NFKC', text)
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
return ' '.join(text.split())
def simple_wer(ref_words, hyp_words):
n, m = len(ref_words), len(hyp_words)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1): dp[i][0] = i
for j in range(m + 1): dp[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[n][m]
right_context = 13
chunk_frames = 1 + right_context
model.encoder.setup_streaming_params(
chunk_size=chunk_frames,
shift_size=chunk_frames,
left_chunks=70 // max(chunk_frames, 1),
)
samples = []
with open(manifest_path) as f:
for line in f:
samples.append(json.loads(line))
if max_samples and len(samples) > max_samples:
samples = samples[:max_samples]
total_edits, total_words = 0, 0
examples = []
errors = 0
for s in samples:
try:
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
buffer = CacheAwareStreamingAudioBuffer(model=model)
buffer.append_audio(audio)
cache_last_channel, cache_last_time, cache_last_channel_len = \
model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
previous_hypotheses = None
pred = ""
for chunk_audio, chunk_len in buffer:
if chunk_audio is None:
break
result = model.conformer_stream_step(
processed_signal=chunk_audio,
processed_signal_length=chunk_len,
cache_last_channel=cache_last_channel,
cache_last_time=cache_last_time,
cache_last_channel_len=cache_last_channel_len,
previous_hypotheses=previous_hypotheses,
return_transcription=True,
)
if isinstance(result, tuple) and len(result) >= 6:
cache_last_channel = result[2]
cache_last_time = result[3]
cache_last_channel_len = result[4]
previous_hypotheses = result[5]
if result[5] and len(result[5]) > 0:
hyp = result[5][0]
new_text = ""
if hasattr(hyp, 'text') and hyp.text:
new_text = hyp.text
elif hasattr(hyp, 'y_sequence'):
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
if tids:
new_text = model.tokenizer.ids_to_text(tids)
if new_text and len(new_text) > len(pred):
pred = new_text
ref_n = normalize_text(s["text"])
pred_n = normalize_text(pred)
ref_words = ref_n.split()
pred_words = pred_n.split()
if ref_words:
edits = simple_wer(ref_words, pred_words)
total_edits += edits
total_words += len(ref_words)
if len(examples) < 5:
examples.append((s["text"][:55], pred[:55]))
except Exception as e:
errors += 1
if errors <= 3:
print(f" [eval error] {type(e).__name__}: {e}")
wer_score = total_edits / max(total_words, 1) * 100
print(f"\n {'Reference':<55} | {'Prediction':<55}")
print(f" {'-'*55} | {'-'*55}")
for ref, pred in examples:
print(f" {ref:<55} | {pred:<55}")
if errors:
print(f" ({errors} samples failed)")
model.train()
return wer_score
@torch.no_grad()
def evaluate_batch(student, manifest_path, device, max_samples=None):
"""Evaluate WER using batch (non-streaming) inference."""
import soundfile as sf_eval
model = student.module if isinstance(student, DDP) else student
model.eval()
def normalize_text(text):
text = unicodedata.normalize('NFKC', text)
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
return ' '.join(text.split())
def simple_wer(ref_words, hyp_words):
n, m = len(ref_words), len(hyp_words)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1): dp[i][0] = i
for j in range(m + 1): dp[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[n][m]
samples = []
with open(manifest_path) as f:
for line in f:
samples.append(json.loads(line))
if max_samples and len(samples) > max_samples:
samples = samples[:max_samples]
total_edits, total_words = 0, 0
errors = 0
batch_size = 16
for start in range(0, len(samples), batch_size):
batch_samples = samples[start:start + batch_size]
try:
audios = []
for s in batch_samples:
audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
audios.append(torch.FloatTensor(audio))
audio_lens = torch.LongTensor([len(a) for a in audios])
max_len = audio_lens.max().item()
padded = torch.zeros(len(audios), max_len)
for i, a in enumerate(audios):
padded[i, :len(a)] = a
padded = padded.to(device)
audio_lens = audio_lens.to(device)
mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
# Greedy decode
best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
if isinstance(best_hyps, tuple):
best_hyps = best_hyps[0]
for s, hyp in zip(batch_samples, best_hyps):
if hasattr(hyp, 'text') and hyp.text:
pred = hyp.text
elif hasattr(hyp, 'y_sequence'):
tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
pred = model.tokenizer.ids_to_text(tids) if tids else ""
else:
pred = str(hyp)
ref_n = normalize_text(s["text"])
pred_n = normalize_text(pred)
ref_words = ref_n.split()
pred_words = pred_n.split()
if ref_words:
total_edits += simple_wer(ref_words, pred_words)
total_words += len(ref_words)
except Exception as e:
errors += 1
if errors <= 3:
print(f" [batch eval error] {type(e).__name__}: {e}")
wer_score = total_edits / max(total_words, 1) * 100
if errors:
print(f" ({errors} batch eval errors)")
model.train()
return wer_score
@torch.no_grad()
def compute_val_loss(student, manifest_path, device, max_samples=500):
"""Compute RNNT loss on validation set (no decoding, fast)."""
import soundfile as sf_val
model = student.module if isinstance(student, DDP) else student
model.eval()
samples = []
with open(manifest_path) as f:
for line in f:
samples.append(json.loads(line))
if max_samples and len(samples) > max_samples:
samples = samples[:max_samples]
total_loss = 0.0
count = 0
for s in samples:
try:
audio, sr = sf_val.read(s["audio_filepath"], dtype="float32")
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
text = unicodedata.normalize("NFKC", s["text"])
text = " ".join(text.split())
tokens = model.tokenizer.text_to_ids(text)
if not tokens:
continue
audio_tensor = torch.FloatTensor(audio).unsqueeze(0).to(device)
audio_len = torch.LongTensor([len(audio)]).to(device)
token_tensor = torch.LongTensor([tokens]).to(device)
token_len = torch.LongTensor([len(tokens)]).to(device)
mel, mel_len = model.preprocessor(input_signal=audio_tensor, length=audio_len)
enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
dec_out = model.decoder(targets=token_tensor, target_length=token_len)
if isinstance(dec_out, tuple):
dec_out = dec_out[0]
if getattr(model.joint, 'fuse_loss_wer', False):
result = model.joint(
encoder_outputs=enc, decoder_outputs=dec_out,
encoder_lengths=enc_len, transcripts=token_tensor,
transcript_lengths=token_len, compute_wer=False,
)
loss = result[0]
else:
joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
loss = model.loss(log_probs=joint_out, targets=token_tensor,
input_lengths=enc_len, target_lengths=token_len)
if loss.dim() > 0:
loss = loss.mean()
total_loss += loss.item()
count += 1
except Exception:
continue
model.train()
return total_loss / max(count, 1)
# ═══════════════════════════════════════════════════════════
# LR Schedule
# ═══════════════════════════════════════════════════════════
def get_cosine_schedule(optimizer, warmup_steps, total_steps, min_lr=5e-6):
base_lr = optimizer.defaults["lr"]
def lr_lambda(step):
if step < warmup_steps:
return max(1e-8 / base_lr, step / max(1, warmup_steps))
progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
return max(min_lr / base_lr, cosine)
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
def get_constant_schedule(optimizer, warmup_steps):
base_lr = optimizer.defaults["lr"]
def lr_lambda(step):
if step < warmup_steps:
return max(1e-8 / base_lr, step / max(1, warmup_steps))
return 1.0
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
# ═══════════════════════════════════════════════════════════
# Main Training Loop
# ═══════════════════════════════════════════════════════════
def train(student, train_loader, train_sampler, val_manifest, device, args, rank,
is_distributed):
os.makedirs(args.output_dir, exist_ok=True)
model = student.module if isinstance(student, DDP) else student
trainable_params = [p for p in student.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(
trainable_params,
lr=args.lr,
weight_decay=args.weight_decay,
betas=(0.9, 0.98),
eps=1e-9,
)
steps_per_epoch = len(train_loader) // args.grad_accum
total_steps = steps_per_epoch * args.epochs
warmup_steps = steps_per_epoch * args.warmup_epochs
if args.constant_lr:
scheduler = get_constant_schedule(optimizer, warmup_steps)
else:
scheduler = get_cosine_schedule(optimizer, warmup_steps, total_steps, args.min_lr)
scaler = torch.amp.GradScaler("cuda") if args.fp16 else None
effective_batch = args.batch_size * args.grad_accum
if is_distributed:
world_size = dist.get_world_size()
effective_batch *= world_size
else:
world_size = 1
print_rank0(f"\n{'='*65}", rank)
print_rank0(f" Training Configuration", rank)
print_rank0(f"{'='*65}", rank)
print_rank0(f" GPUs: {world_size}", rank)
print_rank0(f" Train samples: {len(train_loader.dataset)}", rank)
print_rank0(f" Per-GPU batch: {args.batch_size}", rank)
print_rank0(f" Effective batch: {args.batch_size} x {args.grad_accum} x {world_size} = {effective_batch}", rank)
print_rank0(f" Steps/epoch: {steps_per_epoch}", rank)
print_rank0(f" Total steps: {total_steps}", rank)
print_rank0(f" Warmup steps: {warmup_steps}", rank)
print_rank0(f" Learning rate: {args.lr} ({'constant' if args.constant_lr else 'cosine decay'})", rank)
print_rank0(f" Freeze encoder: first {args.freeze_encoder_epochs} epochs", rank)
print_rank0(f" Mixed precision: {args.fp16}", rank)
print_rank0(f"{'='*65}\n", rank)
global_step = 0
best_wer = float("inf")
patience_counter = 0
import time as time_module
for epoch in range(args.epochs):
epoch_start = time_module.time()
student.train()
# Set epoch for distributed sampler (ensures different shuffling each epoch)
if train_sampler is not None:
train_sampler.set_epoch(epoch)
# Phase management
if epoch < args.freeze_encoder_epochs:
for p in model.encoder.parameters():
p.requires_grad = False
phase = f"Phase 1/{args.freeze_encoder_epochs} (encoder frozen)"
else:
for p in model.encoder.parameters():
p.requires_grad = True
phase = "Phase 2 (full training)"
# Update optimizer param groups
optimizer.param_groups[0]["params"] = [
p for p in student.parameters() if p.requires_grad
]
epoch_loss = 0.0
epoch_steps = 0
epoch_grad_norm = 0.0
grad_norm_steps = 0
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{args.epochs}",
leave=True, ncols=120, disable=not is_main(rank))
optimizer.zero_grad()
for batch_idx, batch in enumerate(pbar):
if batch is None:
continue
try:
if scaler:
with torch.amp.autocast("cuda"):
loss = train_step(student, batch, device)
scaled_loss = loss / args.grad_accum
scaler.scale(scaled_loss).backward()
else:
loss = train_step(student, batch, device)
(loss / args.grad_accum).backward()
except RuntimeError as e:
if "out of memory" in str(e).lower():
torch.cuda.empty_cache()
print_rank0(f"\n OOM at batch {batch_idx}, skipping", rank)
optimizer.zero_grad()
continue
raise
epoch_loss += loss.item()
epoch_steps += 1
if (batch_idx + 1) % args.grad_accum == 0:
if scaler:
scaler.unscale_(optimizer)
trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
grad_norm = torch.nn.utils.clip_grad_norm_(trainable, 1.0).item()
if scaler:
scaler.step(optimizer)
scaler.update()
else:
optimizer.step()
epoch_grad_norm += grad_norm
grad_norm_steps += 1
scheduler.step()
optimizer.zero_grad()
global_step += 1
if epoch_steps % args.log_every == 0 and epoch_steps > 0 and is_main(rank):
avg_loss = epoch_loss / epoch_steps
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
lr = optimizer.param_groups[0]["lr"]
pbar.set_postfix(loss=f"{avg_loss:.3f}", gnorm=f"{avg_gnorm:.2f}",
lr=f"{lr:.1e}", step=global_step)
# End of epoch
epoch_time = time_module.time() - epoch_start
avg_loss = epoch_loss / max(1, epoch_steps)
avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
samples_per_sec = (epoch_steps * args.batch_size) / epoch_time
gpu_mem = torch.cuda.max_memory_allocated(device) / 1e9 if torch.cuda.is_available() else 0
print_rank0(f"\n Epoch {epoch+1} | {phase} | loss={avg_loss:.4f} "
f"grad_norm={avg_gnorm:.3f} lr={optimizer.param_groups[0]['lr']:.2e}"
f" | {epoch_time/60:.1f}min | {samples_per_sec:.0f} samples/s | GPU mem: {gpu_mem:.1f}GB", rank)
# Evaluation (rank 0 only)
if is_main(rank) and val_manifest and (epoch + 1) % args.eval_every_epoch == 0:
try:
print_rank0(f"\n Evaluating...", rank)
# Per-language WER (batch only) and val loss
lang_wers_batch = {}
lang_val_losses = {}
if args.eval_dir:
for lang in ['de', 'es', 'fr', 'it', 'nl']:
lang_val = os.path.join(args.eval_dir, lang, 'eval', 'validation_manifest.json')
if os.path.exists(lang_val):
lang_wers_batch[lang] = evaluate_batch(student, lang_val, device)
lang_val_losses[lang] = compute_val_loss(student, lang_val, device)
if lang_wers_batch:
batch_strs = [f"{l.upper()}={w:.1f}%" for l, w in lang_wers_batch.items()]
loss_strs = [f"{l.upper()}={v:.3f}" for l, v in lang_val_losses.items()]
print_rank0(f" Batch WER: {' | '.join(batch_strs)}", rank)
print_rank0(f" Val loss: {' | '.join(loss_strs)}", rank)
# Combined val loss + batch WER (used for best model selection)
val_loss = compute_val_loss(student, val_manifest, device)
val_wer_batch = evaluate_batch(student, val_manifest, device)
print_rank0(f" Combined — Batch WER: {val_wer_batch:.2f}% | Val loss: {val_loss:.4f}", rank)
if val_wer_batch < best_wer:
best_wer = val_wer_batch
patience_counter = 0
save_path = os.path.join(args.output_dir, "best_model.nemo")
model.save_to(save_path)
print_rank0(f" New best! Batch WER={best_wer:.2f}% -> {save_path}", rank)
else:
patience_counter += 1
print_rank0(f" No improvement ({patience_counter}/{args.early_stop_patience})", rank)
if args.early_stop_patience > 0 and patience_counter >= args.early_stop_patience:
print_rank0(f"\n Early stopping! No improvement for {args.early_stop_patience} epochs.", rank)
break
except Exception as e:
print_rank0(f" [eval error] {type(e).__name__}: {e} — skipping evaluation this epoch", rank)
# Periodic checkpoint (rank 0 only)
if is_main(rank) and (epoch + 1) % args.save_every_epoch == 0:
save_path = os.path.join(args.output_dir, f"epoch_{epoch+1}.nemo")
model.save_to(save_path)
print_rank0(f" Checkpoint -> {save_path}", rank)
# Sync all ranks before next epoch
if is_distributed:
dist.barrier()
# Final save
if is_main(rank):
save_path = os.path.join(args.output_dir, "final_model.nemo")
model.save_to(save_path)
print_rank0(f"\n Final model -> {save_path}", rank)
print_rank0(f" Best WER: {best_wer:.2f}%", rank)
return student
# ═══════════════════════════════════════════════════════════
# Entry Point
# ═══════════════════════════════════════════════════════════
def _seed_everything(seed, rank):
"""Fully deterministic seeding for reproducibility (DDP-safe).
Each rank uses ``seed + rank`` so that DistributedSampler still shuffles
differently per worker, but the run is bit-exact reproducible given the
same hardware, library versions, and (rank, seed) pair.
"""
seed = int(seed) + int(rank)
os.environ["PYTHONHASHSEED"] = str(seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def _make_worker_init_fn(base_seed, rank):
"""DataLoader worker_init_fn: reseeds random/numpy/torch in each worker."""
def _init(worker_id):
s = int(base_seed) + int(rank) * 10_000 + int(worker_id)
random.seed(s)
np.random.seed(s)
torch.manual_seed(s)
return _init
def main():
args = parse_args()
rank, world_size, local_rank, is_distributed = setup_ddp()
device = torch.device(f"cuda:{local_rank}")
_seed_everything(args.seed, rank)
os.makedirs(args.output_dir, exist_ok=True)
print_rank0(f"\n{'='*65}", rank)
print_rank0(f" Nemotron Streaming ASR — Multilingual Training", rank)
print_rank0(f"{'='*65}", rank)
print_rank0(f" GPUs: {world_size}", rank)
print_rank0(f" Student: {args.student}", rank)
if args.resume_from:
print_rank0(f" Resume: {args.resume_from}", rank)
print_rank0(f" Train: {args.train_manifest}", rank)
print_rank0(f"{'='*65}", rank)
# Load model
print_rank0(f"\n[1/3] Loading model...", rank)
student = load_student(args, device, rank)
# Wrap in DDP
if is_distributed:
student = DDP(student, device_ids=[local_rank], find_unused_parameters=True)
print_rank0(f" Wrapped in DDP (find_unused_parameters=True)", rank)
# Create dataloader
print_rank0(f"\n[2/3] Creating data loaders...", rank)
model_for_tok = student.module if isinstance(student, DDP) else student
train_dataset = ASRManifestDataset(
args.train_manifest,
model_for_tok.tokenizer,
min_duration=args.min_duration,
max_duration=args.max_duration,
speed_perturb=args.speed_perturb,
speed_perturb_factors=args.speed_perturb_factors,
)
print_rank0(f" Train dataset: {len(train_dataset)} samples", rank)
train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=args.seed) \
if is_distributed else None
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=(train_sampler is None),
sampler=train_sampler,
num_workers=args.num_workers,
collate_fn=collate_asr,
pin_memory=True,
drop_last=True,
worker_init_fn=_make_worker_init_fn(args.seed, rank),
generator=torch.Generator().manual_seed(int(args.seed) + int(rank)),
)
# Train
print_rank0(f"\n[3/3] Starting training...", rank)
student = train(
student, train_loader, train_sampler,
args.val_manifest, device, args, rank, is_distributed,
)
# Final eval (batch only — run streaming eval separately on best model)
if is_main(rank):
print_rank0(f"\n{'='*65}", rank)
print_rank0(f" Final Evaluation (Batch WER)", rank)
print_rank0(f"{'='*65}", rank)
if args.eval_dir:
for lang in ['de', 'es', 'fr', 'it', 'nl']:
lang_val = os.path.join(args.eval_dir, lang, 'eval', 'validation_manifest.json')
if os.path.exists(lang_val):
b_wer = evaluate_batch(student, lang_val, device)
print_rank0(f" {lang.upper()} — Batch WER: {b_wer:.2f}%", rank)
if args.val_manifest:
b_wer = evaluate_batch(student, args.val_manifest, device)
print_rank0(f" Combined — Batch WER: {b_wer:.2f}%", rank)
cleanup_ddp(is_distributed)
if __name__ == "__main__":
main()
|