Add 50k-step test audio generation + HF sample upload for download
Browse filesFiles changed (3)
- config.py+2
- narrate.py+25-14
- train.py+45
104 unmodified lines105106107108109110111112104 unmodified lines log_every: int = 50
val_every: int = 1000
save_every: int = 2500
sample_every: int = 50_000
hf_sample_repo: Optional[str] = None
seed: int = 42
35 unmodified lines363738394041424344394041464748495051525342434445464748495024 unmodified lines7576777879808182838485868788899091929394959697989910010135 unmodified lines
@torch.inference_mode()def render(checkpoint, text, destination, emotion="neutral", speed=None): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") state = torch.load(checkpoint, map_location="cpu", weights_only=True) cfg = MurliV15Config() if "model_config" in state: cfg.model = ModelConfig(**state["model_config"])def render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion="neutral", speed=None): device = next(model.parameters()).device emotion_id = EMOTION_TO_ID[emotion] if emotion_id and "emotion_counts" in state and not state["emotion_counts"].get(emotion_id): raise ValueError(f"This checkpoint has no training examples for {emotion!r}. Use a trained style.") model = MurliV15Engine(cfg) model.load_state_dict(state["model"]) del state model.to(device).eval() tokenizer = BilingualTextTokenizer(use_g2p_en=False) vocoder = MurliVocoder() destination = Path(destination) destination.parent.mkdir(parents=True, exist_ok=True) if speed is not None and (not math.isfinite(speed) or speed <= 0): raise ValueError("Speed must be finite and positive") was_training = model.training model.eval() with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as f: temporary = f.name try:24 unmodified lines os.replace(temporary, destination) finally: Path(temporary).unlink(missing_ok=True) if was_training: model.train()
@torch.inference_mode()def render(checkpoint, text, destination, emotion="neutral", speed=None): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") state = torch.load(checkpoint, map_location="cpu", weights_only=True) cfg = MurliV15Config() if "model_config" in state: cfg.model = ModelConfig(**state["model_config"]) emotion_id = EMOTION_TO_ID[emotion] if emotion_id and "emotion_counts" in state and not state["emotion_counts"].get(emotion_id): raise ValueError(f"This checkpoint has no training examples for {emotion!r}. Use a trained style.") model = MurliV15Engine(cfg) model.load_state_dict(state["model"]) del state model.to(device).eval() tokenizer = BilingualTextTokenizer(use_g2p_en=False) vocoder = MurliVocoder() render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion=emotion, speed=speed)
if __name__ == "__main__":2 unmodified lines34567893 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596087 unmodified lines14814915015115215315471 unmodified lines22622722822923023123223314 unmodified lines2482492502512522532542552 unmodified linesimport argparse
import hashlib
import math
import os
from collections import Counter
from dataclasses import asdict
from pathlib import Path3 unmodified lines
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 get_lr(step, warmup, max_steps, base_lr, min_lr):
if step < warmup:87 unmodified lines 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"])71 unmodified lines save("murli_v15_best.pt")
if step % tc.save_every == 0:
save(f"murli_v15_step_{step:06d}.pt")
if tc.sample_every > 0 and step % tc.sample_every == 0:
generate_test_sample(model, cfg, step, vocoder_holder)
if step >= tc.max_steps:
break
if not step:14 unmodified lines 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_sample_repo", help="Optional HF model repo to upload test WAVs for download")
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")config.py+2
narrate.py+25-14
train.py+45