#!/usr/bin/env python3 import argparse import json import os import shutil import subprocess import time from pathlib import Path import torch import pytorch_lightning as pl from omegaconf import OmegaConf, open_dict from pytorch_lightning.callbacks import Callback, TQDMProgressBar import nemo.collections.asr as nemo_asr ############################################################################### # DATASET CONFIGURATION ############################################################################### # train.py is intended to live directly inside the training-data folder. # This makes the whole training-data directory portable as one upload. DATA_ROOT = Path(__file__).resolve().parent # Manifest paths are selected at startup. # # Normal: # train_manifest.json # kirtan_val_manifest.json # sehaj_paath_val_manifest.json # # --test: # train_manifest-test.json # kirtan_val_manifest.json (FULL validation) # sehaj_paath_val_manifest.json (FULL validation) # # Audio paths inside the manifests are used exactly as written. TRAIN_MANIFEST = None KIRTAN_VAL_MANIFEST = None SEHAJ_VAL_MANIFEST = None def configure_manifests(test_mode: bool) -> None: """Use small training data in --test, but always use full validation.""" global TRAIN_MANIFEST global KIRTAN_VAL_MANIFEST global SEHAJ_VAL_MANIFEST if test_mode: TRAIN_MANIFEST = DATA_ROOT / "train_manifest-test.json" else: TRAIN_MANIFEST = DATA_ROOT / "train_manifest_max30s.json" # Always score the real/full validation sets, including --test. KIRTAN_VAL_MANIFEST = DATA_ROOT / "kirtan_val_manifest.json" SEHAJ_VAL_MANIFEST = DATA_ROOT / "sehaj_paath_val_manifest.json" EXPECTED_SAMPLE_RATE = 16_000 LANGUAGE_CODE = "pa" # Use one explicit decoder for validation so the metric is stable across epochs. # The model is hybrid RNNT+CTC; CTC is used here only for explicit WER/CER scoring. VALIDATION_DECODER = "ctc" ############################################################################### # MODEL CONFIGURATION ############################################################################### # Restore the multilingual AI4Bharat base model with Punjabi ('pa') support. MODEL_PATH = Path( "/workspace/resume_checkpoint/baniguru_kirtan_v2_best.nemo" ).expanduser().resolve() # Optional checkpoint overlay. # Set to None to train directly from MODEL_PATH only. # Example: LAST_STABLE_CHECKPOINT_PATH = Path( "/workspace/resume_checkpoint/last_stable.ckpt" ).expanduser().resolve() # Resume from the latest CTC-verified stable checkpoint. START_CHECKPOINT_PATH = LAST_STABLE_CHECKPOINT_PATH # START_CHECKPOINT_PATH = None ############################################################################### # TRAINING CONFIGURATION ############################################################################### BATCH_SIZE = 8 # Conservative full-model fine-tuning rate after Stage-2 adaptation. LEARNING_RATE = 1e-5 # Upper limit. # Early stopping can stop training before reaching this. MAX_EPOCHS = 50 # Effective batch size: # # BATCH_SIZE * ACCUMULATE_GRAD_BATCHES # # 4 * 2 = 8 ACCUMULATE_GRAD_BATCHES = 1 # Tiny fixed CTC probe during training. CTC_PROBE_EVERY_OPTIMIZER_STEPS = 1000 CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS = 2000 CTC_PROBE_SAMPLE_COUNT = 2 ############################################################################### # EARLY STOPPING CONFIGURATION ############################################################################### # Stop after this many consecutive validation epochs without improvement. EARLY_STOP_PATIENCE = 10 # WER needs to improve by at least this much to count as an improvement. # # Example: # old WER = 0.1000 # new WER = 0.09995 # # Difference = 0.00005 # # With MIN_WER_IMPROVEMENT = 0.0001, # that would NOT count as an improvement. MIN_WER_IMPROVEMENT = 0.0001 # Kirtan CER is the primary checkpoint metric. Sehaj WER may also promote # a checkpoint when it improves by at least MIN_WER_IMPROVEMENT and Kirtan # CER is no more than 0.5 percentage points worse than the currently selected # best checkpoint. CER is stored as a fraction, so 0.005 == 0.5 points. KIRTAN_CER_TOLERANCE_FOR_SEHAJ = 0.005 ############################################################################### # CLOUDFLARE R2 BACKUP CONFIGURATION ############################################################################### # Upload ONLY best.ckpt when the Kirtan-primary / Sehaj-tie-break rule improves. # Credentials are read from environment variables so secrets are not stored # inside this training script. R2_UPLOAD_ENABLED = True R2_OBJECT_KEY = os.environ.get( "R2_OBJECT_KEY", "checkpoints/best.ckpt", ) R2_UPLOAD_RETRIES = 3 R2_RETRY_DELAY_SECONDS = 10 ############################################################################### # VAST.AI AUTO-DESTROY CONFIGURATION ############################################################################### # Full runs automatically destroy the current Vast instance only after: # 1. training has finished (early stopping or max epochs), AND # 2. a best.ckpt was successfully uploaded to R2. # # --test NEVER destroys the instance. AUTO_DESTROY_VAST = False ############################################################################### # OUTPUT / CHECKPOINT / LOG CONFIGURATION ############################################################################### # Put large/persistent training outputs under this directory. # # Vast.ai workspace output directory. # # Checkpoints, metrics, and the final model stay under OUTPUT_ROOT. # # OUTPUT_ROOT/ # ├── checkpoints/ # │ ├── best.ckpt # │ ├── epoch_XXX.ckpt # │ └── epoch_YYY.ckpt # ├── wer_history.json # └── gurbani_sehaj_paath_v1_base_indicconformer_stt_multi_hybrid_rnnt_600m.nemo # OUTPUT_ROOT = Path( "/workspace/asr_training" ).expanduser().resolve() # Final .nemo model saved when training finishes / early-stops. OUTPUT_MODEL = ( OUTPUT_ROOT / "baniguru_kirtan_v3.nemo" ) # Best checkpoint + last two epoch checkpoints. CHECKPOINT_DIR = ( OUTPUT_ROOT / "checkpoints" ) BEST_CHECKPOINT_PATH = ( CHECKPOINT_DIR / "best.ckpt" ) # Per-epoch validation metrics for BOTH domains. # Contains kirtan WER/CER + sehaj WER/CER. EPOCH_METRICS_PATH = ( OUTPUT_ROOT / "epoch_metrics.json" ) def configure_outputs(test_mode: bool, offline: bool = False) -> None: """Keep test artifacts separate and optionally disable R2 for test runs.""" global OUTPUT_ROOT global OUTPUT_MODEL global CHECKPOINT_DIR global BEST_CHECKPOINT_PATH global EPOCH_METRICS_PATH global R2_OBJECT_KEY global R2_UPLOAD_ENABLED if test_mode: OUTPUT_ROOT = Path("/workspace/asr_training_test").expanduser().resolve() OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_v3.nemo" CHECKPOINT_DIR = OUTPUT_ROOT / "checkpoints" BEST_CHECKPOINT_PATH = CHECKPOINT_DIR / "best.ckpt" EPOCH_METRICS_PATH = OUTPUT_ROOT / "epoch_metrics.json" # Online test runs use a separate R2 object and never overwrite # the full-run best checkpoint. R2_OBJECT_KEY = "checkpoints/test-best.ckpt" if offline: # --offline is intentionally restricted to --test in parse_args(). R2_UPLOAD_ENABLED = False ############################################################################### # CALLBACK: PROGRESS BAR WITH HUMAN-READABLE EPOCH NUMBER ############################################################################### class EpochProgressBar(TQDMProgressBar): def get_metrics(self, trainer, pl_module): items = super().get_metrics(trainer, pl_module) items["epoch"] = trainer.current_epoch + 1 return items ############################################################################### # CALLBACK: EPOCH TIMER ############################################################################### class EpochTimer(Callback): def __init__(self): super().__init__() self.start_time = None def on_train_epoch_start( self, trainer, pl_module, ): self.start_time = time.time() def on_train_epoch_end( self, trainer, pl_module, ): if self.start_time is None: print( f"\nEpoch {trainer.current_epoch + 1} completed " "(timer unavailable because training resumed mid-epoch)" ) return elapsed = time.time() - self.start_time print( f"\nEpoch {trainer.current_epoch + 1} " f"completed in {elapsed / 60:.2f} minutes" ) ############################################################################### # VALIDATION METRICS HELPERS ############################################################################### def levenshtein_ops(reference, hypothesis): """ Return (substitutions, deletions, insertions) for two sequences. """ n = len(reference) m = len(hypothesis) # dp[i][j] = (cost, S, D, I) dp = [[None] * (m + 1) for _ in range(n + 1)] dp[0][0] = (0, 0, 0, 0) for i in range(1, n + 1): dp[i][0] = (i, 0, i, 0) for j in range(1, m + 1): dp[0][j] = (j, 0, 0, j) for i in range(1, n + 1): for j in range(1, m + 1): if reference[i - 1] == hypothesis[j - 1]: dp[i][j] = dp[i - 1][j - 1] continue sub_prev = dp[i - 1][j - 1] del_prev = dp[i - 1][j] ins_prev = dp[i][j - 1] candidates = [ ( sub_prev[0] + 1, sub_prev[1] + 1, sub_prev[2], sub_prev[3], ), ( del_prev[0] + 1, del_prev[1], del_prev[2] + 1, del_prev[3], ), ( ins_prev[0] + 1, ins_prev[1], ins_prev[2], ins_prev[3] + 1, ), ] dp[i][j] = min( candidates, key=lambda item: ( item[0], item[2], # prefer fewer deletions on ties item[3], item[1], ), ) _, substitutions, deletions, insertions = dp[n][m] return substitutions, deletions, insertions def extract_text_from_hypothesis(item): if isinstance(item, str): return item if hasattr(item, "text"): return str(item.text) if isinstance(item, dict): if "text" in item: return str(item["text"]) if "pred_text" in item: return str(item["pred_text"]) return str(item) def select_primary_transcriptions(outputs, expected_count): """ Normalize NeMo transcribe() output. Hybrid RNNT+CTC models can return more than one decoding branch. We select the first complete branch, which is treated here as the primary transcription stream for BOTH domains and all epochs. """ if isinstance(outputs, tuple): outputs = list(outputs) if isinstance(outputs, list): # Normal case: one hypothesis per input. if len(outputs) == expected_count and ( expected_count == 0 or not isinstance(outputs[0], (list, tuple)) ): return [ extract_text_from_hypothesis(item) for item in outputs ] # Hybrid case: [rnnt_outputs, ctc_outputs, ...] for branch in outputs: if ( isinstance(branch, (list, tuple)) and len(branch) == expected_count ): return [ extract_text_from_hypothesis(item) for item in branch ] raise RuntimeError( "Could not identify the primary transcribe() output branch. " f"Expected {expected_count} predictions; got type={type(outputs)}" ) def load_validation_manifest(manifest_path: Path): samples = [] with Path(manifest_path).open( "r", encoding="utf-8", ) as handle: for line_number, line in enumerate( handle, start=1, ): line = line.strip() if not line: continue item = json.loads(line) audio_path = item.get( "audio_filepath" ) text = item.get( "text" ) if not audio_path: raise RuntimeError( f"{manifest_path}: line {line_number} " "has no audio_filepath." ) if text is None: raise RuntimeError( f"{manifest_path}: line {line_number} " "has no text." ) language = item.get("lang") if language != LANGUAGE_CODE: raise RuntimeError( f"{manifest_path}: line {line_number} " f"must have lang='{LANGUAGE_CODE}', got {language!r}." ) samples.append( { "audio_filepath": str(audio_path), "text": " ".join( str(text).strip().split() ), "lang": language, } ) if not samples: raise RuntimeError( f"Validation manifest is empty: {manifest_path}" ) return samples def score_validation_manifest( model, manifest_path: Path, batch_size: int, ): """ Explicitly transcribe one validation manifest and return STRICT word-level WER and character-level CER. Validation is forced onto one decoder (CTC) for every epoch so a hybrid RNNT+CTC model cannot silently switch decoding branches between calls. The model's training/eval state and previous decoder are restored even if validation raises an exception. Spaces are excluded from CER. """ samples = load_validation_manifest( manifest_path ) total_word_substitutions = 0 total_word_deletions = 0 total_word_insertions = 0 total_reference_words = 0 total_predicted_words = 0 total_char_substitutions = 0 total_char_deletions = 0 total_char_insertions = 0 total_reference_chars = 0 total_predicted_chars = 0 # CTC health guard. A catastrophic decoder collapse must never be turned # into a fake WER, checkpoint, R2 upload, or early-stop event. special_or_empty_outputs = 0 checked_outputs = 0 was_training = model.training previous_decoder = getattr( model, "cur_decoder", None, ) model.eval() # Hybrid RNNT+CTC models keep a current decoder. Force validation to use # exactly the same branch every time. The AI4Bharat/NeMo hybrid model # exposes cur_decoder; fail loudly if that contract is unavailable. if not hasattr(model, "cur_decoder"): raise RuntimeError( "Hybrid validation expected model.cur_decoder, but the restored " "model does not expose it. Refusing to compute an ambiguous WER." ) model.cur_decoder = VALIDATION_DECODER try: with torch.no_grad(): for start in range( 0, len(samples), batch_size, ): batch = samples[ start: start + batch_size ] audio_paths = [ item["audio_filepath"] for item in batch ] outputs = model.transcribe( audio_paths, batch_size=batch_size, return_hypotheses=False, verbose=True, language_id=LANGUAGE_CODE, ) hypotheses = select_primary_transcriptions( outputs, expected_count=len(batch), ) normalized_batch = [ " ".join(str(value).strip().split()) for value in hypotheses ] checked_outputs += len(normalized_batch) special_or_empty_outputs += sum( value in {"", "", ""} for value in normalized_batch ) # Print one compact diagnostic batch per validation manifest. # This is intentionally kept in the normal log so a future # decoder regression can be diagnosed without another rerun. if start == 0: print("\nVALIDATION DEBUG") print(f"Manifest: {manifest_path}") print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}") print(f"Outputs type: {type(outputs)}") normalized_debug = normalized_batch # The failure observed previously produced one special token # (for example ) for every sample. Never turn that # decoder failure into a fake 100% WER / early-stop event. if normalized_debug and all( value in {"", "", ""} for value in normalized_debug ): raise RuntimeError( "Validation decoder returned only special/empty " f"tokens for {manifest_path}: " f"{normalized_debug[:5]}. " "Stopping instead of recording a false WER." ) for batch_index, (sample, hypothesis) in enumerate( zip(batch, hypotheses), ): reference = " ".join( sample["text"].strip().split() ) hypothesis = " ".join( hypothesis.strip().split() ) validation_index = start + batch_index + 1 print( f" [{validation_index}] REF : {reference}" ) print( f" [{validation_index}] PRED: {hypothesis}" ) ref_words = reference.split() hyp_words = hypothesis.split() ( word_s, word_d, word_i, ) = levenshtein_ops( ref_words, hyp_words, ) total_word_substitutions += word_s total_word_deletions += word_d total_word_insertions += word_i total_reference_words += len( ref_words ) total_predicted_words += len( hyp_words ) # CER excludes spaces. ref_chars = list( reference.replace(" ", "") ) hyp_chars = list( hypothesis.replace(" ", "") ) ( char_s, char_d, char_i, ) = levenshtein_ops( ref_chars, hyp_chars, ) total_char_substitutions += char_s total_char_deletions += char_d total_char_insertions += char_i total_reference_chars += len( ref_chars ) total_predicted_chars += len( hyp_chars ) finally: # Restore decoder state before handing the model back to Lightning. model.cur_decoder = previous_decoder if was_training: model.train() else: model.eval() # Full-manifest protection as a second line of defense. The historical # failure returned for essentially every sample. Abort before any # metric/checkpoint action if >=95% of outputs are special/empty. special_ratio = ( special_or_empty_outputs / checked_outputs if checked_outputs else 1.0 ) if checked_outputs == 0: raise RuntimeError( f"Validation produced zero hypotheses for {manifest_path}." ) if special_ratio >= 0.95: raise RuntimeError( "CTC VALIDATION COLLAPSE DETECTED: " f"{special_or_empty_outputs}/{checked_outputs} " f"({special_ratio * 100.0:.2f}%) hypotheses were " f"//empty for {manifest_path}. " "Training is being aborted. No checkpoint from this epoch " "will be promoted or uploaded." ) word_errors = ( total_word_substitutions + total_word_deletions + total_word_insertions ) char_errors = ( total_char_substitutions + total_char_deletions + total_char_insertions ) wer = ( word_errors / total_reference_words if total_reference_words else 0.0 ) cer = ( char_errors / total_reference_chars if total_reference_chars else 0.0 ) return { "samples": len(samples), "ctc_special_or_empty_outputs": special_or_empty_outputs, "ctc_checked_outputs": checked_outputs, "ctc_special_or_empty_ratio": special_ratio, "wer": wer, "wer_percent": wer * 100.0, "word_errors": word_errors, "total_reference_words": total_reference_words, "total_predicted_words": total_predicted_words, "word_substitutions": total_word_substitutions, "word_deletions": total_word_deletions, "word_insertions": total_word_insertions, "cer": cer, "cer_percent": cer * 100.0, "char_errors": char_errors, "total_reference_characters": total_reference_chars, "total_predicted_characters": total_predicted_chars, "char_substitutions": total_char_substitutions, "char_deletions": total_char_deletions, "char_insertions": total_char_insertions, } ############################################################################### # PRE-TRAIN CTC HEALTH CHECK ############################################################################### def run_pretrain_ctc_health_check(model, batch_size: int) -> None: """ Refuse to begin training unless the clean base model can successfully decode BOTH full validation manifests through the exact same CTC path used after every epoch. """ print("\n======================================") print("PRE-TRAIN CTC HEALTH CHECK") print("======================================") print("No training has happened yet.") print("Kirtan and Sehaj must both decode successfully before trainer.fit().") print("\nPre-train KIRTAN CTC validation...") kirtan = score_validation_manifest( model=model, manifest_path=KIRTAN_VAL_MANIFEST, batch_size=batch_size, ) print("\nPre-train SEHAJ PAATH CTC validation...") sehaj = score_validation_manifest( model=model, manifest_path=SEHAJ_VAL_MANIFEST, batch_size=batch_size, ) print("\nPRE-TRAIN CTC HEALTH CHECK PASSED") print( f"Kirtan WER: {kirtan['wer']:.6f} " f"({kirtan['wer_percent']:.3f}%)" ) print( f"Kirtan CTC special/empty: " f"{kirtan['ctc_special_or_empty_outputs']}/" f"{kirtan['ctc_checked_outputs']}" ) print( f"Sehaj WER: {sehaj['wer']:.6f} " f"({sehaj['wer_percent']:.3f}%)" ) print( f"Sehaj CTC special/empty: " f"{sehaj['ctc_special_or_empty_outputs']}/" f"{sehaj['ctc_checked_outputs']}" ) print("✓ Safe to begin training") ############################################################################### # CLOUDFLARE R2 HELPERS ############################################################################### def get_r2_config(): """Read and validate Cloudflare R2 connection settings.""" account_id = os.environ.get("R2_ACCOUNT_ID") access_key_id = os.environ.get("R2_ACCESS_KEY_ID") secret_access_key = os.environ.get("R2_SECRET_ACCESS_KEY") bucket = os.environ.get("R2_BUCKET") missing = [ name for name, value in ( ("R2_ACCOUNT_ID", account_id), ("R2_ACCESS_KEY_ID", access_key_id), ("R2_SECRET_ACCESS_KEY", secret_access_key), ("R2_BUCKET", bucket), ) if not value ] if missing: raise RuntimeError( "R2 upload is enabled but these environment variables are " f"missing: {', '.join(missing)}" ) return { "account_id": account_id, "access_key_id": access_key_id, "secret_access_key": secret_access_key, "bucket": bucket, "endpoint_url": ( f"https://{account_id}.r2.cloudflarestorage.com" ), } def upload_best_checkpoint_to_r2(checkpoint_path: Path) -> None: """Upload the completed local best.ckpt to Cloudflare R2.""" if not R2_UPLOAD_ENABLED: return checkpoint_path = Path(checkpoint_path) if not checkpoint_path.is_file(): raise FileNotFoundError( f"Cannot upload missing checkpoint: {checkpoint_path}" ) try: import boto3 except ImportError as exc: raise RuntimeError( "R2 upload requires boto3. Install it with: pip install boto3" ) from exc config = get_r2_config() client = boto3.client( "s3", endpoint_url=config["endpoint_url"], aws_access_key_id=config["access_key_id"], aws_secret_access_key=config["secret_access_key"], region_name="auto", ) last_error = None for attempt in range(1, R2_UPLOAD_RETRIES + 1): try: print( f"Uploading best checkpoint to R2 " f"(attempt {attempt}/{R2_UPLOAD_RETRIES})..." ) client.upload_file( str(checkpoint_path), config["bucket"], R2_OBJECT_KEY, ) print( "✓ R2 upload complete: " f"r2://{config['bucket']}/{R2_OBJECT_KEY}" ) return except Exception as exc: last_error = exc print( f"R2 upload attempt {attempt} failed: {exc}" ) if attempt < R2_UPLOAD_RETRIES: time.sleep(R2_RETRY_DELAY_SECONDS) raise RuntimeError( "best.ckpt was saved locally, but R2 upload failed after " f"{R2_UPLOAD_RETRIES} attempts." ) from last_error ############################################################################### # VAST.AI AUTO-DESTROY HELPERS ############################################################################### def get_vast_instance_id(): """ Return the current Vast instance ID. Vast may expose CONTAINER_ID directly. Older/current environments may instead expose VAST_CONTAINERLABEL in the form C.123456. """ container_id = os.environ.get("CONTAINER_ID") if container_id: value = str(container_id).strip() if value.isdigit(): return value label = os.environ.get("VAST_CONTAINERLABEL") if label: value = str(label).strip() if value.startswith("C."): value = value[2:] if value.isdigit(): return value return None def validate_vast_auto_destroy_config(test_mode: bool) -> None: """ Fail before a FULL training run if auto-destroy cannot be attempted. Test mode deliberately skips this because --test never destroys. """ if test_mode or not AUTO_DESTROY_VAST: return if shutil.which("vastai") is None: raise RuntimeError( "AUTO_DESTROY_VAST is enabled, but the Vast CLI is not installed. " "Install it before the full run with: pip install vastai" ) instance_id = get_vast_instance_id() if instance_id is None: raise RuntimeError( "AUTO_DESTROY_VAST is enabled, but the current Vast instance ID " "could not be determined from CONTAINER_ID or VAST_CONTAINERLABEL." ) def destroy_current_vast_instance() -> None: """ Permanently destroy this Vast instance. This is intentionally called only at the very end of a successful FULL run and only after best.ckpt has already been uploaded successfully to R2. """ if not AUTO_DESTROY_VAST: print("\nVast auto-destroy is disabled.") return instance_id = get_vast_instance_id() if instance_id is None: raise RuntimeError( "Cannot auto-destroy Vast instance: instance ID is unavailable." ) command = [ "vastai", "destroy", "instance", instance_id, "-y", # non-interactive confirmation ] # Vast images may expose a per-instance API key. If it is present, # pass it explicitly. Otherwise the Vast CLI uses its configured key. container_api_key = os.environ.get("CONTAINER_API_KEY") if container_api_key: command.extend( [ "--api-key", container_api_key, ] ) print( "\n======================================" ) print( "AUTO-DESTROYING VAST INSTANCE" ) print( "======================================" ) print( f"Instance ID: {instance_id}" ) print( "best.ckpt has already been uploaded successfully to R2." ) print( "This instance and its local files will now be permanently destroyed." ) # Make sure the final messages are visible before the container disappears. import sys sys.stdout.flush() sys.stderr.flush() try: result = subprocess.run( command, check=False, text=True, capture_output=True, timeout=60, ) except Exception as exc: raise RuntimeError( f"Failed to execute Vast destroy command: {exc}" ) from exc if result.stdout: print(result.stdout.strip()) if result.returncode != 0: if result.stderr: print(result.stderr.strip()) raise RuntimeError( "Vast auto-destroy command failed. " "The instance was NOT intentionally destroyed by this script." ) print( f"✓ Vast destroy request accepted for instance {instance_id}" ) ############################################################################### # DURING-TRAINING CTC HEALTH PROBE ############################################################################### class CTCHealthProbe(Callback): """Run a fixed CTC probe and overwrite one last-known-good checkpoint.""" def __init__( self, manifest_path: Path, stable_checkpoint_path: Path, every_optimizer_steps: int = 500, save_every_optimizer_steps: int = 2000, sample_count: int = 4, ): super().__init__() self.manifest_path = Path(manifest_path) self.stable_checkpoint_path = Path(stable_checkpoint_path) self.every_optimizer_steps = int(every_optimizer_steps) self.save_every_optimizer_steps = int(save_every_optimizer_steps) self.sample_count = int(sample_count) self.probe_samples = None self.last_probed_global_step = -1 if self.every_optimizer_steps <= 0: raise ValueError("CTC probe interval must be > 0") if self.save_every_optimizer_steps <= 0: raise ValueError("Stable checkpoint interval must be > 0") if self.save_every_optimizer_steps % self.every_optimizer_steps != 0: raise ValueError( "Stable checkpoint interval must be a multiple of the CTC probe interval." ) if self.sample_count <= 0: raise ValueError("CTC probe sample_count must be > 0") def setup(self, trainer, pl_module, stage=None): samples = load_validation_manifest(self.manifest_path) if len(samples) < self.sample_count: raise RuntimeError( f"CTC probe requested {self.sample_count} samples but only " f"{len(samples)} are available." ) self.probe_samples = samples[:self.sample_count] print("\n======================================") print("CTC DURING-TRAINING PROBE ENABLED") print("======================================") print(f"Probe interval: every {self.every_optimizer_steps} optimizer steps") print( f"Stable checkpoint interval: every " f"{self.save_every_optimizer_steps} optimizer steps, after a healthy probe" ) print(f"Fixed probe samples: {self.sample_count}") print(f"Rolling stable checkpoint: {self.stable_checkpoint_path}") for i, sample in enumerate(self.probe_samples, 1): print(f" Probe {i}: {sample['audio_filepath']}") def _run_probe(self, trainer, pl_module, global_step: int): if not self.probe_samples: raise RuntimeError("CTC probe samples were not initialized.") if not hasattr(pl_module, "cur_decoder"): raise RuntimeError("CTC probe expected model.cur_decoder.") was_training = pl_module.training previous_decoder = getattr(pl_module, "cur_decoder", None) audio_paths = [s["audio_filepath"] for s in self.probe_samples] references = [s["text"] for s in self.probe_samples] pl_module.eval() pl_module.cur_decoder = VALIDATION_DECODER try: with torch.no_grad(): outputs = pl_module.transcribe( audio_paths, batch_size=len(audio_paths), return_hypotheses=False, verbose=False, language_id=LANGUAGE_CODE, ) hypotheses = select_primary_transcriptions( outputs, expected_count=len(audio_paths), ) normalized = [ " ".join(str(v).strip().split()) for v in hypotheses ] finally: pl_module.cur_decoder = previous_decoder if was_training: pl_module.train() else: pl_module.eval() special_values = {"", "", ""} special_count = sum(v in special_values for v in normalized) epoch_number = trainer.current_epoch + 1 print("\n======================================") print(f"EPOCH {epoch_number} - CTC PROBE @ OPTIMIZER STEP {global_step}") print("======================================") for i, (ref, hyp) in enumerate(zip(references, normalized), 1): print(f" [{i}] REF : {ref}") print(f" [{i}] PRED: {hyp}") print(f"CTC probe special/empty: {special_count}/{len(normalized)}") if normalized and special_count == len(normalized): raise RuntimeError( "CTC TRAINING COLLAPSE DETECTED at optimizer step " f"{global_step}: all {len(normalized)} fixed probe hypotheses " f"were //empty: {normalized}." ) print(f"CTC probe HEALTHY at optimizer step {global_step}") # Probe every 500 optimizer steps, but only write the rolling full # Lightning checkpoint every 2000 optimizer steps. A checkpoint is # written only after the probe at that exact step has passed. if global_step % self.save_every_optimizer_steps != 0: print( f"No checkpoint save at step {global_step}; next stable save is " f"on a multiple of {self.save_every_optimizer_steps} optimizer steps." ) return # Save to a temporary file first, then replace atomically so an # interrupted write does not destroy the previous known-good checkpoint. self.stable_checkpoint_path.parent.mkdir(parents=True, exist_ok=True) temp_path = self.stable_checkpoint_path.with_suffix( self.stable_checkpoint_path.suffix + ".tmp" ) trainer.save_checkpoint(str(temp_path)) os.replace(temp_path, self.stable_checkpoint_path) print( f"✓ Updated last stable checkpoint at optimizer step {global_step}: " f"{self.stable_checkpoint_path}" ) def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): global_step = int(trainer.global_step) if global_step <= 0: return if global_step % self.every_optimizer_steps != 0: return if global_step == self.last_probed_global_step: return self.last_probed_global_step = global_step self._run_probe(trainer, pl_module, global_step) ############################################################################### # POST-EPOCH KIRTAN + SEHAJ WER/CER + BEST CHECKPOINT + EARLY STOPPING ############################################################################### class DomainValidationAndEarlyStopping(Callback): """ After every TRAINING epoch: 1. Explicitly transcribe kirtan validation data. 2. Explicitly transcribe Sehaj Paath validation data. 3. Save BOTH WER and CER to epoch_metrics.json. 4. Use Kirtan CER as the PRIMARY best.ckpt metric. 5. Also accept a Sehaj WER improvement when Kirtan CER is within the configured tolerance of the currently selected best checkpoint. 6. Reset early-stopping patience for either kind of accepted improvement. """ def __init__( self, metrics_path: Path, best_checkpoint_path: Path, kirtan_manifest: Path, sehaj_manifest: Path, batch_size: int, patience: int = 3, min_delta: float = 0.0001, kirtan_cer_tolerance_for_sehaj: float = 0.005, ): super().__init__() self.metrics_path = Path(metrics_path) self.best_checkpoint_path = Path(best_checkpoint_path) self.kirtan_manifest = Path(kirtan_manifest) self.sehaj_manifest = Path(sehaj_manifest) self.batch_size = int(batch_size) self.patience = patience self.min_delta = min_delta self.kirtan_cer_tolerance_for_sehaj = float( kirtan_cer_tolerance_for_sehaj ) self.best_kirtan_cer = float("inf") self.best_kirtan_wer = float("inf") self.best_sehaj_wer = float("inf") self.best_epoch = None self.bad_epochs = 0 self.history = [] self.r2_best_uploaded = False def write_history(self): best_kirtan_cer = ( None if self.best_kirtan_cer == float("inf") else self.best_kirtan_cer ) best_kirtan_wer = ( None if self.best_kirtan_wer == float("inf") else self.best_kirtan_wer ) best_sehaj_wer = ( None if self.best_sehaj_wer == float("inf") else self.best_sehaj_wer ) data = { "selection_metric": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance", "best_epoch": self.best_epoch, "best_kirtan_cer": best_kirtan_cer, "best_kirtan_cer_percent": ( None if best_kirtan_cer is None else best_kirtan_cer * 100.0 ), "best_kirtan_wer": best_kirtan_wer, "best_kirtan_wer_percent": ( None if best_kirtan_wer is None else best_kirtan_wer * 100.0 ), "best_sehaj_wer": best_sehaj_wer, "best_sehaj_wer_percent": ( None if best_sehaj_wer is None else best_sehaj_wer * 100.0 ), "patience": self.patience, "min_metric_improvement": self.min_delta, "kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj, "kirtan_cer_tolerance_for_sehaj_percent_points": ( self.kirtan_cer_tolerance_for_sehaj * 100.0 ), "epochs_without_improvement": self.bad_epochs, "history": self.history, } self.metrics_path.parent.mkdir(parents=True, exist_ok=True) temp_path = self.metrics_path.with_suffix(self.metrics_path.suffix + ".tmp") with temp_path.open("w", encoding="utf-8") as handle: json.dump(data, handle, indent=2, ensure_ascii=False) temp_path.replace(self.metrics_path) def on_train_epoch_end(self, trainer, pl_module): epoch_number = trainer.current_epoch + 1 print("\n======================================") print("EXPLICIT DOMAIN VALIDATION") print("======================================") print("Scoring KIRTAN validation (CER is primary checkpoint metric)...") kirtan = score_validation_manifest( model=pl_module, manifest_path=self.kirtan_manifest, batch_size=self.batch_size, ) print("Scoring SEHAJ PAATH validation (WER secondary metric)...") sehaj = score_validation_manifest( model=pl_module, manifest_path=self.sehaj_manifest, batch_size=self.batch_size, ) previous_best_kirtan_cer = self.best_kirtan_cer previous_best_sehaj_wer = self.best_sehaj_wer # Selection rule: # 1. Kirtan CER is primary. Improvement >= min_delta always wins. # 2. Sehaj WER may also win when it improves >= min_delta and Kirtan CER # is no more than the configured tolerance worse than the selected best. primary_improved = ( kirtan["cer"] < previous_best_kirtan_cer - self.min_delta ) sehaj_improved = ( sehaj["wer"] < previous_best_sehaj_wer - self.min_delta ) kirtan_within_sehaj_tolerance = ( kirtan["cer"] <= previous_best_kirtan_cer + self.kirtan_cer_tolerance_for_sehaj ) sehaj_tiebreak_improved = ( sehaj_improved and kirtan_within_sehaj_tolerance ) improved = primary_improved or sehaj_tiebreak_improved if primary_improved: improvement_reason = "kirtan_cer_primary" elif sehaj_tiebreak_improved: improvement_reason = "sehaj_wer_with_kirtan_cer_tolerance" else: improvement_reason = None if improved: self.best_kirtan_cer = kirtan["cer"] self.best_kirtan_wer = kirtan["wer"] self.best_sehaj_wer = sehaj["wer"] self.best_epoch = epoch_number self.bad_epochs = 0 self.best_checkpoint_path.parent.mkdir(parents=True, exist_ok=True) pl_module.train() trainer.save_checkpoint(str(self.best_checkpoint_path)) upload_best_checkpoint_to_r2(self.best_checkpoint_path) if R2_UPLOAD_ENABLED: self.r2_best_uploaded = True else: print("R2 upload skipped: offline test mode.") if improvement_reason == "kirtan_cer_primary": print("\nNEW BEST — KIRTAN CER IMPROVED") else: print("\nNEW BEST — SEHAJ WER IMPROVED WITH KIRTAN CER WITHIN TOLERANCE") print( "Kirtan CER is within the allowed " f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} " "percentage-point tolerance." ) print(f"Epoch: {epoch_number}") print( f"Kirtan CER: {kirtan['cer']:.6f} " f"({kirtan['cer_percent']:.3f}%)" ) print( f"Kirtan WER: {kirtan['wer']:.6f} " f"({kirtan['wer_percent']:.3f}%)" ) print( f"Sehaj WER: {sehaj['wer']:.6f} " f"({sehaj['wer_percent']:.3f}%)" ) print(f"Selection reason: {improvement_reason}") print("Saved best checkpoint:") print(self.best_checkpoint_path) else: self.bad_epochs += 1 print("\nNo accepted validation improvement.") print( f"Current Kirtan CER: {kirtan['cer']:.6f} " f"({kirtan['cer_percent']:.3f}%)" ) print( f"Best Kirtan CER: {self.best_kirtan_cer:.6f} " f"({self.best_kirtan_cer * 100:.3f}%)" ) print( f"Current Kirtan WER: {kirtan['wer']:.6f} " f"({kirtan['wer_percent']:.3f}%)" ) print( f"Current Sehaj WER: {sehaj['wer']:.6f} " f"({sehaj['wer_percent']:.3f}%)" ) print( f"Best Sehaj WER for selected checkpoint: {self.best_sehaj_wer:.6f} " f"({self.best_sehaj_wer * 100:.3f}%)" ) print( f"Epochs without improvement: {self.bad_epochs}/{self.patience}" ) epoch_record = { "epoch": epoch_number, "kirtan": kirtan, "sehaj": sehaj, "selection_metric": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance", "improved": improved, "improvement_reason": improvement_reason, "primary_kirtan_cer_improved": primary_improved, "sehaj_tiebreak_improved": sehaj_tiebreak_improved, "sehaj_wer_improved": sehaj_improved, "kirtan_cer_within_sehaj_tolerance": kirtan_within_sehaj_tolerance, "kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj, "best_epoch": self.best_epoch, "best_kirtan_cer": self.best_kirtan_cer, "best_kirtan_cer_percent": self.best_kirtan_cer * 100.0, "best_kirtan_wer": self.best_kirtan_wer, "best_kirtan_wer_percent": self.best_kirtan_wer * 100.0, "best_sehaj_wer": self.best_sehaj_wer, "best_sehaj_wer_percent": self.best_sehaj_wer * 100.0, "epochs_without_improvement": self.bad_epochs, } self.history.append(epoch_record) self.write_history() print("\n--------------------------------------") print( f"Epoch {epoch_number} KIRTAN: " f"CER {kirtan['cer_percent']:.3f}% | " f"WER {kirtan['wer_percent']:.3f}%" ) print( f"Epoch {epoch_number} SEHAJ: " f"WER {sehaj['wer_percent']:.3f}% | " f"CER {sehaj['cer_percent']:.3f}%" ) print( "Checkpoint / early-stop rule: KIRTAN CER primary; " "SEHAJ WER can also win when it improves and Kirtan CER is within +" f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} percentage points " "of the selected best Kirtan CER" ) print(f"Metrics JSON: {self.metrics_path}") print("--------------------------------------") if self.bad_epochs >= self.patience: print("\n########################################") print("EARLY STOPPING: NO ACCEPTED KIRTAN/SEHAJ IMPROVEMENT") print("########################################") print( f"No accepted primary/secondary improvement for " f"{self.bad_epochs} epochs." ) print(f"Best epoch: {self.best_epoch}") print( f"Best Kirtan CER: {self.best_kirtan_cer:.6f} " f"({self.best_kirtan_cer * 100:.3f}%)" ) print( f"Best Kirtan WER at selected checkpoint: {self.best_kirtan_wer:.6f} " f"({self.best_kirtan_wer * 100:.3f}%)" ) trainer.should_stop = True ############################################################################### # POST-EPOCH: KEEP LAST TWO EPOCH CHECKPOINTS ############################################################################### class LastTwoEpochCheckpoints(Callback): """ Save one checkpoint after every completed training epoch. Keep only the latest two: epoch_004.ckpt epoch_005.ckpt When epoch 6 finishes: epoch_004.ckpt -> deleted epoch_005.ckpt -> kept epoch_006.ckpt -> saved best.ckpt is NOT deleted by this callback. """ def __init__( self, dirpath: Path, ): super().__init__() self.dirpath = Path( dirpath ) def on_train_epoch_end( self, trainer, pl_module, ): self.dirpath.mkdir( parents=True, exist_ok=True, ) epoch_number = ( trainer.current_epoch + 1 ) checkpoint_path = ( self.dirpath / f"epoch_{epoch_number:03d}.ckpt" ) trainer.save_checkpoint( str(checkpoint_path) ) print( "\nSaved epoch checkpoint:" ) print( checkpoint_path ) # Only look at epoch_XXX.ckpt files. # best.ckpt will therefore never be removed. checkpoints = sorted( self.dirpath.glob( "epoch_*.ckpt" ) ) while len(checkpoints) > 2: oldest_checkpoint = ( checkpoints.pop(0) ) try: oldest_checkpoint.unlink() print( "Removed old epoch checkpoint:" ) print( oldest_checkpoint ) except FileNotFoundError: pass ############################################################################### # DATASET CONFIGURATION ############################################################################### def make_dataset_config( manifest_path: Path, shuffle: bool, ): """ Build a fresh NeMo dataset configuration for Punjabi ('pa') fine-tuning of the multilingual Gurbani model. Fresh train_ds and validation_ds configs are created here at fine-tuning time. The manifests provide lang='pa' and NeMo is asked to return the language ID so the multilingual model uses the Punjabi path. """ return OmegaConf.create({ "manifest_filepath": [ str(manifest_path) ], "sample_rate": EXPECTED_SAMPLE_RATE, "batch_size": BATCH_SIZE, "shuffle": shuffle, "num_workers": 2, "pin_memory": False, "persistent_workers": False, "max_duration": None, "min_duration": 0.0, "is_tarred": False, "tarred_audio_filepaths": None, "use_start_end_token": False, # IMPORTANT: this is a multilingual model. The manifests contain # lang="pa", and the dataset must return the language ID. "return_language_id": True, }) ############################################################################### # PATH VALIDATION ############################################################################### def validate_paths() -> None: if not DATA_ROOT.exists(): raise FileNotFoundError( f"DATA_ROOT does not exist: " f"{DATA_ROOT}" ) if not DATA_ROOT.is_dir(): raise ValueError( f"DATA_ROOT is not a directory: " f"{DATA_ROOT}" ) if not TRAIN_MANIFEST.exists(): raise FileNotFoundError( "Training manifest not found: " f"{TRAIN_MANIFEST}" ) if not KIRTAN_VAL_MANIFEST.exists(): raise FileNotFoundError( "Kirtan validation manifest not found: " f"{KIRTAN_VAL_MANIFEST}" ) if not SEHAJ_VAL_MANIFEST.exists(): raise FileNotFoundError( "Sehaj validation manifest not found: " f"{SEHAJ_VAL_MANIFEST}" ) if not MODEL_PATH.exists(): raise FileNotFoundError( "NeMo model not found: " f"{MODEL_PATH}" ) if ( START_CHECKPOINT_PATH is not None and not START_CHECKPOINT_PATH.exists() ): raise FileNotFoundError( "Starting checkpoint not found: " f"{START_CHECKPOINT_PATH}" ) if R2_UPLOAD_ENABLED: # Validate required R2 environment variables before long training starts. get_r2_config() ############################################################################### # LOAD STAGE-2 BEST CHECKPOINT WEIGHTS ONLY ############################################################################### def load_start_checkpoint_weights(model) -> None: """Optionally load checkpoint model weights without optimizer state.""" if START_CHECKPOINT_PATH is None: print( "\nNo starting checkpoint configured. " "Using MODEL_PATH weights directly." ) return print("\n======================================") print("LOADING OPTIONAL START CHECKPOINT WEIGHTS") print("======================================") print(START_CHECKPOINT_PATH) checkpoint = torch.load( str(START_CHECKPOINT_PATH), map_location="cpu", ) state_dict = checkpoint.get( "state_dict", checkpoint, ) result = model.load_state_dict( state_dict, strict=False, ) missing = list(result.missing_keys) unexpected = list(result.unexpected_keys) print(f"Missing keys: {len(missing)}") print(f"Unexpected keys: {len(unexpected)}") if missing: for key in missing[:30]: print(" MISSING:", key) if unexpected: for key in unexpected[:30]: print(" UNEXPECTED:", key) if missing or unexpected: raise RuntimeError( "Starting checkpoint does not cleanly match " "the restored .nemo model." ) print("✓ Starting checkpoint weights loaded cleanly") print("✓ Old optimizer state NOT restored") print("✓ Old scheduler state NOT restored") ############################################################################### # MODEL INFORMATION ############################################################################### def print_model_information( model, ) -> None: total_parameters = sum( parameter.numel() for parameter in model.parameters() ) trainable_parameters = sum( parameter.numel() for parameter in model.parameters() if parameter.requires_grad ) frozen_parameters = ( total_parameters - trainable_parameters ) print( "\n======================================" ) print( "MODEL INFORMATION" ) print( "======================================" ) print( f"Total parameters: " f"{total_parameters:,}" ) print( f"Trainable parameters: " f"{trainable_parameters:,}" ) print( f"Frozen parameters: " f"{frozen_parameters:,}" ) print( "======================================" ) ############################################################################### # COMMAND LINE ############################################################################### def parse_args(): parser = argparse.ArgumentParser( description="Fine-tune the Gurbani/Punjabi NeMo ASR model." ) parser.add_argument( "--test", action="store_true", help=( "Use the small *-test.json manifests for an infrastructure " "test run. Test artifacts are written under " "/workspace/asr_training_test." ), ) parser.add_argument( "--offline", action="store_true", help=( "TEST MODE ONLY: disable all Cloudflare R2 validation/uploads. " "Use as: python train.py --test --offline" ), ) args = parser.parse_args() if args.offline and not args.test: parser.error("--offline is only allowed together with --test") return args ############################################################################### # MAIN ############################################################################### def main() -> None: args = parse_args() configure_manifests(test_mode=args.test) configure_outputs( test_mode=args.test, offline=args.offline, ) # Test mode runs only 2 epochs. max_epochs = 2 if args.test else MAX_EPOCHS if args.test and args.offline: run_mode = "TEST OFFLINE (*-test.json manifests, 2 epochs, NO R2)" elif args.test: run_mode = "TEST (*-test.json manifests, 2 epochs, separate R2 test checkpoint)" else: run_mode = "FULL" print( "\nRUN MODE:", run_mode, ) validate_vast_auto_destroy_config( test_mode=args.test ) validate_paths() if not torch.cuda.is_available(): raise RuntimeError( "CUDA GPU is not available. This script is configured for Vast GPU training." ) print("\nGPU:", torch.cuda.get_device_name(0)) print("CUDA version:", torch.version.cuda) # Create all output directories under /workspace. OUTPUT_ROOT.mkdir( parents=True, exist_ok=True, ) CHECKPOINT_DIR.mkdir( parents=True, exist_ok=True, ) print( "======================================" ) print( "GURBANI PUNJABI (pa) MULTILINGUAL FINE-TUNING" ) print( "======================================" ) print( f"Training manifest:" ) print( TRAIN_MANIFEST ) print( f"\nKirtan validation manifest:" ) print( KIRTAN_VAL_MANIFEST ) print( f"\nSehaj validation manifest:" ) print( SEHAJ_VAL_MANIFEST ) print( f"\nBase model:" ) print( MODEL_PATH ) print( f"\nStarting checkpoint:" ) print( START_CHECKPOINT_PATH if START_CHECKPOINT_PATH is not None else "None — using MODEL_PATH only" ) print( f"\nOutput model:" ) print( OUTPUT_MODEL ) print( f"\nEpoch metrics JSON:" ) print( EPOCH_METRICS_PATH ) print( f"\nOutput root:" ) print( OUTPUT_ROOT ) print( f"\nCheckpoint directory:" ) print( CHECKPOINT_DIR ) if R2_UPLOAD_ENABLED: r2_config = get_r2_config() print( f"\nR2 best-checkpoint backup: " f"r2://{r2_config['bucket']}/{R2_OBJECT_KEY}" ) else: print( "\nR2 backup: DISABLED (--test --offline)" ) print( "\nLoading Gurbani/Punjabi multilingual model..." ) model = ( nemo_asr.models.ASRModel.restore_from( restore_path=str( MODEL_PATH ) ) ) # Overlay the best Stage-2 learned weights only. load_start_checkpoint_weights( model ) # -------------------------------------------------------- # Verify that the restored multilingual model supports Punjabi ('pa'). # Keep the original multilingual vocabulary and language masks intact. # -------------------------------------------------------- tokenizer_vocab_size = getattr( model.tokenizer, "vocab_size", None, ) print( "\nLoaded tokenizer vocabulary:", tokenizer_vocab_size, ) if tokenizer_vocab_size is None: raise RuntimeError( "Could not determine tokenizer vocabulary size." ) tokenizer_langs = getattr( model.tokenizer, "langs", None, ) print( "Tokenizer languages:", tokenizer_langs, ) if tokenizer_langs is None or LANGUAGE_CODE not in tokenizer_langs: raise RuntimeError( f"Restored multilingual tokenizer does not contain " f"Punjabi ({LANGUAGE_CODE!r})." ) rnnt_vocab_size = getattr( model.decoder, "vocab_size", None, ) print( "RNNT decoder vocabulary:", rnnt_vocab_size, ) if rnnt_vocab_size is None: raise RuntimeError( "Could not determine RNNT decoder vocabulary size." ) if hasattr(model, "ctc_decoder"): ctc_vocab_size = len( getattr( model.ctc_decoder, "vocabulary", [], ) ) print( "CTC decoder vocabulary:", ctc_vocab_size, ) language_masks = getattr( model.ctc_decoder, "language_masks", None, ) print( "CTC language masks present:", language_masks is not None, ) print( f"✓ Multilingual model with Punjabi ({LANGUAGE_CODE!r}) support verified" ) print_model_information( model ) print( "\nCreating fresh Punjabi (pa) training " "and validation dataset configs..." ) train_cfg = make_dataset_config( manifest_path=TRAIN_MANIFEST, shuffle=True, ) # Validation is performed explicitly by DomainValidationAndEarlyStopping # at on_train_epoch_end(). # # IMPORTANT: # NeMo's model.transcribe() still reads model.cfg.validation_ds internally # (for fields such as use_start_end_token), so validation_ds must NOT be None. # We keep a valid Kirtan validation config here, but Lightning's built-in # validation loop remains disabled with limit_val_batches=0 below. validation_cfg = make_dataset_config( manifest_path=KIRTAN_VAL_MANIFEST, shuffle=False, ) OmegaConf.set_struct( train_cfg, False, ) OmegaConf.set_struct( validation_cfg, False, ) with open_dict( model.cfg ): model.cfg.train_ds = train_cfg model.cfg.validation_ds = validation_cfg model.cfg.test_ds = None # Keep the conservative fine-tuning LR. model.cfg.optim.lr = ( LEARNING_RATE ) print( "\nTraining dataset config:" ) print( OmegaConf.to_yaml( model.cfg.train_ds ) ) print( "\nValidation mode: explicit post-epoch transcription " "(Lightning validation disabled)" ) print( f"Kirtan validation: {KIRTAN_VAL_MANIFEST}" ) print( f"Sehaj validation: {SEHAJ_VAL_MANIFEST}" ) domain_validation_callback = ( DomainValidationAndEarlyStopping( metrics_path=( EPOCH_METRICS_PATH ), best_checkpoint_path=( BEST_CHECKPOINT_PATH ), kirtan_manifest=( KIRTAN_VAL_MANIFEST ), sehaj_manifest=( SEHAJ_VAL_MANIFEST ), batch_size=( BATCH_SIZE ), patience=( EARLY_STOP_PATIENCE ), min_delta=( MIN_WER_IMPROVEMENT ), kirtan_cer_tolerance_for_sehaj=( KIRTAN_CER_TOLERANCE_FOR_SEHAJ ), ) ) checkpoint_callback = ( LastTwoEpochCheckpoints( dirpath=( CHECKPOINT_DIR ) ) ) print( "\nTraining configuration:" ) print( f"Batch size: " f"{BATCH_SIZE}" ) print( f"Gradient accumulation: " f"{ACCUMULATE_GRAD_BATCHES}" ) print( f"Effective batch size: " f"{BATCH_SIZE * ACCUMULATE_GRAD_BATCHES}" ) print( f"Learning rate: " f"{LEARNING_RATE}" ) print( f"Maximum epochs: " f"{max_epochs}" ) print( f"Early-stop patience: " f"{EARLY_STOP_PATIENCE}" ) print( f"Minimum WER improvement: " f"{MIN_WER_IMPROVEMENT}" ) ctc_probe_callback = CTCHealthProbe( manifest_path=KIRTAN_VAL_MANIFEST, stable_checkpoint_path=LAST_STABLE_CHECKPOINT_PATH, every_optimizer_steps=CTC_PROBE_EVERY_OPTIMIZER_STEPS, save_every_optimizer_steps=CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS, sample_count=CTC_PROBE_SAMPLE_COUNT, ) trainer = pl.Trainer( accelerator="gpu", devices=1, max_epochs=max_epochs, precision=16, accumulate_grad_batches=ACCUMULATE_GRAD_BATCHES, log_every_n_steps=100, # IMPORTANT: # Validation is done explicitly in the domain callback after each # training epoch. Disable Lightning's built-in validation loop so # kirtan is not evaluated twice. limit_val_batches=0, # Keep Lightning logs under the Vast workspace too. default_root_dir=str(OUTPUT_ROOT / "lightning"), # Checkpoints are managed manually by the callbacks below. enable_checkpointing=False, callbacks=[ EpochProgressBar(), EpochTimer(), ctc_probe_callback, domain_validation_callback, checkpoint_callback, ], ) model.set_trainer( trainer ) print( "\nSetting up training dataset..." ) model.setup_training_data( model.cfg.train_ds ) # Critical safety gate: verify CTC BEFORE the first optimizer step. # If this raises, trainer.fit() is never entered. run_pretrain_ctc_health_check( model=model, batch_size=BATCH_SIZE, ) print( "\n======================================" ) print( "STARTING GURBANI PUNJABI (pa) FINE-TUNING" ) print( "======================================" ) try: trainer.fit( model, ckpt_path=( str(START_CHECKPOINT_PATH) if START_CHECKPOINT_PATH is not None else None ), ) except Exception: print("\n======================================") print("TRAINING STOPPED / FAILED") print("======================================") print("Last CTC-verified stable checkpoint:") print(LAST_STABLE_CHECKPOINT_PATH) print("\nRestart with the same train.py.") print("It will resume model + optimizer + scheduler state from last_stable.ckpt.") raise print( "\n======================================" ) print( "TRAINING FINISHED" ) print( "======================================" ) print("Last CTC-verified stable checkpoint:") print(LAST_STABLE_CHECKPOINT_PATH) print("This same train.py resumes full Lightning state from that checkpoint.") if ( domain_validation_callback.best_epoch is not None ): print( f"Best epoch: " f"{domain_validation_callback.best_epoch}" ) print( f"Best Kirtan validation WER: " f"{domain_validation_callback.best_kirtan_wer:.6f} " f"({domain_validation_callback.best_kirtan_wer * 100:.3f}%)" ) print( f"Best checkpoint Sehaj validation WER: " f"{domain_validation_callback.best_sehaj_wer:.6f} " f"({domain_validation_callback.best_sehaj_wer * 100:.3f}%)" ) print( f"Best checkpoint: " f"{BEST_CHECKPOINT_PATH}" ) print( "\nLast two epoch checkpoints:" ) last_checkpoints = sorted( CHECKPOINT_DIR.glob( "epoch_*.ckpt" ) ) for checkpoint in last_checkpoints: print( f" {checkpoint}" ) print( "\nSaving final training-state " ".nemo model to:" ) print( OUTPUT_MODEL ) model.save_to( str( OUTPUT_MODEL ) ) print( "\n======================================" ) print( "COMPLETE" ) print( "======================================" ) print( f"Final model: " f"{OUTPUT_MODEL}" ) print( f"Best checkpoint: " f"{BEST_CHECKPOINT_PATH}" ) print( f"Epoch metrics: " f"{EPOCH_METRICS_PATH}" ) # Never destroy during infrastructure testing. if args.test: if args.offline: print( "\nTEST OFFLINE MODE: no R2 upload was attempted." ) print( "TEST MODE: Vast instance will NOT be destroyed." ) elif not AUTO_DESTROY_VAST: print( "\nAUTO_DESTROY_VAST is disabled; instance will remain running." ) elif domain_validation_callback.best_epoch is None: print( "\nVast instance NOT destroyed: no best checkpoint was produced." ) elif not domain_validation_callback.r2_best_uploaded: print( "\nVast instance NOT destroyed: best.ckpt was not confirmed " "uploaded to R2." ) else: destroy_current_vast_instance() ############################################################################### # ENTRY POINT ############################################################################### if __name__ == "__main__": main()