Download train-stream-sehaj.py from baniguru/training_scripts: direct link, hf CLI and curl.
- Browser
- Download file 78.1 kB
-
https://huggingface.co/datasets/baniguru/training_scripts/resolve/main/train-stream-sehaj.py
- Command line
-
hf download hf://datasets/baniguru/training_scripts/train-stream-sehaj.py
-
curl -L -o train-stream-sehaj.py https://huggingface.co/datasets/baniguru/training_scripts/resolve/main/train-stream-sehaj.py
78.1 kB
#!/usr/bin/env python3
# Version: initializes model weights from the [202,100] best checkpoint and
# fine-tunes using NeMo-valid [72,23] attention context (2.88 s left, 920 ms right).
import argparse
import copy
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
import torch
import pytorch_lightning as pl
from hydra.utils import instantiate
from omegaconf import OmegaConf, open_dict
from pytorch_lightning.callbacks import Callback, TQDMProgressBar
import nemo.collections.asr as nemo_asr
###############################################################################
# DATASET CONFIGURATION
###############################################################################
# The script lives in /workspace and manifests live in /workspace/training_data.
DATA_ROOT = Path(__file__).resolve().parent
# Manifest paths are selected at startup. Sehaj Paath is the only validation set.
# Normal: training_manifest.json
# --test: training_manifest_test.json (validation remains full Sehaj Paath)
# Audio paths inside the manifests are used exactly as written.
TRAIN_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 SEHAJ_VAL_MANIFEST
if test_mode:
TRAIN_MANIFEST = DATA_ROOT / "training_data/sehaj/training_manifest_test.json"
else:
TRAIN_MANIFEST = DATA_ROOT / "training_data/sehaj/training_manifest.json"
# Always score the real/full validation sets, including --test.
SEHAJ_VAL_MANIFEST = DATA_ROOT / "training_data/sehaj/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 exported model for its architecture/tokenizer, then initialize its
# model weights from the previous [202,100] run's best.ckpt. The encoder is
# rebuilt for the new [72,23] training context before training.
MODEL_PATH = Path(
"/workspace/resume_checkpoint/baniguru_kirtan_stream_v2_224_27.nemo"
).expanduser().resolve()
SOURCE_MODEL_ATT_CONTEXT = [224, 27]
# The first [72,23] run initializes model weights from the previous run's best
# checkpoint (fresh optimizer/scheduler). Subsequent restarts restore the full
# Lightning state from this new context's own rolling checkpoint.
START_CHECKPOINT_PATH = Path(
"/workspace/asr_stream_training_202_100/checkpoints/best.ckpt"
).expanduser().resolve()
# Rolling full-Lightning checkpoint produced by THIS NEW [72,23] run.
LAST_STABLE_CHECKPOINT_PATH = Path(
"/workspace/resume_checkpoint/stream_72_23_last_stable.ckpt"
).expanduser().resolve()
###############################################################################
# CACHE-AWARE / STREAMING ENCODER CONFIGURATION
# Context Look-ahead Chunk
# [112,27] 1080 ms 1120 ms
# [224,27] 520 ms 560 ms
# [112,6] 240 ms 280 ms
# [112,3] 120 ms 160 ms
# [112,1] 40 ms 80 ms
# [112,0] 0 ms 40 ms
# Exported MODEL_PATH context: [224,27] (224x40ms left, 27x40ms right).
# Training context: [72,23] = 72x40ms left (2.88s), 23x40ms right (920ms).
# NeMo requires left_context % (right_context + 1) == 0; 72 % 24 == 0.
###############################################################################
STREAM_ATT_CONTEXTS = [[72, 23]]
# Train the complete manifest using 2.88 s left context and 920 ms right context.
CAUSAL_CONV_CONTEXT = [30, 0]
###############################################################################
# TRAINING CONFIGURATION
###############################################################################
BATCH_SIZE = 8
# Conservative full-model fine-tuning rate for the [72,23] 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 = 20
EARLY_STOP_WARMUP_EPOCHS = 0
# Sehaj CER or WER must improve by at least this much to count as a gain.
#
# Example:
# old WER = 0.1000
# new WER = 0.09995
#
# Difference = 0.00005
#
# The same minimum decrease applies independently to Sehaj CER and WER.
MIN_METRIC_IMPROVEMENT = 0.0001
###############################################################################
# CLOUDFLARE R2 BACKUP CONFIGURATION
###############################################################################
# Upload ONLY best.ckpt when Sehaj Paath CER or WER 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/stream-72_23-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_stream_training_72_23"
).expanduser().resolve()
# Final .nemo model saved when training finishes / early-stops.
OUTPUT_MODEL = (
OUTPUT_ROOT
/ "baniguru_kirtan_stream_72_23.nemo"
)
# Best checkpoint + last two epoch checkpoints.
CHECKPOINT_DIR = (
OUTPUT_ROOT / "checkpoints"
)
BEST_CHECKPOINT_PATH = (
CHECKPOINT_DIR / "best.ckpt"
)
# Per-epoch Sehaj Paath validation metrics (CER and WER).
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_stream_training_72_23_test").expanduser().resolve()
OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_stream_72_23.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-72_23-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 gpu_safe_transcribe(
model,
audio_paths,
batch_size: int,
verbose: bool,
):
"""
Explicit transcription helper.
The model is moved to CUDA before the pre-train health check. The patched
AI4Bharat hybrid _transcribe_forward() moves file-dataloader audio tensors
onto the same model device before forward(), so no runtime monkey-patching
is needed here.
"""
return model.transcribe(
audio_paths,
batch_size=batch_size,
return_hypotheses=False,
verbose=verbose,
language_id=LANGUAGE_CODE,
)
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 stays on its existing device (normally CUDA) and its training/eval
state and previous decoder are restored even if validation raises.
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
special_or_empty_outputs = 0
checked_outputs = 0
was_training = model.training
previous_decoder = getattr(model, "cur_decoder", None)
model.eval()
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 = gpu_safe_transcribe(
model=model,
audio_paths=audio_paths,
batch_size=batch_size,
verbose=True,
)
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 {"<unk>", "<blank>", ""}
for value in normalized_batch
)
if start == 0:
print("\nVALIDATION DEBUG")
print(f"Manifest: {manifest_path}")
print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}")
print(f"Device: {next(model.parameters()).device}")
print(f"Outputs type: {type(outputs)}")
if normalized_batch and all(
value in {"<unk>", "<blank>", ""}
for value in normalized_batch
):
raise RuntimeError(
"Validation decoder returned only special/empty "
f"tokens for {manifest_path}: "
f"{normalized_batch[: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)
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:
model.cur_decoder = previous_decoder
if was_training:
model.train()
else:
model.eval()
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"<unk>/<blank>/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 model decodes the full Sehaj Paath
validation manifest through the same CTC path used after every epoch.
"""
print("\n======================================")
print("PRE-TRAIN CTC HEALTH CHECK")
print("======================================")
print("No training has happened yet.")
print("Sehaj Paath must decode successfully before trainer.fit().")
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"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 = [
sample["audio_filepath"]
for sample in self.probe_samples
]
references = [
sample["text"]
for sample in self.probe_samples
]
# Keep the training model on CUDA. gpu_safe_transcribe() moves only
# transcription-batch tensors to the model device before NeMo forward.
pl_module.eval()
pl_module.cur_decoder = VALIDATION_DECODER
try:
with torch.no_grad():
outputs = gpu_safe_transcribe(
model=pl_module,
audio_paths=audio_paths,
batch_size=len(audio_paths),
verbose=False,
)
hypotheses = select_primary_transcriptions(
outputs,
expected_count=len(audio_paths),
)
normalized = [
" ".join(str(value).strip().split())
for value in hypotheses
]
finally:
pl_module.cur_decoder = previous_decoder
if was_training:
pl_module.train()
else:
pl_module.eval()
special_values = {"<unk>", "<blank>", ""}
special_count = sum(
value in special_values
for value in normalized
)
epoch_number = trainer.current_epoch + 1
print("\n======================================")
print(
f"EPOCH {epoch_number} - "
f"CTC PROBE @ OPTIMIZER STEP {global_step}"
)
print("======================================")
print(f"CTC probe device: {next(pl_module.parameters()).device}")
for i, (reference, hypothesis) in enumerate(
zip(references, normalized),
1,
):
print(f" [{i}] REF : {reference}")
print(f" [{i}] PRED: {hypothesis}")
print(
f"CTC probe special/empty: "
f"{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 "
f"hypotheses were <unk>/<blank>/empty: {normalized}."
)
print(
f"CTC probe HEALTHY at optimizer step {global_step}"
)
if global_step % self.save_every_optimizer_steps != 0:
print(
f"No checkpoint save at step {global_step}; "
f"next stable save is on a multiple of "
f"{self.save_every_optimizer_steps} optimizer steps."
)
return
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 "
f"{global_step}: {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 SEHAJ WER/CER + BEST CHECKPOINT + EARLY STOPPING
###############################################################################
class DomainValidationAndEarlyStopping(Callback):
"""Validate Sehaj Paath only; keep best.ckpt on Sehaj CER or WER gains."""
def __init__(
self,
metrics_path: Path,
best_checkpoint_path: Path,
sehaj_manifest: Path,
batch_size: int,
patience: int = 5,
min_delta: float = 0.0001,
):
super().__init__()
self.metrics_path = Path(metrics_path)
self.best_checkpoint_path = Path(best_checkpoint_path)
self.sehaj_manifest = Path(sehaj_manifest)
self.batch_size = int(batch_size)
self.patience = int(patience)
self.min_delta = float(min_delta)
self.best_sehaj_cer = float("inf")
self.best_sehaj_wer = float("inf")
self.selected_sehaj_cer = float("inf")
self.selected_sehaj_wer = float("inf")
self.best_epoch = None
self.bad_epochs = 0
self.history = []
self.r2_best_uploaded = False
self._seed_from_existing_metrics_json()
@staticmethod
def _finite_or_inf(value):
if value is None:
return float("inf")
try:
return float(value)
except (TypeError, ValueError):
return float("inf")
def _seed_from_existing_metrics_json(self):
if not self.metrics_path.is_file():
return
try:
with self.metrics_path.open("r", encoding="utf-8") as handle:
data = json.load(handle)
except Exception as exc:
print(f"WARNING: could not seed validation history from {self.metrics_path}: {exc}")
return
history = data.get("history")
self.history = history if isinstance(history, list) else []
sehaj_cers = []
sehaj_wers = []
for record in self.history:
try:
sehaj = record.get("sehaj", {})
if sehaj.get("cer") is not None:
sehaj_cers.append(float(sehaj["cer"]))
if sehaj.get("wer") is not None:
sehaj_wers.append(float(sehaj["wer"]))
except (TypeError, ValueError, AttributeError):
continue
self.best_sehaj_cer = min(sehaj_cers) if sehaj_cers else self._finite_or_inf(
data.get("best_sehaj_cer")
)
self.best_sehaj_wer = min(sehaj_wers) if sehaj_wers else self._finite_or_inf(
data.get("best_sehaj_wer")
)
self.best_epoch = data.get("best_epoch")
self.bad_epochs = int(data.get("epochs_without_improvement", 0) or 0)
for record in reversed(self.history):
if record.get("epoch") == self.best_epoch:
sehaj = record.get("sehaj", {})
self.selected_sehaj_cer = self._finite_or_inf(sehaj.get("cer"))
self.selected_sehaj_wer = self._finite_or_inf(sehaj.get("wer"))
break
print("\nRestored Sehaj validation history from:", self.metrics_path)
print(f" best-ever Sehaj CER: {self.best_sehaj_cer}")
print(f" best-ever Sehaj WER: {self.best_sehaj_wer}")
print(f" selected best epoch: {self.best_epoch}")
print(f" epochs without improvement: {self.bad_epochs}")
def state_dict(self):
return {
"best_sehaj_cer": self.best_sehaj_cer,
"best_sehaj_wer": self.best_sehaj_wer,
"selected_sehaj_cer": self.selected_sehaj_cer,
"selected_sehaj_wer": self.selected_sehaj_wer,
"best_epoch": self.best_epoch,
"bad_epochs": self.bad_epochs,
"history": self.history,
"r2_best_uploaded": self.r2_best_uploaded,
}
def load_state_dict(self, state_dict):
if not state_dict:
return
# Keep JSON-seeded values when resuming a checkpoint written by an older
# callback version that did not yet store Sehaj CER.
self.best_sehaj_cer = self._finite_or_inf(
state_dict.get("best_sehaj_cer", self.best_sehaj_cer)
)
self.best_sehaj_wer = self._finite_or_inf(
state_dict.get("best_sehaj_wer", self.best_sehaj_wer)
)
self.selected_sehaj_cer = self._finite_or_inf(
state_dict.get("selected_sehaj_cer", self.selected_sehaj_cer)
)
self.selected_sehaj_wer = self._finite_or_inf(
state_dict.get("selected_sehaj_wer", self.selected_sehaj_wer)
)
self.best_epoch = state_dict.get("best_epoch", self.best_epoch)
self.bad_epochs = int(state_dict.get("bad_epochs", self.bad_epochs) or 0)
restored_history = state_dict.get("history")
if isinstance(restored_history, list):
self.history = restored_history
self.r2_best_uploaded = bool(
state_dict.get("r2_best_uploaded", self.r2_best_uploaded)
)
print("\n✓ Restored Sehaj-only validation callback state")
print(f" best-ever Sehaj CER: {self.best_sehaj_cer}")
print(f" best-ever Sehaj WER: {self.best_sehaj_wer}")
print(f" selected best epoch: {self.best_epoch}")
print(f" epochs without improvement: {self.bad_epochs}")
def write_history(self):
# Put the two headline percentages first inside each nested Sehaj result.
# Existing history entries are reordered as well when the JSON is saved.
for record in self.history:
if not isinstance(record, dict):
continue
sehaj = record.get("sehaj", {})
if not isinstance(sehaj, dict):
continue
sehaj = dict(sehaj)
if "wer_percent" not in sehaj and sehaj.get("wer") is not None:
sehaj["wer_percent"] = float(sehaj["wer"]) * 100.0
if "cer_percent" not in sehaj and sehaj.get("cer") is not None:
sehaj["cer_percent"] = float(sehaj["cer"]) * 100.0
ordered_sehaj = {
key: sehaj[key]
for key in ("wer_percent", "cer_percent")
if key in sehaj
}
ordered_sehaj.update(
(key, value)
for key, value in sehaj.items()
if key not in ("wer_percent", "cer_percent")
)
record["sehaj"] = ordered_sehaj
def optional(value):
return None if value == float("inf") else value
data = {
"selection_metric": "any_improvement_sehaj_cer_or_sehaj_wer",
"best_epoch": self.best_epoch,
"best_sehaj_cer": optional(self.best_sehaj_cer),
"best_sehaj_cer_percent": (
None if optional(self.best_sehaj_cer) is None
else self.best_sehaj_cer * 100.0
),
"best_sehaj_wer": optional(self.best_sehaj_wer),
"best_sehaj_wer_percent": (
None if optional(self.best_sehaj_wer) is None
else self.best_sehaj_wer * 100.0
),
"selected_checkpoint_sehaj_cer": optional(self.selected_sehaj_cer),
"selected_checkpoint_sehaj_wer": optional(self.selected_sehaj_wer),
"patience": self.patience,
"min_metric_improvement": self.min_delta,
"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("SEHAJ PAATH VALIDATION ONLY")
print("======================================")
sehaj = score_validation_manifest(
model=pl_module,
manifest_path=self.sehaj_manifest,
batch_size=self.batch_size,
)
sehaj_cer_improved = sehaj["cer"] < self.best_sehaj_cer - self.min_delta
sehaj_wer_improved = sehaj["wer"] < self.best_sehaj_wer - self.min_delta
improved = sehaj_cer_improved or sehaj_wer_improved
reasons = []
if sehaj_cer_improved:
reasons.append("sehaj_cer")
if sehaj_wer_improved:
reasons.append("sehaj_wer")
improvement_reason = "+".join(reasons) if reasons else None
if sehaj_cer_improved:
self.best_sehaj_cer = sehaj["cer"]
if sehaj_wer_improved:
self.best_sehaj_wer = sehaj["wer"]
if improved:
self.best_epoch = epoch_number
self.bad_epochs = 0
self.selected_sehaj_cer = sehaj["cer"]
self.selected_sehaj_wer = sehaj["wer"]
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)
self.r2_best_uploaded = bool(R2_UPLOAD_ENABLED)
if not R2_UPLOAD_ENABLED:
print("R2 upload skipped: offline test mode.")
print("\nNEW BEST CHECKPOINT — SEHAJ METRIC IMPROVEMENT")
print(f"Epoch: {epoch_number}")
print(f"Sehaj CER: {sehaj['cer']:.6f} ({sehaj['cer_percent']:.3f}%)")
print(f"Sehaj WER: {sehaj['wer']:.6f} ({sehaj['wer_percent']:.3f}%)")
print(f"Selection reason: {improvement_reason}")
print("Saved best checkpoint:", self.best_checkpoint_path)
else:
self.bad_epochs += 1
print("\nNo Sehaj CER or WER improvement.")
print(f"Current Sehaj CER: {sehaj['cer']:.6f} ({sehaj['cer_percent']:.3f}%)")
print(f"Best-ever Sehaj CER: {self.best_sehaj_cer:.6f} ({self.best_sehaj_cer * 100:.3f}%)")
print(f"Current Sehaj WER: {sehaj['wer']:.6f} ({sehaj['wer_percent']:.3f}%)")
print(f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} ({self.best_sehaj_wer * 100:.3f}%)")
print(f"Epochs without improvement: {self.bad_epochs}/{self.patience}")
epoch_record = {
"epoch": epoch_number,
"sehaj": sehaj,
"selection_metric": "any_improvement_sehaj_cer_or_sehaj_wer",
"improved": improved,
"improvement_reason": improvement_reason,
"sehaj_cer_improved": sehaj_cer_improved,
"sehaj_wer_improved": sehaj_wer_improved,
"best_epoch": self.best_epoch,
"best_sehaj_cer": self.best_sehaj_cer,
"best_sehaj_cer_percent": self.best_sehaj_cer * 100.0,
"best_sehaj_wer": self.best_sehaj_wer,
"best_sehaj_wer_percent": self.best_sehaj_wer * 100.0,
"selected_checkpoint_sehaj_cer": self.selected_sehaj_cer,
"selected_checkpoint_sehaj_wer": self.selected_sehaj_wer,
"epochs_without_improvement": self.bad_epochs,
}
self.history.append(epoch_record)
self.write_history()
print("\n--------------------------------------")
print(
f"Epoch {epoch_number} SEHAJ: CER {sehaj['cer_percent']:.3f}% | "
f"WER {sehaj['wer_percent']:.3f}%"
)
print("Checkpoint rule: promote when Sehaj CER OR Sehaj WER improves.")
print(f"Minimum required improvement: {self.min_delta}")
print(f"Metrics JSON: {self.metrics_path}")
print("--------------------------------------")
if self.bad_epochs >= self.patience:
print("\n########################################")
print("EARLY STOPPING: NO SEHAJ METRIC IMPROVEMENT")
print("########################################")
print(f"No Sehaj CER or WER improvement for {self.bad_epochs} epochs.")
print(f"Selected best epoch: {self.best_epoch}")
print(f"Best-ever Sehaj CER: {self.best_sehaj_cer:.6f} ({self.best_sehaj_cer * 100:.3f}%)")
print(f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} ({self.best_sehaj_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 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}"
)
# A brand-new [72,23] run initializes from START_CHECKPOINT_PATH. Later
# restarts resume from its own rolling stable checkpoint.
if not LAST_STABLE_CHECKPOINT_PATH.exists():
if (
START_CHECKPOINT_PATH is not None
and not START_CHECKPOINT_PATH.exists()
):
raise FileNotFoundError(
"Optional initialization 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")
###############################################################################
# CACHE-AWARE ENCODER CONVERSION
###############################################################################
def rebuild_encoder_cache_aware(model, attention_context) -> None:
"""
Rebuild the existing Conformer encoder for one cache-aware/chunked-limited
attention context while preserving all learned encoder weights.
This helper rebuilds the encoder for the requested cache-aware context
while preserving the learned encoder weights.
"""
attention_context = list(attention_context)
print("\n======================================")
print("CACHE-AWARE ENCODER CONVERSION")
print("======================================")
old_cfg = copy.deepcopy(model.cfg.encoder)
print("Original attention context:", old_cfg.get("att_context_size"))
print("Original attention probabilities:", old_cfg.get("att_context_probs", None))
print("Original attention style:", old_cfg.get("att_context_style", "regular"))
print("Original convolution context:", old_cfg.get("conv_context_size", None))
old_state = copy.deepcopy(model.encoder.state_dict())
new_cfg = copy.deepcopy(old_cfg)
with open_dict(new_cfg):
new_cfg.att_context_size = attention_context
new_cfg.att_context_probs = None
new_cfg.att_context_style = "chunked_limited"
new_cfg.conv_context_size = CAUSAL_CONV_CONTEXT
print("\nRebuilding encoder...")
print("Attention context:", attention_context)
print("Attention style: chunked_limited")
print("Convolution context:", CAUSAL_CONV_CONTEXT)
new_encoder = instantiate(new_cfg)
new_encoder.load_state_dict(old_state, strict=True)
model.encoder = new_encoder
with open_dict(model.cfg):
model.cfg.encoder = new_cfg
print("✓ Existing encoder weights loaded strict=True")
print(f"✓ Full-data streaming context: {attention_context}")
print("✓ Causal convolution: [30,0]")
print("======================================\n")
###############################################################################
# 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) STREAMING FINE-TUNING"
)
print(
"======================================"
)
print(
f"Training manifest:"
)
print(
TRAIN_MANIFEST
)
print("\nSehaj Paath 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
)
)
)
# Fail early if the architecture/tokenizer model is not the expected export.
# Its weights are initialized from best.ckpt before rebuilding to [72,23].
loaded_context = model.cfg.encoder.get("att_context_size", None)
if loaded_context is None:
raise RuntimeError(
"Starting model does not specify encoder.att_context_size; "
f"expected {SOURCE_MODEL_ATT_CONTEXT} from {MODEL_PATH}."
)
loaded_context = [int(value) for value in loaded_context]
print("Starting model attention context:", loaded_context)
if loaded_context != SOURCE_MODEL_ATT_CONTEXT:
raise RuntimeError(
"Wrong starting model context: "
f"expected {SOURCE_MODEL_ATT_CONTEXT}, got {loaded_context}. "
f"Model path: {MODEL_PATH}"
)
# Decide whether this is the first [72,23] run or a restart of that run.
resume_ckpt = (
LAST_STABLE_CHECKPOINT_PATH
if LAST_STABLE_CHECKPOINT_PATH.exists()
else None
)
if resume_ckpt is None:
print(
"\nNo [72,23] stable checkpoint exists. "
"This is the FIRST [72,23] run; initializing weights from the prior best.ckpt."
)
load_start_checkpoint_weights(model)
else:
print(
"\nFound [72,23] rolling stable checkpoint. "
"Lightning will restore the full [72,23] training state."
)
print(resume_ckpt)
# --------------------------------------------------------
# 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.
# Keep a valid Sehaj 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=SEHAJ_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"Sehaj Paath validation only: {SEHAJ_VAL_MANIFEST}")
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_METRIC_IMPROVEMENT}"
)
print(
f"Streaming attention context (full data): "
f"{STREAM_ATT_CONTEXTS}"
)
print(
f"Causal convolution context: "
f"{CAUSAL_CONV_CONTEXT}"
)
# ------------------------------------------------------------------
# Full-data streaming training
# ------------------------------------------------------------------
# Train the complete selected manifest using the configured [72,23]
# streaming attention context.
# ------------------------------------------------------------------
for stage_index, attention_context in enumerate(STREAM_ATT_CONTEXTS, start=1):
context_tag = f"{attention_context[0]}_{attention_context[1]}"
stage_root = OUTPUT_ROOT
stage_checkpoint_dir = stage_root / "checkpoints"
stage_best_checkpoint = stage_checkpoint_dir / "best.ckpt"
stage_metrics_path = stage_root / "epoch_metrics.json"
stage_stable_checkpoint = LAST_STABLE_CHECKPOINT_PATH
stage_root.mkdir(parents=True, exist_ok=True)
stage_checkpoint_dir.mkdir(parents=True, exist_ok=True)
print("\n############################################################")
print(
f"FULL-DATA STREAMING TRAINING - ATTENTION {attention_context}"
)
print("############################################################")
rebuild_encoder_cache_aware(
model,
attention_context=attention_context,
)
# Keep the dataset config unchanged, so this stage consumes the entire
# selected training manifest once per epoch.
model.setup_training_data(
model.cfg.train_ds
)
# The pre-train transcription health check runs before trainer.fit().
# Lightning has therefore not yet moved the model to the GPU. Move the
# full hybrid model explicitly so model parameters, preprocessor/STFT
# buffers, and the patched transcribe input tensors all use cuda:0.
model.to(torch.device("cuda:0"))
print(f"Pre-train health-check model device: {next(model.parameters()).device}")
# Verify CTC after changing the streaming attention context and before
# the first optimizer step of this stage.
run_pretrain_ctc_health_check(
model=model,
batch_size=BATCH_SIZE,
)
stage_domain_validation_callback = DomainValidationAndEarlyStopping(
metrics_path=stage_metrics_path,
best_checkpoint_path=stage_best_checkpoint,
sehaj_manifest=SEHAJ_VAL_MANIFEST,
batch_size=BATCH_SIZE,
patience=EARLY_STOP_PATIENCE,
min_delta=MIN_METRIC_IMPROVEMENT,
)
stage_checkpoint_callback = LastTwoEpochCheckpoints(
dirpath=stage_checkpoint_dir
)
stage_ctc_probe_callback = CTCHealthProbe(
manifest_path=SEHAJ_VAL_MANIFEST,
stable_checkpoint_path=stage_stable_checkpoint,
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,
limit_val_batches=0,
default_root_dir=str(stage_root / "lightning"),
enable_checkpointing=False,
callbacks=[
EpochProgressBar(),
EpochTimer(),
stage_ctc_probe_callback,
stage_domain_validation_callback,
stage_checkpoint_callback,
],
)
model.set_trainer(trainer)
print("\n======================================")
print(
f"STARTING FULL-DATA STREAM TRAINING "
f"FOR ATTENTION {attention_context}"
)
print("======================================")
if resume_ckpt is not None:
print(
"\nResuming FULL [72,23] Lightning state from: "
f"{resume_ckpt}"
)
else:
print(
"\nStarting fresh [72,23] training with model weights from: "
f"{START_CHECKPOINT_PATH}"
)
print("Optimizer/scheduler state: FRESH")
try:
trainer.fit(
model,
ckpt_path=str(resume_ckpt)
if resume_ckpt is not None
else None,
)
except Exception:
print("\n======================================")
print("STREAM TRAINING STOPPED / FAILED")
print("======================================")
print("Attention context:", attention_context)
print("Last CTC-verified stable checkpoint:")
print(stage_stable_checkpoint)
raise
print(
f"\n✓ Completed full-data streaming training: "
f"attention {attention_context}"
)
# Restore the best streaming weights before final export.
if stage_best_checkpoint.exists():
print("Loading best streaming checkpoint before continuing:")
print(stage_best_checkpoint)
checkpoint = torch.load(
str(stage_best_checkpoint),
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)
if missing or unexpected:
print("Missing keys:", missing[:30])
print("Unexpected keys:", unexpected[:30])
raise RuntimeError(
"Best streaming checkpoint did not cleanly reload."
)
print("✓ Best streaming weights restored")
print(
"\n======================================"
)
print(
"TRAINING FINISHED"
)
print(
"======================================"
)
print("Last CTC-verified stable checkpoint:")
print(LAST_STABLE_CHECKPOINT_PATH)
print("This checkpoint resumes the full [72,23] Lightning training state.")
if (
stage_domain_validation_callback.best_epoch
is not None
):
print(
f"Best epoch: "
f"{stage_domain_validation_callback.best_epoch}"
)
print(
f"Best Sehaj validation CER: "
f"{stage_domain_validation_callback.best_sehaj_cer:.6f} "
f"({stage_domain_validation_callback.best_sehaj_cer * 100:.3f}%)"
)
print(
f"Best Sehaj validation WER: "
f"{stage_domain_validation_callback.best_sehaj_wer:.6f} "
f"({stage_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 stage_domain_validation_callback.best_epoch is None:
print(
"\nVast instance NOT destroyed: no best checkpoint was produced."
)
elif not stage_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()
#!/usr/bin/env python3
# Version: initializes model weights from the [202,100] best checkpoint and
# fine-tunes using NeMo-valid [72,23] attention context (2.88 s left, 920 ms right).
import argparse
import copy
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
import torch
import pytorch_lightning as pl
from hydra.utils import instantiate
from omegaconf import OmegaConf, open_dict
from pytorch_lightning.callbacks import Callback, TQDMProgressBar
import nemo.collections.asr as nemo_asr
###############################################################################
# DATASET CONFIGURATION
###############################################################################
# The script lives in /workspace and manifests live in /workspace/training_data.
DATA_ROOT = Path(__file__).resolve().parent
# Manifest paths are selected at startup. Sehaj Paath is the only validation set.
# Normal: training_manifest.json
# --test: training_manifest_test.json (validation remains full Sehaj Paath)
# Audio paths inside the manifests are used exactly as written.
TRAIN_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 SEHAJ_VAL_MANIFEST
if test_mode:
TRAIN_MANIFEST = DATA_ROOT / "training_data/sehaj/training_manifest_test.json"
else:
TRAIN_MANIFEST = DATA_ROOT / "training_data/sehaj/training_manifest.json"
# Always score the real/full validation sets, including --test.
SEHAJ_VAL_MANIFEST = DATA_ROOT / "training_data/sehaj/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 exported model for its architecture/tokenizer, then initialize its
# model weights from the previous [202,100] run's best.ckpt. The encoder is
# rebuilt for the new [72,23] training context before training.
MODEL_PATH = Path(
"/workspace/resume_checkpoint/baniguru_kirtan_stream_v2_224_27.nemo"
).expanduser().resolve()
SOURCE_MODEL_ATT_CONTEXT = [224, 27]
# The first [72,23] run initializes model weights from the previous run's best
# checkpoint (fresh optimizer/scheduler). Subsequent restarts restore the full
# Lightning state from this new context's own rolling checkpoint.
START_CHECKPOINT_PATH = Path(
"/workspace/asr_stream_training_202_100/checkpoints/best.ckpt"
).expanduser().resolve()
# Rolling full-Lightning checkpoint produced by THIS NEW [72,23] run.
LAST_STABLE_CHECKPOINT_PATH = Path(
"/workspace/resume_checkpoint/stream_72_23_last_stable.ckpt"
).expanduser().resolve()
###############################################################################
# CACHE-AWARE / STREAMING ENCODER CONFIGURATION
# Context Look-ahead Chunk
# [112,27] 1080 ms 1120 ms
# [224,27] 520 ms 560 ms
# [112,6] 240 ms 280 ms
# [112,3] 120 ms 160 ms
# [112,1] 40 ms 80 ms
# [112,0] 0 ms 40 ms
# Exported MODEL_PATH context: [224,27] (224x40ms left, 27x40ms right).
# Training context: [72,23] = 72x40ms left (2.88s), 23x40ms right (920ms).
# NeMo requires left_context % (right_context + 1) == 0; 72 % 24 == 0.
###############################################################################