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 lines46474845 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`.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 lines41424344454647484986 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816940 unmodified linestext_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()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 linesdynamo=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"])(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"return frontend_path, cfm_path40 unmodified lines4142434445464748495086 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718840 unmodified linestext_with_style = text_feats + style.unsqueeze(1)prior_text = self.pa.compute_prior(text_with_style, text_mask)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_safedurs = 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 linesdynamo=False,)fe_sess = ort.InferenceSession(frontend_path, providers=["CPUExecutionProvider"])cfm_sess = ort.InferenceSession(cfm_path, providers=["CPUExecutionProvider"])# Verify parity across both export dummy shapes and alternative dynamic sequence/batch shapesfe_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": 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 lines747576777879808182838468 unmodified lines1531541551561571582 unmodified lines1611621631641651664 unmodified lines17117217317417517617717817918073 unmodified linesConvNeXt1DBlock(hidden_dim, kernel_size=kernel_size, mult=3)for _ in range(num_blocks)])# AdaLN scale+shift conditioning per ConvNeXt blockself.conv_ada = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim * 2)for _ in range(num_blocks)])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 linessteps: int = 48,cfg_scale: float = 1.3,temperature: float = 0.90,) -> torch.Tensor:bsz, _, t_mel = cond.shapedevice = cond.device2 unmodified linesspeaker_ids = torch.zeros((bsz,), dtype=torch.long, device=device)x = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperaturedt = 1.0 / float(steps)null_cond = torch.zeros_like(cond)4 unmodified linest_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)v_cond, v_uncond = vector_field(x_in, t_in, c_in, speaker_ids=s_in, mask=None).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)x = x + v * dtreturn x73 unmodified lines747576777879808182838485868768 unmodified lines1561571581591601611622 unmodified lines1651661671681691701711724 unmodified lines17717817918018118218318418518618773 unmodified linesConvNeXt1DBlock(hidden_dim, kernel_size=kernel_size, mult=3)for _ in range(num_blocks)])# 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 linessteps: int = 48,cfg_scale: float = 1.3,temperature: float = 0.90,mask: Optional[torch.Tensor] = None,) -> torch.Tensor:bsz, _, t_mel = cond.shapedevice = cond.device2 unmodified linesspeaker_ids = torch.zeros((bsz,), dtype=torch.long, device=device)x = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperatureif mask is not None:x = x * mask.unsqueeze(1).to(dtype)dt = 1.0 / float(steps)null_cond = torch.zeros_like(cond)4 unmodified linest_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 Nonev_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=mask)x = x + v * dtreturn x
12345154 unmodified lines160161162163164165166"""Shared 2026 Transformer & ConvNeXt-V2 Building Blocks for Murli V2.0.Includes RMSNorm, SwiGLU MLP, Rotary Positional Embeddings (RoPE), SDPA Attention,and Mask-Aware ConvNeXt-V2 1D blocks."""154 unmodified linesh = 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)nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)h = self.grn_gamma * (h * nx) + self.grn_beta + hout = residual + self.pw2(h)12345154 unmodified lines160161162163164165166167"""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 linesh = F.gelu(self.pw1(h))if mask is not None:h = h * mask.unsqueeze(-1).to(h.dtype)# Compute squared L2 in FP32 to avoid FP16 overflow and 0/0 NaN gradientsgx = 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 + hout = residual + self.pw2(h)
24 unmodified lines25262728293031184 unmodified lines2162172182192202212226 unmodified lines22923023123223323423523623 unmodified lines2602612622632642652662672682692702712722 unmodified lines27527627727827928028128228328424 unmodified linesfor 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[0, 0] = val_np[b, 0, 0]for y in range(1, ty):lo = max(0, tx - (ty - y))184 unmodified linesgt_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_safegt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safepred_log_dur = self.dur_predictor(text_feats, style, mask=text_mask)6 unmodified linesf0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / t_denomenergy_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 resolutionprosody_tok = torch.stack([pred_f0, pred_energy], dim=-1) # [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 linesemotion_ids: torch.Tensor,speed: float = 0.92,min_frames: int = 2,) -> Tuple[torch.Tensor, torch.Tensor]: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()durs = durs * text_mask.long()pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)2 unmodified linesexpanded_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)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)return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)24 unmodified lines25262728293031184 unmodified lines2162172182192202212222232242256 unmodified lines23223323423523623723823923 unmodified lines2632642652662672682692702712722732742752762 unmodified lines27928028128228328428528628728828929029129229324 unmodified linesfor b in prange(val_np.shape[0]):tx = t_xs[b]ty = t_ys[b]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 linesgt_log_dur = torch.log(gt_dur.clamp(min=1.0))dur_safe = gt_dur.clamp(min=1.0)# Average F0 over voiced frames only so unvoiced frames inside a token do not drag pitch downvuv = (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_tokgt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safepred_log_dur = self.dur_predictor(text_feats, style, mask=text_mask)6 unmodified linesf0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / t_denomenergy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / t_denom# Expand detached coarse prosody predictions and refine smoothly at frame resolutionprosody_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 linesemotion_ids: torch.Tensor,speed: float = 0.92,min_frames: int = 2,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).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 linesexpanded_h = expand_by_durations(text_with_style, durs)coarse_frame_prosody = expand_by_durations(prosody_tok, durs)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)m_f = mel_mask.unsqueeze(-1).to(expanded_h.dtype)cond_expanded = (expanded_h + self.prosody_proj(refined_frame_prosody)) * m_fprior_expanded = expand_by_durations(prior_text, durs, max_len=t_mel) * m_fif return_mask:return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2), mel_maskreturn cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)
12345"""Murli V2.0 Bilingual Text & Phoneme Encoder.Combines local ConvNeXt-V2 phonetic boundary blocks with a deep RoPE SwiGLU Transformer."""12345"""Murli V1.6 Bilingual Text & Phoneme Encoder.Combines local ConvNeXt-V2 phonetic boundary blocks with a deep RoPE SwiGLU Transformer."""
56 unmodified lines57585960616213 unmodified lines7677787980818283848586878840 unmodified lines1291301311321331341351361371381391401412 unmodified lines14414514614714856 unmodified linesenergy_target: torch.Tensor,speaker_ids: Optional[torch.Tensor] = None,emotion_ids: Optional[torch.Tensor] = None,) -> Dict[str, torch.Tensor]:bsz = token_ids.shape[0]if speaker_ids is None:13 unmodified linesenergy_target=energy_target,)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,)tc = self.cfg.train40 unmodified linesspeaker_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(text_feats=text_feats,text_mask=text_mask,speaker_ids=speaker_ids,emotion_ids=emotion_ids,speed=speed,min_frames=m.min_frames,)mel_denorm = sample_ode(self.vector_field,2 unmodified linessteps=steps,cfg_scale=cfg_scale,temperature=temperature,)return mel_denorm * self.cfg.audio.mel_std + self.cfg.audio.mel_mean56 unmodified lines5758596061626313 unmodified lines777879808182838485868788899040 unmodified lines1311321331341351361371381391401411421431442 unmodified lines14714814915015115256 unmodified linesenergy_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 linesenergy_target=energy_target,)drop_p = self.cfg.model.cfg_drop_prob if cfg_drop_prob is None else cfg_drop_probcfm_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=drop_p,)tc = self.cfg.train40 unmodified linesspeaker_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, _, 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 linessteps=steps,cfg_scale=cfg_scale,temperature=temperature,mask=mel_mask,)return mel_denorm * self.cfg.audio.mel_std + self.cfg.audio.mel_mean
123456789101112131415163 unmodified lines2021222324252627281 unmodified line3031323334353637"""Murli V2.0 Neural Vocoder Wrapper.Supports Vocos 24kHz (100 HTK mel bins) by default and optional BigVGAN-v2 24kHz 100-band backend."""import torchimport torch.nn as nnclass MurliVocoder(nn.Module):def __init__(self, backend: str = "vocos"):super().__init__()self.backend = backendself.model = Noneself.sample_rate = 240003 unmodified linesif self.backend == "bigvgan_v2":import bigvganmodel = bigvgan.BigVGAN.from_pretrained("nvidia/bigvgan_v2_24khz_100band_256x", use_cuda_kernel=False).to(device).eval()model.remove_weight_norm()self.model = modelreturn model1 unmodified lineraise ValueError(f"Unknown vocoder: {self.backend}")from vocos import Vocosprint("Loading pretrained Vocos 24kHz (charactr/vocos-mel-24khz)...")self.model = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device).eval()return self.model@torch.no_grad()1234567891011121314151617183 unmodified lines22232425262728291 unmodified line313233343536373839"""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 Optionalimport torchimport torch.nn as nnclass MurliVocoder(nn.Module):def __init__(self, backend: str = "vocos", repo_id: Optional[str] = None):super().__init__()self.backend = backendself.repo_id = repo_idself.model = Noneself.sample_rate = 240003 unmodified linesif self.backend == "bigvgan_v2":import bigvganrepo = 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 = modelreturn model1 unmodified lineraise ValueError(f"Unknown vocoder: {self.backend}")from vocos import Vocosrepo = 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 lines3435363738394041424344454689 unmodified lines13613713813914014114233 unmodified linesparts = []for sentence in filter(str.strip, sentences):words = []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:raise ValueError("A single word exceeds the model chunk limit")words.append(word)if words:parts.append((" ".join(words), 120))if parts:89 unmodified linesdel statemodel.to(device).eval()tokenizer = BilingualTextTokenizer(use_g2p_en=False)vocoder = MurliVocoder()render_with_model(model, tokenizer, vocoder, cfg, text, destination, speaker_id=speaker_id, emotion=emotion, speed=speed)33 unmodified lines34353637383940414243444546474849505189 unmodified lines14114214314414514614733 unmodified linesparts = []for sentence in filter(str.strip, sentences):words = []approx_tokens = 3for word in sentence.split():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 = 3words.append(word)approx_tokens += max(1, w_len - 2)if words:parts.append((" ".join(words), 120))if parts:89 unmodified linesdel statemodel.to(device).eval()tokenizer = BilingualTextTokenizer(use_g2p_en=False)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 lines181920212223242526272818 unmodified lines4748495051525354555657585960616210 unmodified lines73747576777860 unmodified lines13914014114214314417 unmodified linessys.path.insert(0, ROOT)from config import MurliV16Configfrom 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 train import train18 unmodified linesdit_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 wordsself.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ʰəʋ")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 प्रतिशत")))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),]pq_path = root / "shard.parquet"table = pa.table({60 unmodified linesself.assertEqual(mel.shape[1], cfg.model.mel_dim)self.assertGreater(mel.shape[2], 0)with tempfile.TemporaryDirectory() as tmpdir:fe_path, cfm_path = export_acoustic_onnx(engine, tmpdir, opset=17)self.assertTrue(os.path.exists(fe_path))17 unmodified lines1819202122232425262728293018 unmodified lines495051525354555657585960616263646566676869707172737475767778798010 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 train18 unmodified linesdit_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 + conjunct/CVCVC rulesself.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.0proc = 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 linesself.assertEqual(mel.shape[1], cfg.model.mel_dim)self.assertGreater(mel.shape[2], 0)# Verify batched B>1 padded synthesis & narrate chunkingids_short = tok.text_to_ids("नमस्ते")padded = torch.zeros((2, max(ids.numel(), ids_short.numel())), dtype=torch.long)padded[0, :ids.numel()] = idspadded[1, :ids_short.numel()] = ids_shortmel_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 lines2829303132333463 unmodified lines98991001011021031043 unmodified lines10810911011111211311411511642 unmodified lines1591601611621631641654 unmodified lines17017117217317417518 unmodified lines19419519619719819920072 unmodified lines27327427527627727827928028128228328428528628728828 unmodified lines31731831932032132232332432532632732832933038 unmodified lines36937037137237337427 unmodified linesdef generate_test_samples(model, cfg, step, speaker_to_id, vocoder_holder):if vocoder_holder.get("vocoder") is None:vocoder_holder["vocoder"] = MurliVocoder()vocoder_holder["tokenizer"] = BilingualTextTokenizer(use_g2p_en=False)uploaded_ops = []63 unmodified lines@torch.no_grad()def validate(model, loader, device, seed):devices = [torch.cuda.current_device()] if device.type == "cuda" else []total = frames = 0model.eval()3 unmodified linesif 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() * countframes += countfinally:model.train()42 unmodified linescache_dir=tc.cache_dir,audio_cfg=cfg.audio,max_samples=tc.max_samples,skip_invalid=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 linesspk_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}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 linesbatch_size=tc.batch_size,num_workers=tc.num_workers,pin_memory=(device.type == "cuda"),persistent_workers=(tc.num_workers > 0),collate_fn=v16_collate_fn,)if tc.num_workers > 0:72 unmodified linesloader = 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_stepsif 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_sizeif 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)28 unmodified lineseta_h = (tc.max_steps - step) / max(step_rate, 1e-6) / 3600.0print(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"{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 < bestif is_best:best = score38 unmodified linesp.add_argument("--sample_every", type=int)p.add_argument("--hf_backup_every", type=int)p.add_argument("--hf_sample_repo")group = p.add_mutually_exclusive_group()group.add_argument("--resume")group.add_argument("--init_weights")27 unmodified lines2829303132333463 unmodified lines98991001011021031043 unmodified lines10810911011111211311411511611711842 unmodified lines1611621631641651661674 unmodified lines17217317417517617717817918 unmodified lines19819920020120220320472 unmodified lines27727827928028128228328428528628728828929029129229329429529629729828 unmodified lines32732832933033133233333433533633733833934038 unmodified lines37938038138238338438527 unmodified linesdef 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 = []63 unmodified lines@torch.no_grad()def validate(model, loader, device, seed, amp=False, bf16=False):devices = [torch.cuda.current_device()] if device.type == "cuda" else []total = frames = 0model.eval()3 unmodified linesif devices:torch.cuda.manual_seed(seed)for batch in loader:batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}count = int(batch["mel_mask"].sum())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 * countframes += countfinally:model.train()42 unmodified linescache_dir=tc.cache_dir,audio_cfg=cfg.audio,max_samples=tc.max_samples,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 linesspk_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 linesbatch_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:72 unmodified linesloader = DataLoader(train_ds, sampler=order[offset:], generator=generator, **loader_opts)remaining = len(loader)loss_acc = cfm_acc = prior_acc = frm_acc = 0.0for batch_idx, batch in enumerate(loader):group_idx = batch_idx % tc.grad_accum_stepsif group_idx == 0:group_size = min(tc.grad_accum_steps, remaining - batch_idx)loss_acc = cfm_acc = prior_acc = frm_acc = 0.0batch = {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_sizeif not torch.isfinite(loss):raise FloatingPointError(f"Nonfinite training loss after {step} updates")loss_acc += out["loss"].item() / group_sizecfm_acc += out["cfm_loss"].item() / group_sizeprior_acc += out["prior_loss"].item() / group_sizefrm_acc += out["frame_prosody_loss"].item() / group_sizescaler.scale(loss).backward()offset += batch["token_ids"].size(0)clips_since_log += batch["token_ids"].size(0)28 unmodified lineseta_h = (tc.max_steps - step) / max(step_rate, 1e-6) / 3600.0print(f"Ep {epoch + 1}/{tc.max_epochs} | Step {step}/{tc.max_steps} | "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, amp=amp, bf16=bf16)is_best = score < bestif is_best:best = score38 unmodified linesp.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