#!/usr/bin/env python3 """Unified DDP trainer for FastConformer-Hybrid (RNNT+CTC), Phase A or Phase B. Works single- or multi-GPU. For streaming bases the cache-aware encoder cfg is left untouched (only data/opt/joint-fuse are set), so streaming behavior is preserved. Phase A example (8xH100): --lr 1e-3 --warmup 5000 --max-steps 70000 --bd 1600 --devices 8 Phase B example: --lr 4e-5 --warmup 500 --max-steps 15000 --bd 1600 --devices 8""" import argparse, lightning.pytorch as pl from omegaconf import OmegaConf, open_dict from nemo.collections.asr.models import ASRModel from nemo.utils.exp_manager import exp_manager ap=argparse.ArgumentParser() ap.add_argument("--base", required=True, help="restore_from .nemo (persianized base for Phase A, Phase-A model for Phase B)") ap.add_argument("--train", required=True); ap.add_argument("--val", required=True) ap.add_argument("--exp", required=True); ap.add_argument("--name", required=True) ap.add_argument("--lr", type=float, default=1e-3) ap.add_argument("--min-lr", type=float, default=1e-5) ap.add_argument("--warmup", type=int, default=5000) ap.add_argument("--max-steps", type=int, default=70000) ap.add_argument("--bd", type=int, default=1600, help="PER-GPU batch_duration; global ~= bd*devices") ap.add_argument("--devices", type=int, default=8) ap.add_argument("--workers", type=int, default=12, help="per-GPU dataloader workers (devices*workers <= cores)") ap.add_argument("--fuse", type=int, default=16) ap.add_argument("--maxdur", type=float, default=45.0) ap.add_argument("--val-interval", type=int, default=2000) ap.add_argument("--patience", type=int, default=8) ap.add_argument("--ddp-find-unused", action="store_true", help="set if DDP complains about unused params") ap.add_argument("--att-context", default=None, help='streaming look-ahead, e.g. "[70,1]" (80ms), "[70,0]" (0ms), or multi "[[70,13],[70,6],[70,1],[70,0]]"') a=ap.parse_args() m=ASRModel.restore_from(a.base, map_location="cpu") cfg=m.cfg if a.att_context: import ast as _ast ac=_ast.literal_eval(a.att_context) with open_dict(cfg): cfg.encoder.att_context_size=ac try: single = ac if (ac and isinstance(ac[0],int)) else ac[-1] # lowest-latency for multi m.encoder.set_default_att_context_size(single) print(f"[latency] att_context_size set -> {ac} (default infer ctx {single}; right*80ms = look-ahead)",flush=True) except Exception as e: print("att_context note:",e) with open_dict(cfg): for ds,mf,sh in [(cfg.train_ds,a.train,True),(cfg.validation_ds,a.val,False)]: ds.manifest_filepath=mf; ds.is_tarred=False ds.use_lhotse=True; ds.batch_size=None ds.batch_duration=a.bd; ds.quadratic_duration=15 ds.use_bucketing=True; ds.num_buckets=30; ds.bucket_buffer_size=20000; ds.shuffle_buffer_size=10000 ds.shuffle=sh; ds.num_workers=a.workers; ds.pin_memory=True; ds.pretokenize=False ds.max_duration=a.maxdur; ds.min_duration=0.3 if "tarred_audio_filepaths" in ds: ds.tarred_audio_filepaths=None if "augmentor" in ds: ds.augmentor=None cfg.train_ds.perturb_speed=True cfg.joint.fuse_loss_wer=True; cfg.joint.fused_batch_size=a.fuse m.setup_training_data(cfg.train_ds); m.setup_validation_data(cfg.validation_ds) try: m.joint.fuse_loss_wer=True; m.joint.fused_batch_size=a.fuse except Exception as e: print("joint-fuse note:",e) m.setup_optimization(OmegaConf.create({"name":"adamw","lr":a.lr,"weight_decay":1e-3,"betas":[0.9,0.98], "sched":{"name":"CosineAnnealing","warmup_steps":a.warmup,"min_lr":a.min_lr,"max_steps":a.max_steps}})) strat = "auto" if a.devices==1 else ("ddp_find_unused_parameters_true" if a.ddp_find_unused else "ddp") tr=pl.Trainer(logger=False, devices=a.devices, accelerator="gpu", strategy=strat, precision="bf16-mixed", max_steps=a.max_steps, accumulate_grad_batches=1, val_check_interval=a.val_interval, limit_val_batches=1.0, gradient_clip_val=1.0, log_every_n_steps=200, enable_checkpointing=False, enable_progress_bar=True, num_sanity_val_steps=0) m.set_trainer(tr) exp_manager(tr, OmegaConf.create({"exp_dir":a.exp,"name":a.name,"create_checkpoint_callback":True, "checkpoint_callback_params":{"monitor":"val_wer","mode":"min","save_top_k":3,"always_save_nemo":True}, "resume_if_exists":True,"resume_ignore_no_checkpoint":True, "create_early_stopping_callback":True,"early_stopping_callback_params":{"monitor":"val_wer","mode":"min","patience":a.patience,"min_delta":0.001}})) print(f"=== DDP fit: devices={a.devices} strategy={strat} lr={a.lr} bd={a.bd} (global~={a.bd*a.devices}s) base={a.base} ===",flush=True) tr.fit(m); print("=== fit returned ===",flush=True)