Download train.py from ViuAI/Murli-V1.6-Code: direct link, hf CLI and curl.
- Browser
- Download file 25.7 kB
-
https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/train.py
- Command line
-
hf download hf://ViuAI/Murli-V1.6-Code/train.py
-
curl -L -o train.py https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/train.py
25.7 kB
| """Train Murli V1.6 (2026 Hybrid DiT+ConvNeXt, Single-Speaker Only-Hindi Studio Voice) from scratch or resume.""" | |
| import argparse | |
| import gc | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| import time | |
| from collections import Counter | |
| from contextlib import contextmanager | |
| from itertools import islice | |
| from dataclasses import asdict | |
| from pathlib import Path | |
| import torch | |
| from torch.utils.data import DataLoader | |
| from config import AudioConfig, EMOTION_TO_ID, ModelConfig, MurliV16Config | |
| from data.dataset import MurliV16Dataset, _map_emotion, v16_collate_fn, warm_cache_by_shard | |
| from data.text_cleaner import BilingualTextTokenizer | |
| from models.tts_engine import LOSS_MASKS, MurliV16Engine, acoustic_loss | |
| 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_samples(model, cfg, step, speaker_to_id, vocoder_holder): | |
| if vocoder_holder.get("vocoder") is None: | |
| vocoder_holder["vocoder"] = MurliVocoder(repo_id=cfg.model.vocoder_repo) | |
| vocoder_holder["tokenizer"] = BilingualTextTokenizer(use_g2p_en=False) | |
| uploaded_ops = [] | |
| sample_dir = Path(cfg.train.sample_dir) | |
| for spk_name, spk_id in sorted(speaker_to_id.items(), key=lambda kv: kv[1]): | |
| if spk_id >= cfg.model.num_speakers: | |
| continue | |
| sample_path = sample_dir / f"sample_step_{step:06d}_spk{spk_id}_{spk_name}.wav" | |
| render_with_model( | |
| model, | |
| vocoder_holder["tokenizer"], | |
| vocoder_holder["vocoder"], | |
| cfg, | |
| TEST_SAMPLE_SCRIPT, | |
| sample_path, | |
| speaker_id=spk_id, | |
| emotion="neutral", | |
| language=cfg.train.language or "auto", | |
| ) | |
| print(f"[Sample Saved] {sample_path}", flush=True) | |
| uploaded_ops.append((sample_path, f"samples/{sample_path.name}")) | |
| if cfg.train.hf_sample_repo and uploaded_ops: | |
| try: | |
| from huggingface_hub import CommitOperationAdd, HfApi | |
| api = HfApi(token=os.getenv("HF_TOKEN")) | |
| ops = [CommitOperationAdd(path_in_repo=repo_p, path_or_fileobj=str(loc_p)) for loc_p, repo_p in uploaded_ops] | |
| api.create_commit( | |
| repo_id=cfg.train.hf_sample_repo, | |
| repo_type="model", | |
| operations=ops, | |
| commit_message=f"Add Murli V1.6 test samples at step {step}", | |
| ) | |
| print(f"[Sample Uploaded] {len(ops)} WAV(s) to {cfg.train.hf_sample_repo}/samples/", flush=True) | |
| except Exception as exc: | |
| print(f"[Sample Upload Warning] {exc}", flush=True) | |
| 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.6 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)) | |
| def validate(model, loader, device, seed, amp=False, bf16=False, *, detailed=False): | |
| devices = [torch.cuda.current_device()] if device.type == "cuda" else [] | |
| sums = Counter() | |
| counts = Counter() | |
| previous_mode = model.training | |
| 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: | |
| sizes = {mask: int(batch[mask].sum()) for mask in ("mel_mask", "text_mask")} | |
| counts.update(sizes) | |
| 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, cfg_drop_prob=0.0) | |
| values = torch.stack([out[name].detach().float() for name in LOSS_MASKS]).tolist() | |
| for (name, mask), value in zip(LOSS_MASKS.items(), values): | |
| sums[name] += value * sizes[mask] | |
| finally: | |
| model.train(previous_mode) | |
| if not counts["mel_mask"] or not counts["text_mask"]: | |
| raise ValueError("Validation set contains no valid frames or tokens") | |
| metrics = {name: sums[name] / counts[mask] for name, mask in LOSS_MASKS.items()} | |
| if not all(math.isfinite(value) for value in metrics.values()): | |
| raise ValueError(f"Nonfinite validation result: {metrics}") | |
| return metrics if detailed else metrics["cfm_loss"] | |
| def _append_metric(output_dir: Path, payload: dict) -> None: | |
| with (output_dir / "metrics.jsonl").open("a", encoding="utf-8") as stream: | |
| stream.write(json.dumps(payload, sort_keys=True) + "\n") | |
| def _use_ema_weights(model, ema_state): | |
| if ema_state is None: | |
| yield | |
| return | |
| live = {k: v.detach().clone() for k, v in model.state_dict().items()} | |
| try: | |
| model.load_state_dict({k: v.to(device=live[k].device, dtype=live[k].dtype) for k, v in ema_state.items()}) | |
| yield | |
| finally: | |
| model.load_state_dict(live) | |
| def accumulation_groups(loader, size): | |
| batches = iter(loader) | |
| while group := list(islice(batches, size)): | |
| counts = [{mask: int(batch[mask].sum()) for mask in ("mel_mask", "text_mask")} for batch in group] | |
| totals = {mask: sum(item[mask] for item in counts) for mask in counts[0]} | |
| yield [(batch, {mask: n / totals[mask] for mask, n in item.items()}) | |
| for batch, item in zip(group, counts)] | |
| def train(args, cfg=None): | |
| supplied_cfg = cfg is not None | |
| cfg = cfg or MurliV16Config() | |
| tc = cfg.train | |
| for key in ( | |
| "target_gender", "batch_size", "grad_accum_steps", "max_epochs", | |
| "max_steps", "num_workers", "max_samples", "checkpoint_dir", | |
| "cache_dir", "sample_dir", "sample_every", "hf_backup_every", "hf_sample_repo", | |
| "lr", "min_lr", "warmup_steps", "val_every", "save_every", "log_every", "ema_decay", | |
| ): | |
| value = getattr(args, key, None) | |
| if value is not None: | |
| setattr(tc, key, value) | |
| if getattr(args, "target_speakers", None): | |
| tc.target_speakers = [s.strip() for s in args.target_speakers.split(",") if s.strip()] | |
| elif getattr(args, "all_speakers", False): | |
| tc.target_speakers = None | |
| if getattr(args, "subdirs", None): | |
| tc.data_subdirs = [s.strip() for s in args.subdirs.split(",") if s.strip()] | |
| if getattr(args, "language", None): | |
| tc.language = None if args.language == "auto" else args.language | |
| if getattr(args, "compile", False): | |
| tc.compile_model = True | |
| if getattr(args, "no_compile", False): | |
| tc.compile_model = False | |
| 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") | |
| if not 0 <= tc.min_lr <= tc.lr or not math.isfinite(tc.lr) or tc.lr <= 0 or tc.warmup_steps < 0: | |
| raise ValueError("Use finite learning rates with 0 <= min_lr <= lr, lr > 0 and warmup_steps >= 0") | |
| 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) | |
| if initial or resume: | |
| ck = torch.load(initial or resume, map_location="cpu", weights_only=True) | |
| if not supplied_cfg: | |
| if "model_config" in ck: | |
| cfg.model = ModelConfig(**ck["model_config"]) | |
| if "audio_config" in ck: | |
| cfg.audio = AudioConfig(**ck["audio_config"]) | |
| elif resume: | |
| if ck.get("model_config", asdict(cfg.model)) != asdict(cfg.model) or ck.get("audio_config", asdict(cfg.audio)) != asdict(cfg.audio): | |
| raise ValueError("Checkpoint configuration differs from the requested resume configuration") | |
| dataset = MurliV16Dataset( | |
| parquet_paths=getattr(args, "parquet", None), | |
| hf_dataset_name=tc.hf_dataset_name, | |
| data_subdirs=tc.data_subdirs, | |
| target_speakers=tc.target_speakers, | |
| target_gender=tc.target_gender, | |
| cache_dir=tc.cache_dir, | |
| audio_cfg=cfg.audio, | |
| max_samples=tc.max_samples, | |
| skip_invalid=not getattr(args, "strict_dataset", False), | |
| language=tc.language, | |
| target_language=tc.language, | |
| ) | |
| # Exclude invalid records before assigning validation transcripts or counting speakers. | |
| if tc.cache_dir: | |
| warm_cache_by_shard(dataset, num_workers=max(1, tc.num_workers)) | |
| valid_rows = [] | |
| for row in dataset.rows: | |
| marker = Path(tc.cache_dir) / f"{row['uid']}-{dataset.feature_version}.pt.bad" | |
| if marker.is_file(): | |
| if not dataset.skip_invalid: | |
| raise ValueError(f"{row['path']} row {row['offset']}: {marker.read_text(encoding='utf-8')}") | |
| continue | |
| valid_rows.append(row) | |
| if len(valid_rows) != len(dataset.rows): | |
| print(f"[Dataset] Excluded {len(dataset.rows) - len(valid_rows)} invalid clips", flush=True) | |
| dataset.rows = valid_rows | |
| train_ds, val_ds = dataset.split() | |
| if not len(train_ds): | |
| raise ValueError("No valid training clips match selected speakers/subdirs") | |
| active_speakers = sorted({r["speaker_id"] for r in train_ds.rows}) | |
| if any("unknown" in s.lower() for s in active_speakers): | |
| raise ValueError(f"Unidentified speaker found: {active_speakers}") | |
| spk_counts = dict(Counter(r["speaker_id"] for r in train_ds.rows)) | |
| active_map = {s: dataset.speaker_to_id[s] for s in active_speakers} | |
| if max(active_map.values()) >= cfg.model.num_speakers: | |
| raise ValueError(f"Speaker ID {max(active_map.values())} exceeds model.num_speakers={cfg.model.num_speakers}") | |
| print(f"Train {len(train_ds)} | Validation {len(val_ds)} | Speakers {spk_counts} | IDs {active_map}", flush=True) | |
| emotions = Counter(_map_emotion(row["emotion"]) for row in train_ds.rows) | |
| print("Emotion counts", {name: emotions[idx] for name, idx in EMOTION_TO_ID.items()}, flush=True) | |
| gc.collect() | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| if device.type == "cuda": | |
| torch.set_float32_matmul_precision("high") | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| torch.backends.cudnn.benchmark = True | |
| torch.manual_seed(tc.seed) | |
| model = MurliV16Engine(cfg).to(device) | |
| n_params = sum(p.numel() for p in model.parameters()) / 1e6 | |
| print(f"[Murli V1.6] Parameters: {n_params:.2f}M (Hybrid DiT+ConvNeXt + Frame Prosody)", flush=True) | |
| optimizer = torch.optim.AdamW( | |
| model.parameters(), | |
| lr=tc.lr, | |
| weight_decay=tc.weight_decay, | |
| betas=(0.9, 0.98), | |
| fused=(device.type == "cuda"), | |
| ) | |
| 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=False, | |
| collate_fn=v16_collate_fn, | |
| ) | |
| if tc.num_workers > 0: | |
| loader_opts["prefetch_factor"] = 2 | |
| val_loader = DataLoader(val_ds, **loader_opts) | |
| signature = hashlib.sha256() | |
| for row in dataset.rows: | |
| signature.update(repr((row["uid"], row["speaker_num"], | |
| 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") | |
| last_validation = {} | |
| last_validation_step = None | |
| vocoder_holder = {} | |
| ema_state = ( | |
| {k: v.detach().float().clone() for k, v in model.state_dict().items()} | |
| if tc.ema_decay > 0.0 else None | |
| ) | |
| if initial or resume: | |
| model.load_state_dict(ck["model"]) | |
| if ema_state is not None: | |
| src_ema = ck.get("ema_model") or ck["model"] | |
| ema_state = {k: v.detach().float().to(device).clone() for k, v in src_ema.items()} | |
| if resume: | |
| if "optimizer" not in ck: | |
| raise ValueError("Resume checkpoint is missing optimizer state; pass --init_weights") | |
| optimizer.load_state_dict(ck["optimizer"]) | |
| if ck.get("scaler") and scaler.is_enabled(): | |
| scaler.load_state_dict(ck["scaler"]) | |
| last_validation = ck.get("validation_metrics") or {} | |
| last_validation_step = ck.get("validation_step") | |
| if "best_val_cfm" in ck: | |
| best = float(ck["best_val_cfm"]) | |
| elif "val_cfm" in ck: | |
| best = float(ck["val_cfm"]) | |
| if "step" in ck and ck.get("layout") == layout: | |
| step, epoch, offset = int(ck["step"]), int(ck["epoch"]), int(ck["offset"]) | |
| 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: | |
| raise ValueError("Checkpoint dataset, feature version, or batch layout differs; use --init_weights to start a new run") | |
| del ck | |
| if device.type == "cuda" and tc.compile_model: | |
| try: | |
| model.text_encoder.compile(dynamic=True) | |
| model.vector_field.compile(dynamic=True) | |
| print("[Speed] Compiled text_encoder & vector_field (dynamic=True) + fused AdamW", flush=True) | |
| except Exception as exc: | |
| print(f"[Compile Warning] Falling back to eager mode: {exc}", flush=True) | |
| ema_fp_dst, ema_fp_src, ema_other_pairs = [], [], [] | |
| if ema_state is not None: | |
| for k, v in model.state_dict().items(): | |
| if k not in ema_state: | |
| continue | |
| if v.is_floating_point(): | |
| ema_fp_dst.append(ema_state[k]) | |
| ema_fp_src.append(v) | |
| else: | |
| ema_other_pairs.append((ema_state[k], v)) | |
| def save(name): | |
| live_sd = model.state_dict() | |
| atomic_save( | |
| dict( | |
| format_version=2, | |
| model=live_sd, | |
| ema_model=( | |
| {k: v.to(dtype=live_sd[k].dtype) for k, v in ema_state.items()} | |
| if ema_state is not None else None | |
| ), | |
| optimizer=optimizer.state_dict(), | |
| scaler=scaler.state_dict(), | |
| step=step, | |
| epoch=epoch, | |
| offset=offset, | |
| best_val_cfm=best, | |
| val_cfm=last_validation.get("cfm_loss", best), | |
| validation_metrics=last_validation, | |
| validation_step=last_validation_step, | |
| train_config=asdict(tc), | |
| layout=layout, | |
| model_config=asdict(cfg.model), | |
| audio_config=asdict(cfg.audio), | |
| speaker_to_id=active_map, | |
| 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 | |
| best_saved_this_run = False | |
| while step < tc.max_steps and epoch < tc.max_epochs: | |
| display_epoch = epoch + 1 | |
| 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) | |
| for group in accumulation_groups(loader, tc.grad_accum_steps): | |
| group_losses = [] | |
| for batch, fractions in group: | |
| batch = {key: tensor.to(device, non_blocking=True) for key, tensor in batch.items()} | |
| with torch.autocast(device.type, dtype=torch.bfloat16 if bf16 else torch.float16, enabled=amp): | |
| out = model(**batch) | |
| contributions = {name: out[name] * fractions[mask] for name, mask in LOSS_MASKS.items()} | |
| loss = acoustic_loss(contributions, tc) | |
| if not torch.isfinite(loss): | |
| raise FloatingPointError(f"Nonfinite training loss after {step} updates") | |
| scaler.scale(loss).backward() | |
| group_losses.append(torch.stack([loss, *contributions.values()]).detach()) | |
| offset += batch["token_ids"].size(0) | |
| clips_since_log += batch["token_ids"].size(0) | |
| del out, loss, contributions | |
| 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) | |
| grad_norm = 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 ema_fp_dst: | |
| decay = min(tc.ema_decay, (1.0 + step) / (10.0 + step)) | |
| with torch.no_grad(): | |
| src_fp = [s.detach() if s.dtype == torch.float32 else s.detach().float() for s in ema_fp_src] | |
| torch._foreach_mul_(ema_fp_dst, decay) | |
| torch._foreach_add_(ema_fp_dst, src_fp, alpha=1.0 - decay) | |
| for dst, src in ema_other_pairs: | |
| dst.copy_(src) | |
| if step == 1 or step % tc.log_every == 0: | |
| total, cfm, prior, duration, pitch, energy, frame = torch.stack(group_losses).sum(0).tolist() | |
| 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 {display_epoch}/{tc.max_epochs} | Step {step}/{tc.max_steps} | " | |
| f"Loss {total:.3f} (CFM {cfm:.3f}, Prior {prior:.3f}, Duration {duration:.3f}, " | |
| f"F0 {pitch:.3f}, Energy {energy:.3f}, Frame {frame:.3f}) | " | |
| f"lr={pg['lr']:.3g} grad_norm={float(grad_norm):.3f} | " | |
| f"{clips_s:.2f} cl/s | ETA {eta_h:.1f}h", | |
| flush=True, | |
| ) | |
| _append_metric(output, { | |
| "type": "train", "step": step, "epoch": display_epoch, "loss": round(total, 5), | |
| "cfm_loss": round(cfm, 5), "prior_loss": round(prior, 5), "dur_loss": round(duration, 5), | |
| "f0_loss": round(pitch, 5), "energy_loss": round(energy, 5), "frame_prosody_loss": round(frame, 5), | |
| "lr": pg["lr"], "grad_norm": float(grad_norm), "clips_per_sec": round(clips_s, 3), | |
| }) | |
| if len(val_ds) and (step % tc.val_every == 0 or step == tc.max_steps or epoch == tc.max_epochs): | |
| with _use_ema_weights(model, ema_state): | |
| last_validation = validate(model, val_loader, device, tc.seed, amp=amp, bf16=bf16, detailed=True) | |
| last_validation_step = step | |
| score = last_validation["cfm_loss"] | |
| is_best = score < best | |
| if is_best: | |
| best = score | |
| save("murli_v16_best.pt") | |
| best_saved_this_run = True | |
| print("Validation losses", {name: round(value, 4) for name, value in last_validation.items()}, flush=True) | |
| print(f"[Val Ep {display_epoch} Step {step}] CFM={score:.4f} (Best={best:.4f}){' [BEST]' if is_best else ''}", flush=True) | |
| _append_metric(output, {"type": "val", "step": step, "epoch": display_epoch, "best_val_cfm": best, **last_validation}) | |
| step_ckpt = f"murli_v16_step_{step:06d}.pt" | |
| if step % tc.save_every == 0: | |
| save(step_ckpt) | |
| if tc.sample_every > 0 and step % tc.sample_every == 0: | |
| try: | |
| with _use_ema_weights(model, ema_state): | |
| generate_test_samples(model, cfg, step, active_map, vocoder_holder) | |
| except (ImportError, OSError, RuntimeError, ValueError) as exc: | |
| print(f"[Sample Warning] Step {step}: {exc}", flush=True) | |
| 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_v16_best.pt"] if best_saved_this_run else [])) | |
| if step >= tc.max_steps: | |
| break | |
| if not step: | |
| raise RuntimeError("No optimizer update completed") | |
| save("murli_v16_final.pt") | |
| upload_checkpoints_to_hf(output, tc.hf_sample_repo, step, ["murli_v16_final.pt"] + (["murli_v16_best.pt"] if best_saved_this_run else [])) | |
| print(f"Saved final checkpoint after {step} optimizer updates", flush=True) | |
| 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_speakers", help="Comma-separated speaker IDs") | |
| p.add_argument("--all_speakers", action="store_true", help="Disable speaker filtering") | |
| 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) | |
| 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_dir") | |
| p.add_argument("--lr", type=float) | |
| p.add_argument("--min_lr", type=float) | |
| p.add_argument("--warmup_steps", type=int) | |
| p.add_argument("--val_every", type=int) | |
| p.add_argument("--save_every", type=int) | |
| p.add_argument("--log_every", type=int) | |
| p.add_argument("--sample_every", type=int) | |
| p.add_argument("--hf_backup_every", type=int) | |
| p.add_argument("--hf_sample_repo") | |
| p.add_argument("--ema_decay", type=float) | |
| p.add_argument("--language", choices=["hi", "en", "auto"], help="Dataset G2P language mode (default: hi)") | |
| p.add_argument("--compile", action="store_true", help="Enable torch.compile on CUDA (off by default for variable-length stability)") | |
| p.add_argument("--no_compile", action="store_true", help="Disable torch.compile speedup on CUDA") | |
| p.add_argument("--strict_dataset", action="store_true", help="Fail immediately on any corrupt/unalignable clip") | |
| group = p.add_mutually_exclusive_group() | |
| group.add_argument("--resume") | |
| group.add_argument("--init_weights") | |
| train(p.parse_args()) | |