Verified hardening pass: G2P conjuncts, 150Hz F0 fix, corrupt-row recovery, batched B>1 synthesis, 69.71 MiB ONNX CFM (3/3 tests pass)
Browse filesFiles changed (11)
- RULEBOOK_V1_6.md+1
- export_onnx.py+48-29
- models/flow_matching.py+10-3
- models/layers.py+3-2
- models/prosody_aligner.py+19-10
- models/text_encoder.py+1-1
- models/tts_engine.py+6-2
- models/vocoder.py+9-7
- narrate.py+10-5
- tests/test_v16.py+31-1
- train.py+20-9
45 unmodified lines4647484945 unmodified lines- **2026-12-01 (Data & Exporter):** Added 3-speaker mapping (`0=syspin_male_01`, `1=kalita_rasa_male_01`, `2=iisc_f_hindi_female_spk001`), duration bucketing, multi-speaker test WAV uploader, and opset-17 Android ONNX exporter (`frontend=51.99 MiB`, `cfm_step=82.11 MiB`).- **2026-12-01 (Verify & Release):** `python -m unittest discover -s tests -p "test_*.py" -v` → `Ran 3 tests in 52.324s — OK`. Ready for `108.8+h` training on `ViuAI/Murli-V1.6-Code`.- **2026-12-01 (Speed Tuning):** Removed full-tensor FP32 allocation in `ConvNeXt1DBlock` GRN (`layers.py`) and added `prefetch_factor=4` + `float32_matmul_precision("high")` in `train.py`.- **2026-12-01 (13:19 Audit & Verification):** Verified user hardening edits (`ज्ञान→gjaːn̪`, `मतलब→mət̪ləb`, `प्रगति→pɾəgət̪ɪ`, English `"3.5 percent"`, `150 Hz F0` non-zero separation, corrupt audio skip + `--strict_dataset`, batched `B>1` padded synthesis, `cfm_step.onnx` reduced to `69.71 MiB`). `test_v16.py` → `Ran 3 tests in 49.749s — OK`. Pushed to `ViuAI/Murli-V1.6-Code`.40 unmodified lines4142434445464445464748495086 unmodified lines13713813913914014114214014414514614714814915015115215315415514114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417515715815916016116216316416516617617717817918018118218318418518618718840 unmodified lines text_with_style = text_feats + style.unsqueeze(1) prior_text = self.pa.compute_prior(text_with_style, text_mask)
log_dur = self.pa.dur_predictor(text_feats, style, mask=text_mask) dur_raw = torch.exp(log_dur) / speed.view(1, 1) durs = torch.clamp(torch.round(dur_raw), min=self.min_frames).long() log_dur = torch.clamp(self.pa.dur_predictor(text_feats, style, mask=text_mask), max=10.0) speed_safe = torch.clamp(speed.view(1, 1), min=1e-3) dur_raw = torch.exp(log_dur) / speed_safe durs = torch.clamp(torch.round(dur_raw), min=self.min_frames, max=250.0).long()
pred_f0 = self.pa.f0_predictor(text_feats, style, mask=text_mask) pred_energy = self.pa.energy_predictor(text_feats, style, mask=text_mask)86 unmodified lines dynamo=False, )
with torch.no_grad(): pt_cond, pt_prior = frontend(dummy_ids, dummy_spk, dummy_emo, dummy_speed) pt_vel = cfm_step(dummy_x, dummy_t, dummy_cond, dummy_spk_b)
fe_sess = ort.InferenceSession(frontend_path, providers=["CPUExecutionProvider"]) ort_cond, ort_prior = fe_sess.run( None, { "token_ids": dummy_ids.numpy(), "speaker_id": dummy_spk.numpy(), "emotion_id": dummy_emo.numpy(), "speed": dummy_speed.numpy(), }, ) assert np.allclose(pt_cond.numpy(), ort_cond, atol=1e-4, rtol=1e-4), "Frontend cond parity mismatch" assert np.allclose(pt_prior.numpy(), ort_prior, atol=1e-4, rtol=1e-4), "Frontend prior parity mismatch"
cfm_sess = ort.InferenceSession(cfm_path, providers=["CPUExecutionProvider"])
# Verify parity across both export dummy shapes and alternative dynamic sequence/batch shapes fe_cases = [ (dummy_ids, dummy_spk, dummy_emo, dummy_speed), (torch.randint(1, 60, (1, 7), dtype=torch.long), torch.tensor([2], dtype=torch.long), torch.tensor([1], dtype=torch.long), torch.tensor([1.1], dtype=torch.float32)), ] for ids_c, spk_c, emo_c, spd_c in fe_cases: with torch.no_grad(): pt_cond, pt_prior = frontend(ids_c, spk_c, emo_c, spd_c) ort_cond, ort_prior = fe_sess.run( None, { "token_ids": ids_c.numpy(), "speaker_id": spk_c.numpy(), "emotion_id": emo_c.numpy(), "speed": spd_c.numpy(), }, ) assert np.allclose(pt_cond.numpy(), ort_cond, atol=1e-4, rtol=1e-4), "Frontend cond parity mismatch" assert np.allclose(pt_prior.numpy(), ort_prior, atol=1e-4, rtol=1e-4), "Frontend prior parity mismatch"
cfm_cases = [ (dummy_x, dummy_t, dummy_cond, dummy_spk_b), ( torch.randn((1, engine.cfg.model.mel_dim, 37), dtype=torch.float32), torch.tensor([0.75], dtype=torch.float32), torch.randn((1, engine.cfg.model.text_dim, 37), dtype=torch.float32), torch.tensor([0], dtype=torch.long), ), ] for x_c, t_c, cond_c, spk_c in cfm_cases: with torch.no_grad(): pt_vel = cfm_step(x_c, t_c, cond_c, spk_c) (ort_vel,) = cfm_sess.run( None, { "x": dummy_x.numpy(), "t": dummy_t.numpy(), "cond": dummy_cond.numpy(), "speaker_id": dummy_spk_b.numpy(), }, ) assert np.allclose(pt_vel.numpy(), ort_vel, atol=1e-4, rtol=1e-4), "CFM step parity mismatch" (ort_vel,) = cfm_sess.run( None, { "x": x_c.numpy(), "t": t_c.numpy(), "cond": cond_c.numpy(), "speaker_id": spk_c.numpy(), }, ) assert np.allclose(pt_vel.numpy(), ort_vel, atol=1e-4, rtol=1e-4), "CFM step parity mismatch" return frontend_path, cfm_path
73 unmodified lines74757677777879808182838485868768 unmodified lines1561571581591601611622 unmodified lines1651661671681691701711724 unmodified lines17717817918017418118218317718418518618773 unmodified lines ConvNeXt1DBlock(hidden_dim, kernel_size=kernel_size, mult=3) for _ in range(num_blocks) ]) # AdaLN scale+shift conditioning per ConvNeXt block # AdaLN scale+shift conditioning per ConvNeXt block (zero-initialized for identity start) self.conv_ada = nn.ModuleList([ nn.Linear(hidden_dim, hidden_dim * 2) for _ in range(num_blocks) ]) for ada in self.conv_ada: nn.init.zeros_(ada.weight) nn.init.zeros_(ada.bias) self.dit_blocks = nn.ModuleList([ AdaLNZeroDiTBlock(hidden_dim, num_heads=attn_heads, ff_mult=2.0) if ((idx + 1) % attn_every == 0) else nn.Identity()68 unmodified lines steps: int = 48, cfg_scale: float = 1.3, temperature: float = 0.90, mask: Optional[torch.Tensor] = None,) -> torch.Tensor: bsz, _, t_mel = cond.shape device = cond.device2 unmodified lines speaker_ids = torch.zeros((bsz,), dtype=torch.long, device=device)
x = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperature if mask is not None: x = x * mask.unsqueeze(1).to(dtype) dt = 1.0 / float(steps) null_cond = torch.zeros_like(cond)
4 unmodified lines t_in = torch.cat([t_cur, t_cur], dim=0) c_in = torch.cat([cond, null_cond], dim=0) s_in = torch.cat([speaker_ids, speaker_ids], dim=0) m_in = torch.cat([mask, mask], dim=0) if mask is not None else None v_cond, v_uncond = vector_field(x_in, t_in, c_in, speaker_ids=s_in, mask=None).chunk(2, dim=0) v_cond, v_uncond = vector_field(x_in, t_in, c_in, speaker_ids=s_in, mask=m_in).chunk(2, dim=0) v = v_uncond + cfg_scale * (v_cond - v_uncond) else: v = vector_field(x, t_cur, cond, speaker_ids=speaker_ids, mask=None) v = vector_field(x, t_cur, cond, speaker_ids=speaker_ids, mask=mask) x = x + v * dt
return x122345154 unmodified lines160161162163163164165166167"""
Shared 2026 Transformer & ConvNeXt-V2 Building Blocks for Murli V2.0.
Shared 2026 Transformer & ConvNeXt-V2 Building Blocks for Murli V1.6.
Includes RMSNorm, SwiGLU MLP, Rotary Positional Embeddings (RoPE), SDPA Attention,
and Mask-Aware ConvNeXt-V2 1D blocks.
"""154 unmodified lines h = F.gelu(self.pw1(h))
if mask is not None:
h = h * mask.unsqueeze(-1).to(h.dtype)
gx = h.pow(2).sum(dim=1, keepdim=True, dtype=torch.float32).add(1e-12).sqrt().to(h.dtype)
# Compute squared L2 in FP32 to avoid FP16 overflow and 0/0 NaN gradients
gx = h.float().pow(2).sum(dim=1, keepdim=True).add(1e-12).sqrt().to(h.dtype)
nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
h = self.grn_gamma * (h * nx) + self.grn_beta + h
out = residual + self.pw2(h)24 unmodified lines2526272828293031184 unmodified lines2162172182192192202212222232242256 unmodified lines23223323423223323523623723823923 unmodified lines2632642652632662672682692702712682692722732742752762 unmodified lines27928028127828228328428528628728228328828929029129229324 unmodified lines for b in prange(val_np.shape[0]): tx = t_xs[b] ty = t_ys[b] q = np.full((tx, ty), -1e9, dtype=np.float32) q = np.full((tx, ty), -np.inf, dtype=np.float32) q[0, 0] = val_np[b, 0, 0] for y in range(1, ty): lo = max(0, tx - (ty - y))184 unmodified lines gt_log_dur = torch.log(gt_dur.clamp(min=1.0))
dur_safe = gt_dur.clamp(min=1.0) gt_f0_tok = torch.bmm(attn, f0_target.unsqueeze(-1)).squeeze(-1) / dur_safe # Average F0 over voiced frames only so unvoiced frames inside a token do not drag pitch down vuv = (f0_target > 0.05).float() vuv_tok = torch.bmm(attn, vuv.unsqueeze(-1)).squeeze(-1).clamp(min=1.0) gt_f0_tok = torch.bmm(attn, (f0_target * vuv).unsqueeze(-1)).squeeze(-1) / vuv_tok gt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safe
pred_log_dur = self.dur_predictor(text_feats, style, mask=text_mask)6 unmodified lines f0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / t_denom energy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / t_denom
# Expand text + predicted coarse prosody, then refine smoothly at frame resolution prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1) # [B, T_x, 2] # Expand detached coarse prosody predictions and refine smoothly at frame resolution prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1).detach() # [B, T_x, 2] expanded_h = torch.bmm(attn.transpose(1, 2), text_with_style) coarse_frame_prosody = torch.bmm(attn.transpose(1, 2), prosody_tok) refined_frame_prosody = self.frame_prosody_net(23 unmodified lines emotion_ids: torch.Tensor, speed: float = 0.92, min_frames: int = 2, ) -> Tuple[torch.Tensor, torch.Tensor]: return_mask: bool = False, ): style = self.speaker_emb(speaker_ids) + self.emotion_emb(emotion_ids) text_with_style = text_feats + style.unsqueeze(1) prior_text = self.compute_prior(text_with_style, text_mask)
log_dur = self.dur_predictor(text_feats, style, mask=text_mask) durs = torch.clamp(torch.round(torch.exp(log_dur) / max(speed, 1e-3)), min=min_frames).long() log_dur = self.dur_predictor(text_feats, style, mask=text_mask).clamp(max=10.0) durs = torch.clamp(torch.round(torch.exp(log_dur) / max(speed, 1e-3)), min=min_frames, max=250).long() durs = durs * text_mask.long()
pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)2 unmodified lines
expanded_h = expand_by_durations(text_with_style, durs) coarse_frame_prosody = expand_by_durations(prosody_tok, durs) mel_mask = torch.ones((expanded_h.shape[0], expanded_h.shape[1]), dtype=torch.bool, device=expanded_h.device) mel_lengths = durs.sum(dim=1) t_mel = expanded_h.shape[1] mel_mask = torch.arange(t_mel, device=expanded_h.device).unsqueeze(0) < mel_lengths.unsqueeze(1) refined_frame_prosody = self.frame_prosody_net( expanded_h, coarse_frame_prosody, self.prosody_proj, mask=mel_mask ) cond_expanded = expanded_h + self.prosody_proj(refined_frame_prosody) prior_expanded = expand_by_durations(prior_text, durs) m_f = mel_mask.unsqueeze(-1).to(expanded_h.dtype) cond_expanded = (expanded_h + self.prosody_proj(refined_frame_prosody)) * m_f prior_expanded = expand_by_durations(prior_text, durs, max_len=t_mel) * m_f if return_mask: return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2), mel_mask return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)122345"""Murli V2.0 Bilingual Text & Phoneme Encoder.Murli V1.6 Bilingual Text & Phoneme Encoder.Combines local ConvNeXt-V2 phonetic boundary blocks with a deep RoPE SwiGLU Transformer."""
56 unmodified lines5758596061626313 unmodified lines77787980818283848586858788899040 unmodified lines1311321331321341351361371381391401411421431442 unmodified lines14714814915015115256 unmodified lines energy_target: torch.Tensor, speaker_ids: Optional[torch.Tensor] = None, emotion_ids: Optional[torch.Tensor] = None, cfg_drop_prob: Optional[float] = None, ) -> Dict[str, torch.Tensor]: bsz = token_ids.shape[0] if speaker_ids is None:13 unmodified lines energy_target=energy_target, )
drop_p = self.cfg.model.cfg_drop_prob if cfg_drop_prob is None else cfg_drop_prob cfm_loss = compute_cfm_loss( self.vector_field, mel_target=mel_target, cond=cond_mel, mel_mask=mel_mask, speaker_ids=speaker_ids, cfg_drop_prob=self.cfg.model.cfg_drop_prob, cfg_drop_prob=drop_p, )
tc = self.cfg.train40 unmodified lines speaker_ids = torch.full((bsz,), int(speaker_id), dtype=torch.long, device=token_ids.device) emotion_ids = torch.full((bsz,), int(emotion_id), dtype=torch.long, device=token_ids.device) text_feats = self.text_encoder(token_ids, text_mask=text_mask) cond_mel, _ = self.prosody_aligner.forward_infer( cond_mel, _, mel_mask = self.prosody_aligner.forward_infer( text_feats=text_feats, text_mask=text_mask, speaker_ids=speaker_ids, emotion_ids=emotion_ids, speed=speed, min_frames=m.min_frames, return_mask=True, ) mel_denorm = sample_ode( self.vector_field,2 unmodified lines steps=steps, cfg_scale=cfg_scale, temperature=temperature, mask=mel_mask, ) return mel_denorm * self.cfg.audio.mel_std + self.cfg.audio.mel_mean1223456789101111121314151617183 unmodified lines22232423242525262728291 unmodified line3132333334343536373839"""
Murli V2.0 Neural Vocoder Wrapper.
Murli V1.6 Neural Vocoder Wrapper.
Supports Vocos 24kHz (100 HTK mel bins) by default and optional BigVGAN-v2 24kHz 100-band backend.
"""
from typing import Optional
import torch
import torch.nn as nn
class MurliVocoder(nn.Module):
def __init__(self, backend: str = "vocos"):
def __init__(self, backend: str = "vocos", repo_id: Optional[str] = None):
super().__init__()
self.backend = backend
self.repo_id = repo_id
self.model = None
self.sample_rate = 24000
3 unmodified lines
if self.backend == "bigvgan_v2":
import bigvgan
model = bigvgan.BigVGAN.from_pretrained(
"nvidia/bigvgan_v2_24khz_100band_256x", use_cuda_kernel=False
).to(device).eval()
repo = self.repo_id or "nvidia/bigvgan_v2_24khz_100band_256x"
model = bigvgan.BigVGAN.from_pretrained(repo, use_cuda_kernel=False).to(device).eval()
model.remove_weight_norm()
self.model = model
return model1 unmodified line raise ValueError(f"Unknown vocoder: {self.backend}")
from vocos import Vocos
print("Loading pretrained Vocos 24kHz (charactr/vocos-mel-24khz)...")
self.model = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device).eval()
repo = self.repo_id or "charactr/vocos-mel-24khz"
print(f"Loading pretrained Vocos 24kHz ({repo})...")
self.model = Vocos.from_pretrained(repo).to(device).eval()
return self.model
@torch.no_grad()33 unmodified lines3435363738383940413940414243444546474849505189 unmodified lines14114214313914414514614733 unmodified lines parts = [] for sentence in filter(str.strip, sentences): words = [] approx_tokens = 3 for word in sentence.split(): if words and tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit: parts.append((" ".join(words), 70)) words = [] if tokenizer.text_to_ids(word).numel() > limit: w_len = tokenizer.text_to_ids(word).numel() if w_len > limit: raise ValueError("A single word exceeds the model chunk limit") if words and approx_tokens + w_len + 2 > limit: if tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit: parts.append((" ".join(words), 70)) words = [] approx_tokens = 3 words.append(word) approx_tokens += max(1, w_len - 2) if words: parts.append((" ".join(words), 120)) if parts:89 unmodified lines del state model.to(device).eval() tokenizer = BilingualTextTokenizer(use_g2p_en=False) vocoder = MurliVocoder() vocoder = MurliVocoder(repo_id=cfg.model.vocoder_repo) render_with_model(model, tokenizer, vocoder, cfg, text, destination, speaker_id=speaker_id, emotion=emotion, speed=speed)
17 unmodified lines1819202122232425262728293018 unmodified lines49505150525354555657585960616263646566676869707172737475767778798010 unmodified lines9192939495969760 unmodified lines15815916016116216316416516616716816917017117217317417 unmodified linessys.path.insert(0, ROOT)
from config import MurliV16Configfrom data.audio_processor import AudioProcessorfrom data.dataset import MurliV16Datasetfrom data.text_cleaner import BilingualTextTokenizer, hindi_word_to_ipafrom export_onnx import export_acoustic_onnxfrom models.flow_matching import AdaLNZeroDiTBlockfrom models.tts_engine import MurliV16Enginefrom narrate import script_chunksfrom train import train
18 unmodified lines dit_count = sum(isinstance(b, AdaLNZeroDiTBlock) for b in engine.vector_field.dit_blocks) self.assertEqual(dit_count, 4)
# Verify V1.5 schwa bug fixes + preservation of tricky Hindi words # Verify V1.5 schwa bug fixes + preservation of tricky Hindi words + conjunct/CVCVC rules self.assertEqual("".join(hindi_word_to_ipa("मुरली")), "mʊɾliː") self.assertEqual("".join(hindi_word_to_ipa("लकड़ी")), "ləkɽiː") self.assertEqual("".join(hindi_word_to_ipa("लड़का")), "ləɽkaː") self.assertEqual("".join(hindi_word_to_ipa("बढ़ई")), "bəɽʰəiː") self.assertEqual("".join(hindi_word_to_ipa("राघव")), "ɾaːgʰəʋ") self.assertEqual("".join(hindi_word_to_ipa("ज्ञान")), "gjaːn̪") self.assertEqual("".join(hindi_word_to_ipa("मतलब")), "mət̪ləb") self.assertEqual("".join(hindi_word_to_ipa("प्रगति")), "pɾəgət̪ɪ")
tok = BilingualTextTokenizer(use_g2p_en=False) self.assertIn("baːɾəɦ", "".join(tok.text_to_phonemes("12 साल"))) self.assertIn("d̪əʃəmələʋ", "".join(tok.text_to_phonemes("3.5 प्रतिशत"))) en_ph = "".join(tok.text_to_phonemes("3.5 percent", language="en")) self.assertIn("pɔɪnt", en_ph) self.assertIn("pərsɛnt", en_ph)
# Verify 150 Hz F0 does not collide with unvoiced 0.0 proc = AudioProcessor(cfg.audio) t_150 = torch.linspace(0.0, 0.5, 12000) wav_150 = 0.5 * torch.sin(2.0 * torch.pi * 150.0 * t_150) _, f0_150, energy_150 = proc.extract_features(wav_150) voiced = f0_150[f0_150 > 0] self.assertGreater(voiced.numel(), 10) self.assertGreater(float(voiced.min()), 0.2) self.assertTrue(torch.isfinite(energy_150).all())
def test_multispeaker_train_synthesize_and_resume_continuity(self): with tempfile.TemporaryDirectory() as tmp:10 unmodified lines (wb, "तीन दशमलव पाँच प्रतिशत लाभ हुआ।", "iisc_f_hindi_female_spk001", 1.1), (wb, "सच्चाई से हर काम सफल होता है।", "kalita_rasa_male_01", 1.1), (wb, "सुंदरपुर में नयी सुबह आई।", "syspin_male_01", 1.1), (b"not-a-valid-wav", "खराब ऑडियो भी स्किप होना चाहिए।", "syspin_male_01", 1.1), ] pq_path = root / "shard.parquet" table = pa.table({60 unmodified lines self.assertEqual(mel.shape[1], cfg.model.mel_dim) self.assertGreater(mel.shape[2], 0)
# Verify batched B>1 padded synthesis & narrate chunking ids_short = tok.text_to_ids("नमस्ते") padded = torch.zeros((2, max(ids.numel(), ids_short.numel())), dtype=torch.long) padded[0, :ids.numel()] = ids padded[1, :ids_short.numel()] = ids_short mel_batch = engine.synthesize(padded, speaker_id=0, steps=2) self.assertEqual(mel_batch.shape[0], 2) self.assertTrue(torch.isfinite(mel_batch).all()) chunks = list(script_chunks("नमस्ते! आज मौसम अच्छा है।\n\nचलो चलते हैं।", tok)) self.assertEqual(len(chunks), 3)
with tempfile.TemporaryDirectory() as tmpdir: fe_path, cfm_path = export_acoustic_onnx(engine, tmpdir, opset=17) self.assertTrue(os.path.exists(fe_path))27 unmodified lines282930313132333463 unmodified lines98991001011011021031043 unmodified lines10810911011111111211311311411511611711842 unmodified lines1611621631621641651661674 unmodified lines17217317417517617717817918 unmodified lines19819920019720120220320472 unmodified lines27727827928028128228328428528628728828929029129229329429529629729828 unmodified lines32732832932032133033133233333433533632733733833934038 unmodified lines37938038138238338438527 unmodified lines
def generate_test_samples(model, cfg, step, speaker_to_id, vocoder_holder): if vocoder_holder.get("vocoder") is None: vocoder_holder["vocoder"] = MurliVocoder() vocoder_holder["vocoder"] = MurliVocoder(repo_id=cfg.model.vocoder_repo) vocoder_holder["tokenizer"] = BilingualTextTokenizer(use_g2p_en=False)
uploaded_ops = []63 unmodified lines
@torch.no_grad()def validate(model, loader, device, seed):def validate(model, loader, device, seed, amp=False, bf16=False): devices = [torch.cuda.current_device()] if device.type == "cuda" else [] total = frames = 0 model.eval()3 unmodified lines if devices: torch.cuda.manual_seed(seed) for batch in loader: batch = {k: v.to(device) for k, v in batch.items()} batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()} count = int(batch["mel_mask"].sum()) total += model(**batch)["cfm_loss"].item() * count with torch.autocast(device.type, dtype=torch.bfloat16 if bf16 else torch.float16, enabled=amp): cfm_val = model(**batch, cfg_drop_prob=0.0)["cfm_loss"].item() total += cfm_val * count frames += count finally: model.train()42 unmodified lines cache_dir=tc.cache_dir, audio_cfg=cfg.audio, max_samples=tc.max_samples, skip_invalid=False, skip_invalid=not getattr(args, "strict_dataset", False), ) active_speakers = sorted({r["speaker_id"] for r in dataset.rows}) if any("unknown" in s.lower() for s in active_speakers):4 unmodified lines
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)18 unmodified lines batch_size=tc.batch_size, num_workers=tc.num_workers, pin_memory=(device.type == "cuda"), persistent_workers=(tc.num_workers > 0), persistent_workers=False, collate_fn=v16_collate_fn, ) if tc.num_workers > 0:72 unmodified lines
loader = DataLoader(train_ds, sampler=order[offset:], generator=generator, **loader_opts) remaining = len(loader) loss_acc = cfm_acc = prior_acc = frm_acc = 0.0 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) loss_acc = cfm_acc = prior_acc = frm_acc = 0.0 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") loss_acc += out["loss"].item() / group_size cfm_acc += out["cfm_loss"].item() / group_size prior_acc += out["prior_loss"].item() / group_size frm_acc += out["frame_prosody_loss"].item() / group_size scaler.scale(loss).backward() offset += batch["token_ids"].size(0) clips_since_log += batch["token_ids"].size(0)28 unmodified lines 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}, Frm {out['frame_prosody_loss'].item():.3f}) | " f"Loss {loss_acc:.3f} (CFM {cfm_acc:.3f}, " f"Pr {prior_acc:.3f}, Frm {frm_acc:.3f}) | " f"{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) score = validate(model, val_loader, device, tc.seed, amp=amp, bf16=bf16) is_best = score < best if is_best: best = score38 unmodified lines p.add_argument("--sample_every", type=int) p.add_argument("--hf_backup_every", type=int) p.add_argument("--hf_sample_repo") 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")RULEBOOK_V1_6.md+1
export_onnx.py+48-29
models/flow_matching.py+10-3
models/layers.py+3-2
models/prosody_aligner.py+19-10
models/text_encoder.py+1-1
models/tts_engine.py+6-2
models/vocoder.py+9-7
narrate.py+10-5
tests/test_v16.py+31-1
train.py+20-9