Download train_single_lang.py from data-scale-paper/slt2026-code: direct link, hf CLI and curl.
- Browser
- Download file 85.8 kB
-
https://huggingface.co/datasets/data-scale-paper/slt2026-code/resolve/main/train_single_lang.py
- Command line
-
hf download hf://datasets/data-scale-paper/slt2026-code/train_single_lang.py
-
curl -L -o train_single_lang.py https://huggingface.co/datasets/data-scale-paper/slt2026-code/resolve/main/train_single_lang.py
85.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| train_single_lang.py | |
| Single-language fine-tuning of Nemotron-Speech-Streaming. | |
| Adapted from train_multilingual_nemotron.py for per-language training. | |
| This script is the entry point for every (language, hours, init) cell of | |
| the main grid in the paper. The init arm is selected by the combination | |
| of --resume_from and --encoder_from / --reinit_encoder; the multilingual | |
| tokenizer, decoder and joint always come from the multilingual base. | |
| ML init (paper's "ML" arm) | |
| --resume_from <multilingual_base.nemo> | |
| Encoder, decoder, joint and tokenizer all come from the multilingual | |
| base checkpoint. | |
| EN init (paper's "EN" arm) | |
| --resume_from <multilingual_base.nemo> | |
| --encoder_from nvidia/nemotron-speech-streaming-en-0.6b | |
| The decoder, joint and tokenizer are kept from the multilingual base | |
| (so the comparison isolates the encoder), and the encoder weights are | |
| overwritten layer-for-layer with the English-only Nemotron encoder. | |
| Random-encoder ablation (NOT the paper's EN arm) | |
| --resume_from <multilingual_base.nemo> | |
| --reinit_encoder | |
| Same as ML init except the encoder is freshly random-initialized. | |
| Direct from English checkpoint (legacy / not used in the main grid) | |
| --student nvidia/nemotron-speech-streaming-en-0.6b | |
| No --resume_from. Everything (encoder, decoder, joint, tokenizer) is | |
| taken from the English checkpoint and only the prediction-network | |
| output layer is resized to the target tokenizer. | |
| Example usage (paper ML init for German, 100 h): | |
| torchrun --nproc_per_node=1 train_single_lang.py \ | |
| --lang de \ | |
| --resume_from <CKPT_DIR>/multilingual_base.nemo \ | |
| --train_manifest <DATA_ROOT>/de/100h/train.jsonl \ | |
| --val_manifest <VAL_MANIFEST> \ | |
| --output_dir ./out/de_100h_ml \ | |
| --epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \ | |
| --early_stop_patience 8 --decay_spec_augment --seed 42 | |
| Example usage (paper EN init for the same cell): | |
| torchrun --nproc_per_node=1 train_single_lang.py \ | |
| --lang de \ | |
| --resume_from <CKPT_DIR>/multilingual_base.nemo \ | |
| --encoder_from nvidia/nemotron-speech-streaming-en-0.6b \ | |
| --train_manifest <DATA_ROOT>/de/100h/train.jsonl \ | |
| --val_manifest <VAL_MANIFEST> \ | |
| --output_dir ./out/de_100h_en \ | |
| --epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \ | |
| --early_stop_patience 8 --decay_spec_augment --seed 42 | |
| Manifest format (one JSON object per line): | |
| {"audio_filepath": "/abs/path/utt.wav", "duration": 8.4, "text": "reference transcript"} | |
| `duration` (seconds) is required: it drives min/max-duration filtering and | |
| the --max_train_hours subsampling. | |
| Requirements: | |
| pip install nemo_toolkit[asr] soundfile jiwer tqdm | |
| Evaluation also requires Whisper's BasicMultilingualTextNormalizer from the | |
| Open ASR Leaderboard repo (clone https://github.com/huggingface/open_asr_leaderboard | |
| and add it to PYTHONPATH). | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import gc | |
| 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 | |
| # Use Whisper's BasicMultilingualTextNormalizer for consistent eval | |
| try: | |
| from normalizer import BasicMultilingualTextNormalizer | |
| _ml_normalizer = BasicMultilingualTextNormalizer() | |
| _has_real_normalizer = True | |
| except ImportError: | |
| print( | |
| "ERROR: could not import BasicMultilingualTextNormalizer. " | |
| "This script requires Whisper's BasicMultilingualTextNormalizer, " | |
| "shipped in the Open ASR Leaderboard repo. " | |
| "Clone https://github.com/huggingface/open_asr_leaderboard and add it " | |
| "to PYTHONPATH (or set OPEN_ASR_LB_ROOT).", | |
| file=sys.stderr, | |
| ) | |
| exit(1) | |
| _ml_normalizer = None | |
| _has_real_normalizer = False | |
| # ═══════════════════════════════════════════════════════════ | |
| # DDP Utilities | |
| # ═══════════════════════════════════════════════════════════ | |
| def setup_ddp(): | |
| """Initialize distributed training. Returns (rank, world_size, local_rank, 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"]) | |
| from datetime import timedelta | |
| dist.init_process_group("nccl", timeout=timedelta(minutes=60)) | |
| 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="Single-language Nemotron Streaming ASR Training", | |
| formatter_class=argparse.ArgumentDefaultsHelpFormatter, | |
| ) | |
| # Language | |
| p.add_argument("--lang", type=str, required=True, | |
| help="Language code (e.g., de, es, fr, it, nl, sv, pt, pl)") | |
| # 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 | |
| p.add_argument("--train_manifest", type=str, required=True, | |
| help="Path to training manifest (JSONL)") | |
| p.add_argument("--val_manifest", type=str, required=True, | |
| help="Path to validation manifest (JSONL)") | |
| # Training | |
| p.add_argument("--output_dir", default="./nemotron_lang") | |
| p.add_argument("--epochs", type=int, default=30) | |
| p.add_argument("--batch_size", type=int, default=16, | |
| 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=1e-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("--reinit_encoder", action="store_true", default=False, | |
| help="Randomly reinitialize all encoder weights (ablation). " | |
| "NOT the paper's EN arm -- EN init uses --encoder_from " | |
| "to copy the English encoder weights, not random init.") | |
| p.add_argument("--reinit_joint", action="store_true", default=False, | |
| help="Randomly reinitialize the RNNT joint network weights (ablation study). " | |
| "Useful after swapping encoders so the joint relearns the encoder->vocab mapping.") | |
| p.add_argument("--lr_decay_epochs", type=int, default=25, | |
| help="Cosine decay reaches min_lr after N epochs (0=use total 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=0, | |
| help="Save training state every N epochs (0=disabled)") | |
| p.add_argument("--early_stop_patience", type=int, default=30, | |
| help="Stop if WER doesn't improve for N evals (0=disabled)") | |
| p.add_argument("--grad_clip", type=float, default=1.0, | |
| help="Gradient clipping max norm") | |
| p.add_argument("--rnnt_clamp", type=float, default=-1.0, | |
| help="RNNT loss per-frame clamping value (-1=disabled, 1.0=recommended)") | |
| p.add_argument("--bf16", action="store_true", default=True) | |
| p.add_argument("--fp16", action="store_true", default=False) | |
| p.add_argument("--num_workers", type=int, default=4) | |
| p.add_argument("--max_train_hours", type=float, default=0, | |
| help="Limit training data to N hours (0=use all data). Samples randomly.") | |
| p.add_argument("--data_seed", type=int, default=12345, | |
| help="Seed for data subsampling (separate from training seed for reproducibility)") | |
| p.add_argument("--seed", type=int, default=42) | |
| p.add_argument("--resume_from", type=str, default=None, | |
| help="Resume from .nemo checkpoint (the multilingual base for both " | |
| "the ML and EN arms of the paper's main grid). Sets the " | |
| "tokenizer, decoder and joint; the encoder is then either kept " | |
| "(ML arm), overwritten via --encoder_from (EN arm), or " | |
| "re-initialized via --reinit_encoder (ablation).") | |
| p.add_argument("--encoder_from", type=str, default=None, | |
| help="Overwrite encoder weights with those of this checkpoint after " | |
| "--resume_from has loaded the multilingual base. This is how " | |
| "the paper's EN arm is built: multilingual tokenizer/decoder/joint " | |
| "+ English encoder (nvidia/nemotron-speech-streaming-en-0.6b).") | |
| p.add_argument("--swap_joint_enc", action="store_true", default=False, | |
| 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.") | |
| p.add_argument("--encoder_from_layers", type=str, default="all", | |
| help="Which Conformer layer indices to copy from --encoder_from. " | |
| "Examples: 'all' (default, full encoder), 'none' (skip layers, only use preencode/postnorm flags), " | |
| "'0:8' (Python slice, layers 0..7), '-8:' (last 8 layers), '0:8,16:24' (multiple ranges). " | |
| "Negative indices count from the end. Layers outside the slice stay from --resume_from/--student.") | |
| p.add_argument("--encoder_from_preencode", type=str, default="off", choices=["auto", "on", "off"], | |
| help="Copy the pre-encoder subsampling (conv frontend) and positional embeddings from --encoder_from. " | |
| "Default 'off' keeps the destination model's preencode (ML baseline when --resume_from is set), " | |
| "which is preferable for cross-lingual splices since the ML preencode has seen the target language. " | |
| "'auto': on iff layer 0 is in --encoder_from_layers.") | |
| p.add_argument("--encoder_from_postnorm", type=str, default="off", choices=["auto", "on", "off"], | |
| help="Copy the final encoder norm/output projection from --encoder_from. " | |
| "Default 'off' keeps the destination model's postnorm (ML baseline when --resume_from is set), " | |
| "which is the natural pairing when the top layers also come from the destination. " | |
| "'auto': on iff the last layer is in --encoder_from_layers.") | |
| p.add_argument("--decay_spec_augment", action="store_true", default=False, | |
| help="Linearly decay SpecAugment mask counts over training (time_masks: N->2, freq_masks: N->1)") | |
| p.add_argument("--resume_training", type=str, default=None, | |
| help="Resume training from a training_state.pt checkpoint (saved in output_dir). Restores optimizer, scheduler, epoch, and all training state.") | |
| p.add_argument("--confidence_penalty", type=float, default=0.0, | |
| help="Entropy regularization weight (0=off). Penalizes overconfident joint predictions. Try 0.1-0.3.") | |
| p.add_argument("--streaming_chunk_sec", type=float, default=0, | |
| help="Enable chunk-aware streaming training. Chunk duration in seconds (e.g., 1.2). 0=full context training.") | |
| p.add_argument("--test_manifest", type=str, default=None, | |
| help="Path to test manifest (JSONL) for final evaluation") | |
| p.add_argument("--decoder_hidden", type=int, default=0, | |
| help="Override RNNT decoder (prediction network) LSTM hidden size. 0=keep original (640). E.g., 860, 1024.") | |
| p.add_argument("--decoder_layers", type=int, default=0, | |
| help="Override RNNT decoder LSTM layer count. 0=keep original (2). E.g., 3, 4.") | |
| 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 | |
| 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) | |
| def update_spec_augment(student, args, epoch, total_epochs, rank): | |
| """Linearly decay SpecAugment mask counts over training.""" | |
| if not args.decay_spec_augment or args.no_spec_augment: | |
| return | |
| from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation | |
| progress = epoch / max(1, total_epochs - 1) | |
| new_time_masks = max(2, round(args.time_masks * (1 - progress))) | |
| new_freq_masks = max(1, round(args.freq_masks * (1 - 0.5 * progress))) | |
| model = student.module if isinstance(student, DDP) else student | |
| spec_aug = SpectrogramAugmentation( | |
| freq_masks=new_freq_masks, | |
| time_masks=new_time_masks, | |
| freq_width=args.freq_width, | |
| time_width=args.time_width, | |
| ) | |
| model.spec_augmentation = spec_aug.to(next(model.parameters()).device) | |
| print_rank0(f" SpecAug decay: freq={new_freq_masks}x{args.freq_width} time={new_time_masks}x{args.time_width}", rank) | |
| from omegaconf import open_dict | |
| with open_dict(model.cfg): | |
| model.cfg.spec_augment.freq_masks = new_freq_masks | |
| model.cfg.spec_augment.time_masks = new_time_masks | |
| model.cfg.spec_augment.freq_width = args.freq_width | |
| model.cfg.spec_augment.time_width = args.time_width | |
| def _parse_layer_slice(spec, num_layers): | |
| """Parse a slice spec like 'all', 'none', '0:8', '-8:', '0:8,16:24' into a sorted set of indices. | |
| Supports Python-style slice ranges, comma-separated. Negative indices count from num_layers. | |
| Returns a set of ints in [0, num_layers). | |
| """ | |
| if spec is None: | |
| return set() | |
| s = spec.strip().lower() | |
| if s in ("all", "*"): | |
| return set(range(num_layers)) | |
| if s in ("none", ""): | |
| return set() | |
| out = set() | |
| for part in s.split(","): | |
| part = part.strip() | |
| if not part: | |
| continue | |
| if ":" in part: | |
| lo_s, hi_s = part.split(":", 1) | |
| lo = int(lo_s) if lo_s else 0 | |
| hi = int(hi_s) if hi_s else num_layers | |
| if lo < 0: | |
| lo += num_layers | |
| if hi < 0: | |
| hi += num_layers | |
| lo = max(0, min(num_layers, lo)) | |
| hi = max(0, min(num_layers, hi)) | |
| out.update(range(lo, hi)) | |
| else: | |
| idx = int(part) | |
| if idx < 0: | |
| idx += num_layers | |
| if 0 <= idx < num_layers: | |
| out.add(idx) | |
| return out | |
| def _splice_encoder(dst_encoder, src_encoder, layer_indices, include_preencode, include_postnorm, rank): | |
| """Merge src_encoder weights into dst_encoder for the given layer indices, plus optional | |
| preencode (subsampling + positional encoding) and postnorm modules. | |
| Layer keys are expected to start with 'layers.<i>.'. Everything else is treated as | |
| 'preencode-like' if its name matches pre_encode/pos_enc/embedding, or 'postnorm-like' otherwise. | |
| """ | |
| src_sd = src_encoder.state_dict() | |
| dst_sd = dst_encoder.state_dict() | |
| PREENC_PREFIXES = ("pre_encode", "pos_enc", "pos_embedding", "pos_embed", "embedding") | |
| copied_layers = set() | |
| copied_pre = [] | |
| copied_post = [] | |
| skipped_shape = [] | |
| skipped_missing = [] | |
| for k, v in src_sd.items(): | |
| if k.startswith("layers."): | |
| try: | |
| idx = int(k.split(".", 2)[1]) | |
| except (ValueError, IndexError): | |
| continue | |
| if idx not in layer_indices: | |
| continue | |
| target_key = k | |
| bucket = ("layer", idx) | |
| elif any(k.startswith(p) for p in PREENC_PREFIXES): | |
| if not include_preencode: | |
| continue | |
| target_key = k | |
| bucket = ("pre", k) | |
| else: | |
| if not include_postnorm: | |
| continue | |
| target_key = k | |
| bucket = ("post", k) | |
| if target_key not in dst_sd: | |
| skipped_missing.append(target_key) | |
| continue | |
| if dst_sd[target_key].shape != v.shape: | |
| skipped_shape.append((target_key, tuple(v.shape), tuple(dst_sd[target_key].shape))) | |
| continue | |
| dst_sd[target_key] = v | |
| if bucket[0] == "layer": | |
| copied_layers.add(bucket[1]) | |
| elif bucket[0] == "pre": | |
| copied_pre.append(target_key) | |
| else: | |
| copied_post.append(target_key) | |
| missing, unexpected = dst_encoder.load_state_dict(dst_sd, strict=False) | |
| print_rank0( | |
| f" Encoder splice: copied layers {sorted(copied_layers)} " | |
| f"({len(copied_layers)} of {len(layer_indices)} requested)", rank | |
| ) | |
| if copied_pre: | |
| print_rank0(f" Encoder splice: copied {len(copied_pre)} preencode keys", rank) | |
| if copied_post: | |
| print_rank0(f" Encoder splice: copied {len(copied_post)} postnorm/other keys", rank) | |
| if skipped_shape: | |
| print_rank0(f" WARNING: skipped {len(skipped_shape)} keys due to shape mismatch (first: {skipped_shape[0]})", rank) | |
| if skipped_missing: | |
| print_rank0(f" WARNING: skipped {len(skipped_missing)} keys missing in dst encoder (first: {skipped_missing[0]})", rank) | |
| 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 from: {args.resume_from}", rank) | |
| student = nemo_asr.models.ASRModel.restore_from(args.resume_from, map_location='cpu') | |
| print_rank0(f" Vocab: {student.tokenizer.vocab_size} tokens", rank) | |
| args.freeze_encoder_epochs = 0 | |
| # Optionally override encoder weights from a different model (e.g., English) | |
| if args.encoder_from: | |
| print_rank0(f" Loading encoder from: {args.encoder_from}", rank) | |
| if args.encoder_from.endswith('.nemo'): | |
| encoder_model = nemo_asr.models.ASRModel.restore_from(args.encoder_from, map_location='cpu') | |
| else: | |
| encoder_model = nemo_asr.models.ASRModel.from_pretrained(args.encoder_from, map_location='cpu') | |
| # Determine number of Conformer layers from the source encoder | |
| src_layers_attr = getattr(encoder_model.encoder, "layers", None) | |
| num_layers = len(src_layers_attr) if src_layers_attr is not None else 0 | |
| dst_layers_attr = getattr(student.encoder, "layers", None) | |
| dst_num_layers = len(dst_layers_attr) if dst_layers_attr is not None else 0 | |
| if num_layers == 0 or dst_num_layers == 0: | |
| raise RuntimeError( | |
| f"Could not locate '.encoder.layers' on src ({num_layers}) or dst ({dst_num_layers}); " | |
| f"layer splicing requires a Conformer-style encoder with .layers nn.ModuleList." | |
| ) | |
| if num_layers != dst_num_layers: | |
| print_rank0( | |
| f" WARNING: src encoder has {num_layers} layers but dst has {dst_num_layers}; " | |
| f"only layers present in both will be copied.", rank | |
| ) | |
| spec = args.encoder_from_layers or "all" | |
| effective_layers = min(num_layers, dst_num_layers) | |
| layer_indices = _parse_layer_slice(spec, effective_layers) | |
| # Auto-detect: preencode if EN provides layer 0; postnorm if EN provides last layer. | |
| auto_preencode = 0 in layer_indices | |
| auto_postnorm = (effective_layers - 1) in layer_indices | |
| def _resolve(flag, auto_value, name): | |
| if flag == "on": | |
| return True | |
| if flag == "off": | |
| return False | |
| return auto_value # "auto" | |
| include_preencode = _resolve(args.encoder_from_preencode, auto_preencode, "preencode") | |
| include_postnorm = _resolve(args.encoder_from_postnorm, auto_postnorm, "postnorm") | |
| # Fast path: entire encoder copied (all layers + both boundaries) -> direct load_state_dict. | |
| full_copy = ( | |
| len(layer_indices) == effective_layers | |
| and include_preencode | |
| and include_postnorm | |
| and num_layers == dst_num_layers | |
| ) | |
| if full_copy: | |
| student.encoder.load_state_dict(encoder_model.encoder.state_dict()) | |
| enc_params = sum(p.numel() for p in student.encoder.parameters()) / 1e6 | |
| print_rank0(f" Encoder fully swapped: {enc_params:.1f}M params from {args.encoder_from}", rank) | |
| else: | |
| print_rank0( | |
| f" Encoder splice spec='{spec}' ({len(layer_indices)}/{effective_layers} layers); " | |
| f"preencode={include_preencode} ({args.encoder_from_preencode}" | |
| f"{' -> auto=' + str(auto_preencode) if args.encoder_from_preencode == 'auto' else ''}), " | |
| f"postnorm={include_postnorm} ({args.encoder_from_postnorm}" | |
| f"{' -> auto=' + str(auto_postnorm) if args.encoder_from_postnorm == 'auto' else ''})", rank | |
| ) | |
| _splice_encoder( | |
| student.encoder, | |
| encoder_model.encoder, | |
| layer_indices, | |
| include_preencode=include_preencode, | |
| include_postnorm=include_postnorm, | |
| rank=rank, | |
| ) | |
| # Optionally also swap the joint network's encoder-side projection | |
| if args.swap_joint_enc: | |
| swapped_keys = [] | |
| src_joint_sd = encoder_model.joint.state_dict() | |
| dst_joint_sd = student.joint.state_dict() | |
| for key in src_joint_sd: | |
| # Match encoder-side projection layers (enc, enc_hat, etc.) | |
| if 'enc' in key and key in dst_joint_sd and src_joint_sd[key].shape == dst_joint_sd[key].shape: | |
| dst_joint_sd[key] = src_joint_sd[key] | |
| swapped_keys.append(key) | |
| if swapped_keys: | |
| student.joint.load_state_dict(dst_joint_sd) | |
| print_rank0(f" Joint encoder projection swapped: {swapped_keys}", rank) | |
| else: | |
| print_rank0(f" WARNING: --swap_joint_enc set but no matching joint.enc keys found", rank) | |
| del encoder_model | |
| 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) | |
| # Optionally resize decoder (prediction network) | |
| if args.decoder_hidden > 0 or args.decoder_layers > 0: | |
| from omegaconf import open_dict, OmegaConf | |
| old_hidden = student.cfg.decoder.prednet.pred_hidden | |
| old_layers = student.cfg.decoder.prednet.pred_rnn_layers | |
| new_hidden = args.decoder_hidden if args.decoder_hidden > 0 else old_hidden | |
| new_layers = args.decoder_layers if args.decoder_layers > 0 else old_layers | |
| with open_dict(student.cfg): | |
| student.cfg.decoder.prednet.pred_hidden = new_hidden | |
| student.cfg.decoder.prednet.pred_rnn_layers = new_layers | |
| # Rebuild decoder + joint with new dimensions | |
| from nemo.collections.asr.modules import RNNTDecoder, RNNTJoint | |
| student.decoder = RNNTDecoder( | |
| prednet=OmegaConf.to_container(student.cfg.decoder.prednet, resolve=True), | |
| vocab_size=student.tokenizer.vocab_size, | |
| normalization_mode=student.cfg.decoder.get('normalization_mode', None), | |
| random_state_sampling=student.cfg.decoder.get('random_state_sampling', False), | |
| blank_as_pad=student.cfg.decoder.get('blank_as_pad', True), | |
| ) | |
| # Rebuild joint network to match new decoder hidden | |
| with open_dict(student.cfg): | |
| student.cfg.joint.jointnet.pred_hidden = new_hidden | |
| student.cfg.joint.jointnet.encoder_hidden = student.cfg.encoder.d_model | |
| student.cfg.joint.num_classes = student.tokenizer.vocab_size | |
| joint_cfg = OmegaConf.to_container(student.cfg.joint, resolve=True) | |
| joint_cfg.pop('_target_', None) | |
| joint_cfg.pop('vocabulary', None) | |
| student.joint = RNNTJoint(**joint_cfg) | |
| dec_params = sum(p.numel() for p in student.decoder.parameters()) / 1e6 | |
| joint_params = sum(p.numel() for p in student.joint.parameters()) / 1e6 | |
| print_rank0(f" Decoder resized: hidden {old_hidden}->{new_hidden}, layers {old_layers}->{new_layers}", rank) | |
| print_rank0(f" New decoder params: {dec_params:.1f}M, joint params: {joint_params:.1f}M", rank) | |
| student = student.to(device) | |
| # Optionally reinitialize encoder weights (ablation study) | |
| if args.reinit_encoder: | |
| print_rank0(" REINITIALIZING ENCODER WEIGHTS (random init)", rank) | |
| for name, param in student.encoder.named_parameters(): | |
| if param.dim() >= 2: | |
| torch.nn.init.xavier_uniform_(param) | |
| else: | |
| torch.nn.init.zeros_(param) | |
| # Also reinit batch norm running stats | |
| for module in student.encoder.modules(): | |
| if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)): | |
| module.reset_running_stats() | |
| enc_params = sum(p.numel() for p in student.encoder.parameters()) | |
| print_rank0(f" Reinitialized {enc_params/1e6:.1f}M encoder parameters", rank) | |
| # Optionally reinitialize joint network weights (ablation study) | |
| if args.reinit_joint: | |
| print_rank0(" REINITIALIZING JOINT NETWORK WEIGHTS (random init)", rank) | |
| # Re-seed RNG with a fixed value so ML and EN arms get IDENTICAL joint init | |
| # (independent of prior RNG state consumed by different checkpoint loads). | |
| # Using args.seed (not args.seed+rank) ensures same init across DDP ranks too. | |
| _joint_seed = args.seed | |
| _gen_state_cpu = torch.random.get_rng_state() | |
| _gen_state_cuda = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None | |
| torch.manual_seed(_joint_seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed_all(_joint_seed) | |
| print_rank0(f" Joint reinit RNG seeded with {_joint_seed} (identical across ML/EN arms)", rank) | |
| for name, param in student.joint.named_parameters(): | |
| if param.dim() >= 2: | |
| torch.nn.init.xavier_uniform_(param) | |
| else: | |
| torch.nn.init.zeros_(param) | |
| for module in student.joint.modules(): | |
| if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)): | |
| module.reset_running_stats() | |
| # Restore prior RNG state so training stochasticity is unaffected | |
| torch.random.set_rng_state(_gen_state_cpu) | |
| if _gen_state_cuda is not None: | |
| torch.cuda.set_rng_state_all(_gen_state_cuda) | |
| joint_params = sum(p.numel() for p in student.joint.parameters()) | |
| print_rank0(f" Reinitialized {joint_params/1e6:.1f}M joint parameters", rank) | |
| # SpecAugment | |
| setup_spec_augment(student, args) | |
| # Streaming chunk-aware training: restrict attention context | |
| if args.streaming_chunk_sec > 0: | |
| # Force single attention context mode [70, 13] instead of random multi-context | |
| # Default model has 4 modes: [70,13], [70,6], [70,1], [70,0] sampled randomly | |
| # This forces always using [70, 13] (largest context, lowest latency mode) | |
| student.encoder.att_context_size = [70, 13] | |
| student.encoder.att_context_size_all = [[70, 13]] | |
| student.encoder.att_context_probs = [1.0] | |
| print_rank0(f" Streaming training: forced att_context=[70,13] only (no multi-context)", rank) | |
| # 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) | |
| # Override RNNT loss clamping if requested | |
| if args.rnnt_clamp > 0: | |
| from nemo.collections.asr.losses.rnnt import RNNTLoss | |
| with open_dict(student.cfg): | |
| student.cfg.loss.warprnnt_numba_kwargs.clamp = args.rnnt_clamp | |
| student.loss = RNNTLoss(num_classes=student.decoder.vocab_size, loss_name='default', | |
| loss_kwargs=dict(student.cfg.loss.warprnnt_numba_kwargs)) | |
| print_rank0(f" RNNT loss clamping: {args.rnnt_clamp}", rank) | |
| 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, | |
| max_train_hours=0, seed=42): | |
| 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) | |
| # Subsample to max_train_hours if specified | |
| if max_train_hours > 0: | |
| target_seconds = max_train_hours * 3600 | |
| rng = np.random.RandomState(seed) | |
| rng.shuffle(self.samples) | |
| selected = [] | |
| total_dur = 0.0 | |
| for s in self.samples: | |
| if total_dur >= target_seconds: | |
| break | |
| selected.append(s) | |
| total_dur += s["duration"] | |
| self.samples = selected | |
| self.total_hours = total_dur / 3600 | |
| 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, confidence_penalty=0.0): | |
| """Single forward/backward step: RNNT loss + optional entropy regularization.""" | |
| 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) | |
| 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, | |
| ) | |
| if loss.dim() > 0: | |
| loss = loss.mean() | |
| # Confidence penalty: negative entropy regularization on joint output | |
| # Encourages less confident (more spread) predictions, acts like label smoothing | |
| if confidence_penalty > 0.0: | |
| # Extra forward pass through joint to get logits (works with fuse_loss_wer too) | |
| joint_logits = model.joint(encoder_outputs=enc, decoder_outputs=dec_out) | |
| # joint_logits: (B, T, U, V) log-probabilities | |
| probs = torch.exp(joint_logits) | |
| entropy = -(probs * joint_logits).sum(dim=-1) # (B, T, U) | |
| # Maximize entropy = minimize negative entropy = subtract from loss | |
| loss = loss - confidence_penalty * entropy.mean() | |
| return loss | |
| # ═══════════════════════════════════════════════════════════ | |
| # Evaluation | |
| # ═══════════════════════════════════════════════════════════ | |
| def normalize_text(text): | |
| if _ml_normalizer is not None: | |
| return _ml_normalizer(text) | |
| text = unicodedata.normalize('NFKC', text) | |
| text = text.lower() | |
| text = re.sub(r'[^\w\s]', '', text) | |
| return ' '.join(text.split()) | |
| def normalize_text_fallback(text): | |
| """Always use fallback normalizer for consistency with older runs.""" | |
| 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] | |
| def compute_wer_ids(ref_words, hyp_words): | |
| """Edit distance with backtrace to get S/D/I counts.""" | |
| 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): | |
| if ref_words[i - 1] == hyp_words[j - 1]: | |
| dp[i][j] = dp[i - 1][j - 1] | |
| else: | |
| dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) | |
| subs, dels, ins = 0, 0, 0 | |
| i, j = n, m | |
| while i > 0 or j > 0: | |
| if i > 0 and j > 0 and ref_words[i - 1] == hyp_words[j - 1]: | |
| i -= 1; j -= 1 | |
| elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1: | |
| subs += 1; i -= 1; j -= 1 | |
| elif i > 0 and dp[i][j] == dp[i - 1][j] + 1: | |
| dels += 1; i -= 1 | |
| else: | |
| ins += 1; j -= 1 | |
| return subs, dels, ins | |
| def evaluate_batch(student, manifest_path, device, max_samples=None, normalizer_fn=None, rank=0): | |
| """Evaluate WER using batch (non-streaming) inference.""" | |
| import soundfile as sf_eval | |
| if normalizer_fn is None: | |
| normalizer_fn = normalize_text | |
| 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_edits, total_words = 0, 0 | |
| total_subs, total_dels, total_ins = 0, 0, 0 | |
| errors = 0 | |
| batch_size = 16 | |
| examples = [] | |
| total_batches = (len(samples) + batch_size - 1) // batch_size | |
| for start in range(0, len(samples), batch_size): | |
| batch_samples = samples[start:start + batch_size] | |
| batch_num = start // batch_size + 1 | |
| if (batch_num % 10 == 0 or batch_num == 1) and rank == 0: | |
| print(f" [eval batch {batch_num}/{total_batches}]", flush=True) | |
| 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) | |
| 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 = normalizer_fn(s["text"]) | |
| pred_n = normalizer_fn(pred) | |
| ref_words = ref_n.split() | |
| pred_words = pred_n.split() | |
| if ref_words: | |
| sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words) | |
| total_subs += sub_c | |
| total_dels += del_c | |
| total_ins += ins_c | |
| total_edits += sub_c + del_c + ins_c | |
| 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 and rank == 0: | |
| print(f" [batch eval error] {type(e).__name__}: {e}") | |
| wer_score = total_edits / max(total_words, 1) * 100 | |
| if normalizer_fn is normalize_text and rank == 0: # Only print examples for primary eval | |
| 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} batch eval errors)") | |
| model.train() | |
| return wer_score, total_subs, total_dels, total_ins, total_words | |
| def evaluate_streaming(student, manifest_path, device, max_samples=None, rank=0): | |
| """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() | |
| 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 | |
| total_subs, total_dels, total_ins = 0, 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: | |
| sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words) | |
| total_subs += sub_c | |
| total_dels += del_c | |
| total_ins += ins_c | |
| total_edits += sub_c + del_c + ins_c | |
| 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 and rank == 0: | |
| print(f" [streaming eval error] {type(e).__name__}: {e}") | |
| wer_score = total_edits / max(total_words, 1) * 100 | |
| if rank == 0: | |
| 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, total_subs, total_dels, total_ins, total_words | |
| def compute_val_loss(student, manifest_path, device, max_samples=500): | |
| """Compute RNNT loss on validation set.""" | |
| 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=1e-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 = min(1.0, (step - warmup_steps) / max(1, total_steps - warmup_steps)) | |
| return (min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * progress))) / base_lr | |
| 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, args, device, rank, is_distributed): | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| lang = args.lang.upper() | |
| 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: | |
| decay_epochs = args.lr_decay_epochs if args.lr_decay_epochs > 0 else args.epochs | |
| cosine_total_steps = steps_per_epoch * decay_epochs | |
| scheduler = get_cosine_schedule(optimizer, warmup_steps, cosine_total_steps, args.min_lr) | |
| use_amp = args.bf16 or args.fp16 | |
| amp_dtype = torch.bfloat16 if args.bf16 else torch.float16 | |
| 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 | |
| starting_from = args.resume_from if args.resume_from else args.student | |
| print_rank0(f"\n{'='*65}", rank) | |
| print_rank0(f" {lang} Training Configuration", rank) | |
| print_rank0(f"{'='*65}", rank) | |
| print_rank0(f" Language: {lang}", rank) | |
| print_rank0(f" Starting from: {starting_from}", 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" Min LR: {args.min_lr}", rank) | |
| print_rank0(f" Freeze encoder: first {args.freeze_encoder_epochs} epochs", rank) | |
| print_rank0(f" Mixed precision: {'bf16' if args.bf16 else 'fp16' if args.fp16 else 'off'}", rank) | |
| print_rank0(f" Weight decay: {args.weight_decay}", rank) | |
| print_rank0(f" Grad clip norm: {args.grad_clip}", rank) | |
| if args.no_spec_augment: | |
| print_rank0(f" SpecAugment: OFF", rank) | |
| else: | |
| print_rank0(f" SpecAugment: freq={args.freq_masks}x{args.freq_width} time={args.time_masks}x{args.time_width}", rank) | |
| print_rank0(f" Speed perturb: {args.speed_perturb_factors if args.speed_perturb else 'OFF'}", rank) | |
| print_rank0(f" LR decay epochs: {args.lr_decay_epochs}", rank) | |
| print_rank0(f" Early stop: {args.early_stop_patience} epochs", rank) | |
| if args.confidence_penalty > 0: | |
| print_rank0(f" Confidence penalty: {args.confidence_penalty}", rank) | |
| if args.streaming_chunk_sec > 0: | |
| print_rank0(f" Streaming train: forced att_context=[70,13] only", rank) | |
| print_rank0(f" Val manifest: {args.val_manifest}", rank) | |
| print_rank0(f"{'='*65}\n", rank) | |
| global_step = 0 | |
| best_wer = float("inf") | |
| best_val_loss = float("inf") | |
| patience_counter = 0 | |
| start_epoch = 0 | |
| # Track top-K best WER checkpoints | |
| top_k_wer = 3 | |
| top_k_checkpoints = [] # list of (wer, epoch, path) | |
| # Track WER per epoch for convergence analysis | |
| wer_history = [] | |
| import time as time_module | |
| # Resume from training checkpoint if specified | |
| if args.resume_training: | |
| ckpt_path = args.resume_training | |
| if os.path.isdir(ckpt_path): | |
| # Load latest model weights if available | |
| latest_model_path = os.path.join(ckpt_path, "latest_model.pt") | |
| if os.path.exists(latest_model_path): | |
| print_rank0(f" Loading latest model weights from: {latest_model_path}", rank) | |
| sd = torch.load(latest_model_path, map_location=device, weights_only=False) | |
| model.load_state_dict(sd) | |
| del sd | |
| torch.cuda.empty_cache() | |
| ckpt_path = os.path.join(ckpt_path, "training_state.pt") | |
| if os.path.exists(ckpt_path): | |
| print_rank0(f" Resuming training state from: {ckpt_path}", rank) | |
| ckpt = torch.load(ckpt_path, map_location=device, weights_only=False) | |
| optimizer.load_state_dict(ckpt["optimizer"]) | |
| scheduler.load_state_dict(ckpt["scheduler"]) | |
| start_epoch = ckpt["epoch"] | |
| global_step = ckpt["global_step"] | |
| best_wer = ckpt["best_wer"] | |
| best_val_loss = ckpt["best_val_loss"] | |
| patience_counter = ckpt["patience_counter"] | |
| wer_history = ckpt.get("wer_history", []) | |
| if scaler and "scaler" in ckpt: | |
| scaler.load_state_dict(ckpt["scaler"]) | |
| print_rank0(f" Resumed at epoch {start_epoch}, step {global_step}, best_wer={best_wer:.2f}%", rank) | |
| del ckpt | |
| torch.cuda.empty_cache() | |
| else: | |
| print_rank0(f" WARNING: resume_training path not found: {ckpt_path}", rank) | |
| if is_distributed: | |
| dist.barrier() | |
| # ── Epoch 0: evaluate before any training ── | |
| if start_epoch == 0: | |
| print_rank0(f"\n === Epoch 0 (pre-training baseline) ===", rank) | |
| import sys as _sys | |
| # Compute initial train loss + grad norm on first few batches (all ranks) | |
| student.train() | |
| e0_loss = 0.0 | |
| e0_gnorm = 0.0 | |
| e0_steps = 0 | |
| e0_max_batches = 20 | |
| for batch_idx, batch in enumerate(train_loader): | |
| if batch is None: | |
| continue | |
| if batch_idx >= e0_max_batches: | |
| break | |
| try: | |
| if use_amp: | |
| with torch.amp.autocast("cuda", dtype=amp_dtype): | |
| loss = train_step(student, batch, device, confidence_penalty=0.0) | |
| loss.backward() | |
| else: | |
| loss = train_step(student, batch, device, confidence_penalty=0.0) | |
| loss.backward() | |
| trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None] | |
| gnorm = torch.nn.utils.clip_grad_norm_(trainable, 1e6).item() | |
| e0_loss += loss.item() | |
| if math.isfinite(gnorm): | |
| e0_gnorm += gnorm | |
| e0_steps += 1 | |
| optimizer.zero_grad() | |
| except Exception: | |
| optimizer.zero_grad() | |
| continue | |
| if e0_steps > 0: | |
| print_rank0(f" Epoch 0 train_loss={e0_loss/e0_steps:.4f} gnorm={e0_gnorm/e0_steps:.3f} (avg over {e0_steps} batches)", rank) | |
| # Tear down DDP before eval (same as regular epoch eval) | |
| if is_distributed: | |
| optimizer.zero_grad(set_to_none=True) | |
| del student | |
| student = None | |
| torch.cuda.empty_cache() | |
| dist.barrier() | |
| # Free GPU memory before eval | |
| optimizer.zero_grad(set_to_none=True) | |
| opt_state_backup_e0 = {} | |
| for k, v in optimizer.state.items(): | |
| opt_state_backup_e0[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()} | |
| optimizer.state.clear() | |
| torch.cuda.empty_cache() | |
| gc.collect() | |
| # Evaluate WER + val_loss (all ranks run forward passes) | |
| print_rank0(f"\n Evaluating {lang} (epoch 0)...", rank) | |
| _sys.stdout.flush() | |
| val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank) | |
| print_rank0(f" [eval] WER done", rank); _sys.stdout.flush() | |
| val_loss = compute_val_loss(model, args.val_manifest, device) | |
| print_rank0(f" [eval] val_loss done", rank); _sys.stdout.flush() | |
| if is_main(rank): | |
| print_rank0(f" Epoch 0 WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank) | |
| wer_history.append({ | |
| 'epoch': 0, | |
| 'wer': val_wer, | |
| 'val_loss': val_loss, | |
| 'lr': 0.0, | |
| 'train_loss': e0_loss / max(1, e0_steps), | |
| }) | |
| _sys.stdout.flush() | |
| # Restore optimizer states from CPU | |
| for k, v in opt_state_backup_e0.items(): | |
| optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()} | |
| del opt_state_backup_e0 | |
| torch.cuda.empty_cache() | |
| # Rebuild DDP for training | |
| if is_distributed: | |
| student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True) | |
| optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad] | |
| # Reset dataloader state | |
| if train_sampler is not None: | |
| train_sampler.set_epoch(0) | |
| for epoch in range(start_epoch, args.epochs): | |
| epoch_start = time_module.time() | |
| student.train() | |
| # Decay SpecAugment if enabled (all ranks need updated module) | |
| if args.decay_spec_augment: | |
| update_spec_augment(student, args, epoch, args.epochs, rank) | |
| 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"Encoder frozen ({epoch+1}/{args.freeze_encoder_epochs})" | |
| else: | |
| for p in model.encoder.parameters(): | |
| p.requires_grad = True | |
| phase = "Full training" | |
| 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 | |
| inf_grad_steps = 0 | |
| pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{args.epochs} [{lang}]", | |
| leave=True, ncols=120, disable=not is_main(rank) or not sys.stderr.isatty()) | |
| optimizer.zero_grad() | |
| max_batch_audio_sec = 0.0 | |
| batch_lengths = [] | |
| for batch_idx, batch in enumerate(pbar): | |
| if batch is None: | |
| continue | |
| # Track batch audio lengths | |
| audio, audio_len_t, _, _ = batch | |
| max_audio_samples = audio_len_t.max().item() | |
| total_audio_samples = audio_len_t.sum().item() | |
| max_sec = max_audio_samples / 16000 | |
| total_sec = total_audio_samples / 16000 | |
| batch_lengths.append(max_sec) | |
| if max_sec > max_batch_audio_sec: | |
| max_batch_audio_sec = max_sec | |
| try: | |
| if use_amp: | |
| with torch.amp.autocast("cuda", dtype=amp_dtype): | |
| loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty) | |
| if scaler: | |
| scaled_loss = loss / args.grad_accum | |
| scaler.scale(scaled_loss).backward() | |
| else: | |
| (loss / args.grad_accum).backward() | |
| else: | |
| loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty) | |
| (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} (max_audio={max_sec:.1f}s, total={total_sec:.1f}s, batch_size={len(audio_len_t)}), 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, args.grad_clip).item() | |
| if scaler: | |
| scaler.step(optimizer) | |
| scaler.update() | |
| else: | |
| optimizer.step() | |
| if math.isfinite(grad_norm): | |
| epoch_grad_norm += grad_norm | |
| grad_norm_steps += 1 | |
| else: | |
| inf_grad_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"] | |
| gnorm_str = f"{avg_gnorm:.2f}" if grad_norm_steps > 0 else "n/a" | |
| if inf_grad_steps > 0: | |
| gnorm_str += f" ({inf_grad_steps} skipped)" | |
| pbar.set_postfix(loss=f"{avg_loss:.3f}", gnorm=gnorm_str, | |
| 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) | |
| gnorm_display = f"{avg_gnorm:.3f}" if grad_norm_steps > 0 else "n/a" | |
| if inf_grad_steps > 0: | |
| gnorm_display += f" ({inf_grad_steps} inf-skipped)" | |
| 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 | |
| # Batch length stats | |
| if batch_lengths: | |
| avg_max_sec = sum(batch_lengths) / len(batch_lengths) | |
| p95 = sorted(batch_lengths)[int(0.95 * len(batch_lengths))] | |
| 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) | |
| print_rank0(f"\n Epoch {epoch+1} [{lang}] | {phase} | loss={avg_loss:.4f} " | |
| f"gnorm={gnorm_display} lr={optimizer.param_groups[0]['lr']:.2e}" | |
| f" | {epoch_time/60:.1f}min | {samples_per_sec:.0f} samples/s | GPU: {gpu_mem:.1f}GB", rank) | |
| # Tear down DDP before eval to remove forward hooks from model. | |
| # DDP with find_unused_parameters=True registers hooks on the underlying | |
| # model, so calling model.forward() during rank-0-only eval would trigger | |
| # DDP communication and deadlock the other ranks. | |
| if is_distributed: | |
| optimizer.zero_grad(set_to_none=True) | |
| del student | |
| student = None | |
| torch.cuda.empty_cache() | |
| dist.barrier() | |
| # Free GPU memory before eval: offload optimizer states to CPU | |
| optimizer.zero_grad(set_to_none=True) | |
| opt_state_backup = {} | |
| for k, v in optimizer.state.items(): | |
| opt_state_backup[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()} | |
| optimizer.state.clear() | |
| torch.cuda.empty_cache() | |
| gc.collect() | |
| mem_after = torch.cuda.memory_allocated(device) / 1e9 | |
| print_rank0(f" [pre-eval] GPU mem after offload: {mem_after:.1f}GB", rank) | |
| import sys as _sys; _sys.stdout.flush() | |
| # Evaluation — ALL ranks run forward passes (needed for SyncBatchNorm / distributed | |
| # layers inside NeMo encoder), but only rank 0 uses the results. | |
| if (epoch + 1) % args.eval_every_epoch == 0: | |
| try: | |
| print_rank0(f"\n Evaluating {lang}...", rank) | |
| _sys.stdout.flush() | |
| val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank) | |
| print_rank0(f" [eval] WER done", rank); _sys.stdout.flush() | |
| val_loss = compute_val_loss(model, args.val_manifest, device) | |
| print_rank0(f" [eval] val_loss done", rank); _sys.stdout.flush() | |
| if is_main(rank): | |
| print_rank0(f" {lang} Batch WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank) | |
| wer_history.append({ | |
| 'epoch': epoch + 1, | |
| 'wer': val_wer, | |
| 'val_loss': val_loss, | |
| 'lr': optimizer.param_groups[0]["lr"], | |
| 'train_loss': avg_loss, | |
| }) | |
| if val_wer < best_wer: | |
| best_wer = val_wer | |
| patience_counter = 0 | |
| save_path = os.path.join(args.output_dir, "best_model.nemo") | |
| print_rank0(f" [saving] best_model.nemo...", rank); _sys.stdout.flush() | |
| model.save_to(save_path) | |
| print_rank0(f" New best WER! WER={best_wer:.2f}% -> {save_path}", rank) | |
| else: | |
| patience_counter += 1 | |
| print_rank0(f" No WER improvement ({patience_counter}/{args.early_stop_patience})", rank) | |
| # Save top-K best WER checkpoints for post-hoc evaluation | |
| should_save_topk = len(top_k_checkpoints) < top_k_wer or val_wer < top_k_checkpoints[-1][0] | |
| if should_save_topk: | |
| topk_path = os.path.join(args.output_dir, f"best_model_wer_ep{epoch+1}.nemo") | |
| print_rank0(f" [saving] top-{top_k_wer} checkpoint (WER={val_wer:.2f}%)...", rank); _sys.stdout.flush() | |
| model.save_to(topk_path) | |
| top_k_checkpoints.append((val_wer, epoch + 1, topk_path)) | |
| top_k_checkpoints.sort(key=lambda x: x[0]) # sort by WER ascending | |
| # Remove worst checkpoint if we exceed top_k_wer | |
| while len(top_k_checkpoints) > top_k_wer: | |
| _, _, old_path = top_k_checkpoints.pop() | |
| if os.path.exists(old_path): | |
| os.remove(old_path) | |
| print_rank0(f" [removed] {os.path.basename(old_path)}", 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 | |
| if val_loss < best_val_loss: | |
| best_val_loss = val_loss | |
| save_path = os.path.join(args.output_dir, "best_model_loss.nemo") | |
| print_rank0(f" [saving] best_model_loss.nemo...", rank); _sys.stdout.flush() | |
| model.save_to(save_path) | |
| print_rank0(f" New best loss! loss={best_val_loss:.4f} -> {save_path}", rank) | |
| except Exception as e: | |
| print_rank0(f" [eval error] {type(e).__name__}: {e} — skipping", rank) | |
| print_rank0(f" [post-eval] reaching barrier...", rank); sys.stdout.flush() | |
| # Restore optimizer states from CPU | |
| for k, v in opt_state_backup.items(): | |
| optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()} | |
| del opt_state_backup | |
| torch.cuda.empty_cache() | |
| # Rebuild DDP for next training epoch (after eval is done) | |
| if is_distributed: | |
| student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True) | |
| optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad] | |
| # Save full training state for resumability | |
| if is_main(rank) and args.save_every_epoch > 0 and (epoch + 1) % args.save_every_epoch == 0: | |
| # Save latest model weights as raw state dict (fast, avoids NeMo save_to overhead) | |
| latest_path = os.path.join(args.output_dir, "latest_model.pt") | |
| torch.save(model.state_dict(), latest_path + ".tmp") | |
| os.replace(latest_path + ".tmp", latest_path) | |
| state = { | |
| "epoch": epoch + 1, | |
| "global_step": global_step, | |
| "optimizer": optimizer.state_dict(), | |
| "scheduler": scheduler.state_dict(), | |
| "best_wer": best_wer, | |
| "best_val_loss": best_val_loss, | |
| "patience_counter": patience_counter, | |
| "wer_history": wer_history, | |
| } | |
| if scaler: | |
| state["scaler"] = scaler.state_dict() | |
| state_path = os.path.join(args.output_dir, "training_state.pt") | |
| torch.save(state, state_path + ".tmp") | |
| os.replace(state_path + ".tmp", state_path) | |
| # Clear GPU memory fragmentation from eval/save before next training epoch | |
| torch.cuda.empty_cache() | |
| if is_distributed: | |
| dist.barrier() | |
| # Save WER history for convergence analysis | |
| if is_main(rank): | |
| history_path = os.path.join(args.output_dir, "wer_history.json") | |
| with open(history_path, "w") as f: | |
| json.dump(wer_history, f, indent=2) | |
| print_rank0(f"\n WER history saved to {history_path}", rank) | |
| # Final save | |
| save_path = os.path.join(args.output_dir, "final_model.nemo") | |
| model.save_to(save_path) | |
| print_rank0(f" Final model -> {save_path}", rank) | |
| print_rank0(f" Best {lang} WER: {best_wer:.2f}%", rank) | |
| return student | |
| # ═══════════════════════════════════════════════════════════ | |
| # Entry Point | |
| # ═══════════════════════════════════════════════════════════ | |
| def main(): | |
| args = parse_args() | |
| rank, world_size, local_rank, is_distributed = setup_ddp() | |
| device = torch.device(f"cuda:{local_rank}") | |
| torch.manual_seed(args.seed + rank) | |
| np.random.seed(args.seed + rank) | |
| torch.cuda.manual_seed_all(args.seed + rank) | |
| import random | |
| random.seed(args.seed + rank) | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| lang = args.lang.upper() | |
| starting_from = "multilingual base" if args.resume_from else "English checkpoint" | |
| print_rank0(f"\n{'='*65}", rank) | |
| print_rank0(f" Nemotron Streaming ASR — {lang} Training", rank) | |
| print_rank0(f"{'='*65}", rank) | |
| print_rank0(f" Language: {lang}", rank) | |
| print_rank0(f" Path: {starting_from}", rank) | |
| print_rank0(f" GPUs: {world_size}", rank) | |
| if args.resume_from: | |
| print_rank0(f" Base: {args.resume_from}", rank) | |
| else: | |
| print_rank0(f" Student: {args.student}", rank) | |
| print_rank0(f" Train: {args.train_manifest}", rank) | |
| print_rank0(f" Val: {args.val_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, | |
| max_train_hours=args.max_train_hours, | |
| seed=args.data_seed, | |
| ) | |
| print_rank0(f" Train dataset: {len(train_dataset)} samples", rank) | |
| if args.max_train_hours > 0: | |
| print_rank0(f" Subsampled to {train_dataset.total_hours:.1f}h (requested {args.max_train_hours}h)", rank) | |
| # Offset by -42 so --seed=42 (default) keeps PyTorch's default sampler seed=0 | |
| # for backward compat with prior runs. --seed=43 -> sampler seed=1, etc. | |
| train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=args.seed - 42) 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, | |
| ) | |
| # Train | |
| print_rank0(f"\n[3/3] Starting {lang} training...", rank) | |
| student = train( | |
| student, train_loader, train_sampler, | |
| args, device, rank, is_distributed, | |
| ) | |
| # Final eval on best model — all ranks run eval (NeMo model has distributed internals), | |
| # only rank 0 prints/uses results | |
| import nemo.collections.asr as nemo_asr | |
| best_path = os.path.join(args.output_dir, "best_model.nemo") | |
| if os.path.exists(best_path): | |
| print_rank0(f"\n Loading best model from {best_path}...", rank) | |
| best_model = nemo_asr.models.ASRModel.restore_from(best_path, map_location=device) | |
| best_model = best_model.to(device) | |
| best_model.eval() | |
| else: | |
| print_rank0(f"\n Best model not found, using final model.", rank) | |
| best_model = model | |
| print_rank0(f"\n{'='*65}", rank) | |
| print_rank0(f" Final Evaluation — {lang} (best checkpoint)", rank) | |
| print_rank0(f"{'='*65}", rank) | |
| batch_wer, b_s, b_d, b_i, b_w = evaluate_batch(best_model, args.val_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| print_rank0(f" Counts: subs={b_s} dels={b_d} ins={b_i} / {b_w} ref words", rank) | |
| print_rank0(f"\n Running streaming eval...", rank) | |
| stream_wer, s_s, s_d, s_i, s_w = evaluate_streaming(best_model, args.val_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| print_rank0(f" Counts: subs={s_s} dels={s_d} ins={s_i} / {s_w} ref words", rank) | |
| if args.test_manifest: | |
| print_rank0(f"\n{'='*65}", rank) | |
| print_rank0(f" Test Evaluation — {lang} (best checkpoint)", rank) | |
| print_rank0(f"{'='*65}", rank) | |
| test_batch_wer, tb_s, tb_d, tb_i, tb_w = evaluate_batch(best_model, args.test_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| print_rank0(f" Counts: subs={tb_s} dels={tb_d} ins={tb_i} / {tb_w} ref words", rank) | |
| print_rank0(f"\n Running streaming test eval...", rank) | |
| test_stream_wer, ts_s, ts_d, ts_i, ts_w = evaluate_streaming(best_model, args.test_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| print_rank0(f" Counts: subs={ts_s} dels={ts_d} ins={ts_i} / {ts_w} ref words", rank) | |
| del best_model | |
| torch.cuda.empty_cache() | |
| # Evaluate best-by-loss model if it exists | |
| best_loss_path = os.path.join(args.output_dir, "best_model_loss.nemo") | |
| if os.path.exists(best_loss_path): | |
| print_rank0(f"\n{'='*65}", rank) | |
| print_rank0(f" Final Evaluation — {lang} (best loss checkpoint)", rank) | |
| print_rank0(f"{'='*65}", rank) | |
| print_rank0(f" Loading best-by-loss model from {best_loss_path}...", rank) | |
| best_loss_model = nemo_asr.models.ASRModel.restore_from(best_loss_path, map_location=device) | |
| best_loss_model = best_loss_model.to(device) | |
| best_loss_model.eval() | |
| bl_wer, bl_s, bl_d, bl_i, bl_w = evaluate_batch(best_loss_model, args.val_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| if args.test_manifest: | |
| tbl_wer, tbl_s, tbl_d, tbl_i, tbl_w = evaluate_batch(best_loss_model, args.test_manifest, device, rank=rank) | |
| if is_main(rank): | |
| 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) | |
| del best_loss_model | |
| torch.cuda.empty_cache() | |
| # All ranks must wait for rank 0's final eval before destroying process group | |
| if is_distributed: | |
| dist.barrier() | |
| cleanup_ddp(is_distributed) | |
| if __name__ == "__main__": | |
| main() | |