Murli-V1.5-Code / train.py
ViuAI's picture
Add 50k-step atomic Hugging Face checkpoint backup (murli_v15_step + best + final)
830eb8a verified
Raw History Blame Contribute Delete
16.6 kB
"""Train Murli V1.5 from scratch or resume a completed optimizer update."""
import argparse
import hashlib
import math
import os
import time
from collections import Counter
from dataclasses import asdict
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from config import EMOTION_TO_ID, MurliV15Config
from data.dataset import MurliV15Dataset, _map_emotion, v15_collate_fn
from data.text_cleaner import BilingualTextTokenizer
from models.tts_engine import MurliV15Engine
from models.vocoder import MurliVocoder
from narrate import render_with_model
from utils.checkpoint import atomic_save
TEST_SAMPLE_SCRIPT = (
"नमस्ते! आज राघव बढ़ई अपनी लकड़ी की मुरली लेकर मेहनत और सम्मान के साथ 12 साल बाद घर लौटा। "
"उसने 3.5 प्रतिशत मुनाफा कमाया।"
)
def generate_test_sample(model, cfg, step, vocoder_holder):
sample_path = Path(cfg.train.sample_dir) / f"sample_step_{step:06d}.wav"
if vocoder_holder.get("vocoder") is None:
vocoder_holder["vocoder"] = MurliVocoder()
vocoder_holder["tokenizer"] = BilingualTextTokenizer(use_g2p_en=False)
render_with_model(
model,
vocoder_holder["tokenizer"],
vocoder_holder["vocoder"],
cfg,
TEST_SAMPLE_SCRIPT,
sample_path,
emotion="neutral",
)
print(f"[Sample Saved] {sample_path}")
if cfg.train.hf_sample_repo:
try:
from huggingface_hub import HfApi
api = HfApi(token=os.getenv("HF_TOKEN"))
api.upload_file(
path_or_fileobj=str(sample_path),
path_in_repo=f"samples/{sample_path.name}",
repo_id=cfg.train.hf_sample_repo,
repo_type="model",
commit_message=f"Add Murli V1.5 test sample at step {step}",
)
print(f"[Sample Uploaded] https://huggingface.co/{cfg.train.hf_sample_repo}/resolve/main/samples/{sample_path.name}")
except Exception as exc:
print(f"[Sample Upload Warning] {exc}")
def upload_checkpoints_to_hf(output_dir, repo_id, step, filenames):
if not repo_id:
return
try:
from huggingface_hub import CommitOperationAdd, HfApi
ops = []
for name in filenames:
local_path = Path(output_dir) / name
if local_path.is_file():
ops.append(CommitOperationAdd(path_in_repo=f"checkpoints/{name}", path_or_fileobj=str(local_path)))
if not ops:
return
api = HfApi(token=os.getenv("HF_TOKEN"))
api.create_commit(
repo_id=repo_id,
repo_type="model",
operations=ops,
commit_message=f"Backup Murli V1.5 checkpoints at step {step}",
)
print(f"[HF Backup] Uploaded {len(ops)} checkpoint(s) at step {step} to {repo_id}/checkpoints/", flush=True)
except Exception as exc:
print(f"[HF Backup Warning] {exc}", flush=True)
def get_lr(step, warmup, max_steps, base_lr, min_lr):
if step < warmup:
return base_lr * (step + 1) / max(warmup, 1)
progress = min(1.0, (step - warmup) / max(max_steps - warmup, 1))
return min_lr + 0.5 * (base_lr - min_lr) * (1 + math.cos(math.pi * progress))
@torch.no_grad()
def validate(model, loader, device, seed):
# Compare checkpoints on the same validation noise and preserve training RNG.
devices = [torch.cuda.current_device()] if device.type == "cuda" else []
total = frames = 0
model.eval()
try:
with torch.random.fork_rng(devices=devices):
torch.random.default_generator.manual_seed(seed)
if devices:
torch.cuda.manual_seed(seed)
for batch in loader:
batch = {k: v.to(device) for k, v in batch.items()}
count = int(batch["mel_mask"].sum())
total += model(**batch)["cfm_loss"].item() * count
frames += count
finally:
model.train()
if not frames or not math.isfinite(total):
raise ValueError("Validation produced no finite frame-weighted loss")
return total / frames
def train(args, cfg=None):
cfg = cfg or MurliV15Config()
tc = cfg.train
for key in ("target_speaker", "target_gender", "batch_size", "grad_accum_steps",
"max_epochs", "max_steps", "num_workers", "max_samples",
"checkpoint_dir", "cache_dir", "sample_every", "hf_backup_every", "hf_sample_repo"):
value = getattr(args, key, None)
if value is not None:
setattr(tc, key, value)
if (args.subdirs or getattr(args, "parquet", None)) and getattr(args, "target_speaker", None) is None:
# A custom corpus can use a different narrator ID than the bundled default.
tc.target_speaker = None
if args.subdirs:
tc.data_subdirs = [s.strip() for s in args.subdirs.split(",") if s.strip()]
if min(tc.batch_size, tc.max_steps, tc.grad_accum_steps, tc.max_epochs,
tc.log_every, tc.save_every, tc.val_every) < 1 or tc.num_workers < 0:
raise ValueError("Training counts must be positive and workers nonnegative")
output = Path(tc.checkpoint_dir)
output.mkdir(parents=True, exist_ok=True)
resume = getattr(args, "resume", None)
initial = getattr(args, "init_weights", None)
if resume and initial:
raise ValueError("Choose either --resume or --init_weights")
if (resume or initial) and not Path(resume or initial).is_file():
raise FileNotFoundError(resume or initial)
dataset = MurliV15Dataset(
parquet_paths=getattr(args, "parquet", None), hf_dataset_name=tc.hf_dataset_name,
data_subdirs=tc.data_subdirs, target_speaker=tc.target_speaker, target_gender=tc.target_gender,
cache_dir=tc.cache_dir, audio_cfg=cfg.audio, max_samples=tc.max_samples, skip_invalid=False,
)
speakers = {row["speaker_id"] for row in dataset.rows}
if tc.target_speaker is None and (len(speakers) > 1 or any("unknown" in s.lower() for s in speakers)):
raise ValueError(f"Select a verified narrator with --target_speaker. Found {sorted(speakers)[:20]}")
train_ds, val_ds = dataset.split()
if not len(train_ds):
raise ValueError(f"No training clips match speaker {tc.target_speaker!r} and the selected data")
print(f"Train {len(train_ds)} | Validation {len(val_ds)} | Speakers "
f"{dict(Counter(r['speaker_id'] for r in train_ds.rows))}")
emotions = Counter(_map_emotion(row["emotion"]) for row in train_ds.rows)
print("Training emotion counts", {name: emotions[idx] for name, idx in EMOTION_TO_ID.items()})
if not emotions[EMOTION_TO_ID["story"]]:
print("No training clips labeled story. Story style has no supervised examples.")
if not len(val_ds):
print("Only one distinct transcript. Validation is unavailable.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if device.type == "cuda":
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cudnn.benchmark = True
torch.manual_seed(tc.seed)
model = MurliV15Engine(cfg).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=tc.lr, weight_decay=tc.weight_decay, betas=(0.9, 0.98))
amp = device.type == "cuda" and tc.use_amp
bf16 = amp and torch.cuda.is_bf16_supported()
scaler = torch.amp.GradScaler("cuda", enabled=amp and not bf16)
loader_opts = dict(batch_size=tc.batch_size, num_workers=tc.num_workers,
pin_memory=device.type == "cuda",
persistent_workers=(tc.num_workers > 0),
collate_fn=v15_collate_fn)
val_loader = DataLoader(val_ds, **loader_opts)
signature = hashlib.sha256()
for row in dataset.rows:
signature.update(repr((Path(row["path"]).name, row["group"], row["offset"], row["split_key"],
row["speaker_id"], row["emotion"])).encode())
layout = (signature.hexdigest(), tc.batch_size, tc.grad_accum_steps, tc.seed, dataset.feature_version)
step = epoch = offset = 0
best = float("inf")
vocoder_holder = {}
if initial or resume:
ck = torch.load(initial or resume, map_location="cpu", weights_only=True)
model.load_state_dict(ck["model"])
if resume:
if "optimizer" not in ck:
raise ValueError("Legacy weights-only checkpoint. Use --init_weights for a new optimizer.")
optimizer.load_state_dict(ck["optimizer"])
if ck.get("format_version") == 2:
if tuple(ck["layout"]) != layout:
raise ValueError("Data, preprocessing, batch size, accumulation or seed changed since checkpoint")
if ck["model_config"] != asdict(cfg.model):
raise ValueError("Model configuration changed since checkpoint")
step, epoch, offset = ck["step"], ck["epoch"], ck["offset"]
best = ck["best_val_cfm"]
if scaler.is_enabled() and ck["scaler"]:
scaler.load_state_dict(ck["scaler"])
torch.set_rng_state(ck["rng"])
if device.type == "cuda" and ck["cuda_rng"] is not None:
torch.cuda.set_rng_state(ck["cuda_rng"])
else:
step = max((int(s["step"]) for s in ck["optimizer"]["state"].values() if "step" in s), default=0)
print(f"Legacy optimizer restored at update {step}. Starting a new data epoch.")
del ck
def save(name):
atomic_save(dict(format_version=2, model=model.state_dict(), optimizer=optimizer.state_dict(),
scaler=scaler.state_dict(), step=step, epoch=epoch, offset=offset,
best_val_cfm=best, val_cfm=best, layout=layout, model_config=asdict(cfg.model),
emotion_counts=dict(emotions), rng=torch.get_rng_state(),
cuda_rng=torch.cuda.get_rng_state() if device.type == "cuda" else None),
output / name)
model.train()
optimizer.zero_grad(set_to_none=True)
t_log = time.time()
clips_since_log = 0
steps_since_log = 0
while step < tc.max_steps and epoch < tc.max_epochs:
generator = torch.Generator().manual_seed(tc.seed + epoch)
perm = torch.randperm(len(train_ds), generator=generator).tolist()
pool_size = max(tc.batch_size * 32, tc.batch_size)
order = []
for start in range(0, len(perm), pool_size):
pool = sorted(perm[start : start + pool_size], key=lambda i: train_ds.rows[i].get("duration", 0.0))
batches = [pool[j : j + tc.batch_size] for j in range(0, len(pool), tc.batch_size)]
for b_idx in torch.randperm(len(batches), generator=generator).tolist():
order.extend(batches[b_idx])
loader = DataLoader(train_ds, sampler=order[offset:], generator=generator, **loader_opts)
remaining = len(loader)
for batch_idx, batch in enumerate(loader):
group_idx = batch_idx % tc.grad_accum_steps
if group_idx == 0:
group_size = min(tc.grad_accum_steps, remaining - batch_idx)
batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
with torch.autocast(device.type, dtype=torch.bfloat16 if bf16 else torch.float16, enabled=amp):
out = model(**batch)
loss = out["loss"] / group_size
if not torch.isfinite(loss):
raise FloatingPointError(f"Nonfinite training loss after {step} updates")
scaler.scale(loss).backward()
offset += batch["token_ids"].size(0)
clips_since_log += batch["token_ids"].size(0)
if group_idx + 1 < group_size:
continue
for pg in optimizer.param_groups:
pg["lr"] = get_lr(step, tc.warmup_steps, tc.max_steps, tc.lr, tc.min_lr)
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), tc.grad_clip, error_if_nonfinite=not scaler.is_enabled())
old_scale = scaler.get_scale()
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True)
if offset == len(order):
epoch += 1
offset = 0
if scaler.get_scale() < old_scale:
continue
step += 1
steps_since_log += 1
if step == 1 or step % tc.log_every == 0:
now = time.time()
dt_log = max(now - t_log, 1e-6)
clips_s = clips_since_log / dt_log
step_rate = steps_since_log / dt_log
t_log = now
clips_since_log = 0
steps_since_log = 0
eta_h = (tc.max_steps - step) / max(step_rate, 1e-6) / 3600.0
print(
f"Ep {epoch + 1}/{tc.max_epochs} | Step {step}/{tc.max_steps} | "
f"Loss {out['loss'].item():.3f} (CFM {out['cfm_loss'].item():.3f}, "
f"Pr {out['prior_loss'].item():.3f}) | {clips_s:.0f} cl/s | ETA {eta_h:.1f}h",
flush=True,
)
if len(val_ds) and step % tc.val_every == 0:
score = validate(model, val_loader, device, tc.seed)
is_best = score < best
if is_best:
best = score
save("murli_v15_best.pt")
print(
f"[Val Ep {epoch + 1} Step {step}] CFM={score:.4f} (Best={best:.4f})"
f"{' [BEST]' if is_best else ''}",
flush=True,
)
step_ckpt = f"murli_v15_step_{step:06d}.pt"
if step % tc.save_every == 0:
save(step_ckpt)
if tc.sample_every > 0 and step % tc.sample_every == 0:
generate_test_sample(model, cfg, step, vocoder_holder)
if tc.hf_backup_every > 0 and step % tc.hf_backup_every == 0 and tc.hf_sample_repo:
if step % tc.save_every != 0:
save(step_ckpt)
upload_checkpoints_to_hf(output, tc.hf_sample_repo, step, [step_ckpt, "murli_v15_best.pt"])
if step >= tc.max_steps:
break
if not step:
raise RuntimeError("No optimizer update completed")
save("murli_v15_final.pt")
upload_checkpoints_to_hf(output, tc.hf_sample_repo, step, ["murli_v15_final.pt", "murli_v15_best.pt"])
print(f"Saved final checkpoint after {step} optimizer updates")
if __name__ == "__main__":
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--subdirs", help="Comma-separated dataset folders")
p.add_argument("--parquet", nargs="+", help="Local Parquet shards in place of Hugging Face")
p.add_argument("--target_speaker", help="Exact speaker ID, default syspin_male_01")
p.add_argument("--target_gender")
p.add_argument("--batch_size", type=int)
p.add_argument("--grad_accum_steps", type=int)
p.add_argument("--max_epochs", type=int)
p.add_argument("--max_steps", type=int, help="Completed optimizer updates")
p.add_argument("--num_workers", type=int)
p.add_argument("--max_samples", type=int)
p.add_argument("--cache_dir")
p.add_argument("--checkpoint_dir")
p.add_argument("--sample_every", type=int, help="Render test WAV every N optimizer updates (default 50000)")
p.add_argument("--hf_backup_every", type=int, help="Upload checkpoints to HF every N updates (default 50000)")
p.add_argument("--hf_sample_repo", help="Optional HF model repo to upload test WAVs & checkpoints")
group = p.add_mutually_exclusive_group()
group.add_argument("--resume", help="Restore model, optimizer and training progress")
group.add_argument("--init_weights", help="Initialize model weights and start a fresh optimizer")
train(p.parse_args())