Download train_multilingual_nemotron.py from data-scale-paper/slt2026-code: direct link, hf CLI and curl.
- Browser
- Download file 42.4 kB
-
https://huggingface.co/datasets/data-scale-paper/slt2026-code/resolve/main/train_multilingual_nemotron.py
- Command line
-
hf download hf://datasets/data-scale-paper/slt2026-code/train_multilingual_nemotron.py
-
curl -L -o train_multilingual_nemotron.py https://huggingface.co/datasets/data-scale-paper/slt2026-code/resolve/main/train_multilingual_nemotron.py
42.4 kB
| #!/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 | |
| # ═══════════════════════════════════════════════════════════ | |
| 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 | |
| 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 | |
| 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() | |