Murli-V1.6-Code / tests /test_v16.py
ViuAI's picture
Fix narration quality: colon/semicolon normalization, 150ms leading silence, short clause merge, 0.95 soft limiter, speed=0.88/temp=0.88
870a8cd verified
Raw History Blame Contribute Delete
15.6 kB
"""Comprehensive unit, Hindi schwa-G2P, multi-speaker resume, and Android ONNX tests for Murli V1.6."""
import io
import os
import sys
import tempfile
import unittest
import wave
from unittest.mock import patch
from argparse import Namespace
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import torch
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from config import MurliV16Config
from data.audio_processor import AudioProcessor
from data.dataset import MurliV16Dataset, warm_cache_by_shard
from data.text_cleaner import BilingualTextTokenizer, hindi_word_to_ipa
from export_onnx import export_acoustic_onnx, quantize_onnx_int8
from models.flow_matching import AdaLNZeroDiTBlock, compute_cfm_loss, sample_ode
from models.tts_engine import MurliV16Engine
from narrate import render, script_chunks
from train import train
def _wav_bytes(samples: np.ndarray, sr: int = 24000) -> bytes:
buf = io.BytesIO()
pcm = (np.clip(samples, -1.0, 1.0) * 32767.0).astype("<i2")
with wave.open(buf, "wb") as w:
w.setparams((1, 2, sr, 0, "NONE", "not compressed"))
w.writeframes(pcm.tobytes())
return buf.getvalue()
class TestMurliV16(unittest.TestCase):
def test_hybrid_dit_architecture_and_schwa_fixes(self):
cfg = MurliV16Config()
self.assertEqual(cfg.train.data_subdirs, ["hindi_50h"])
self.assertEqual(cfg.train.target_speakers, ["syspin_male_01"])
self.assertEqual(cfg.train.language, "hi")
engine = MurliV16Engine(cfg)
n_params = sum(p.numel() for p in engine.parameters())
print(f"\n[Murli V1.6] Total acoustic params: {n_params / 1e6:.2f}M")
self.assertGreater(n_params, 26_000_000)
self.assertLess(n_params, 45_000_000)
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 + 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̪ɪ")
self.assertEqual("".join(hindi_word_to_ipa("पुत्र")), "pʊt̪ɾə")
self.assertEqual("".join(hindi_word_to_ipa("संवाद")), "sə̃ʋaːd̪")
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)
hi_loan = tok.text_to_phonemes("आज 10 pm पर AI model school गया।", language="hi")
self.assertIn("<en>", hi_loan)
self.assertIn("tɛn", "".join(hi_loan))
self.assertIn("piːɛm", "".join(hi_loan))
self.assertIn("skuːl", "".join(hi_loan))
self.assertFalse(any(a == "<sp>" and b == "<sp>" for a, b in zip(hi_loan, hi_loan[1:])))
# 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:
root = Path(tmp)
t = np.linspace(0.0, 1.1, int(24000 * 1.1), endpoint=False)
sig = 0.25 * np.sin(2.0 * np.pi * 160.0 * t)
wb = _wav_bytes(sig)
rows = [
(wb, "आज राघव बढ़ई घर लौटा।", "syspin_male_01", 1.1),
(wb, "लकड़ी की मुरली बहुत सुंदर है।", "kalita_rasa_male_01", 1.1),
(wb, "उसने मेहनत और सम्मान कमाया।", "iisc_f_hindi_female_spk001", 1.1),
(wb, "बारह साल बाद संगीत फिर गूंजा।", "syspin_male_01", 1.1),
(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({
"audio": pa.array([{"bytes": r[0]} for r in rows]),
"text": pa.array([r[1] for r in rows]),
"speaker_id": pa.array([r[2] for r in rows]),
"duration_s": pa.array([r[3] for r in rows], type=pa.float32()),
})
pq.write_table(table, pq_path)
warm_ds = MurliV16Dataset(parquet_paths=[str(pq_path)], cache_dir=str(root / "warm_cache"))
warm_cache_by_shard(warm_ds, num_workers=1)
self.assertEqual(len(list((root / "warm_cache").glob("*.pt"))), 7)
self.assertEqual(len(list((root / "warm_cache").glob("*.bad"))), 1)
# Second warmup call skips both cached valid clips and .bad markers
warm_cache_by_shard(warm_ds, num_workers=1)
with self.assertRaises(ValueError):
warm_ds._load_features(warm_ds.rows[-1])
# Verify warmed cache actually hits in _load_features (without touching parquet bytes)
cached_toks, cached_mel, _, _ = warm_ds._load_features(warm_ds.rows[0])
self.assertGreater(cached_mel.shape[1], cached_toks.numel())
def make_cfg(ckpt_dir):
c = MurliV16Config()
c.model.text_dim, c.model.text_heads, c.model.text_layers = 32, 2, 1
c.model.prosody_layers = 1
c.model.cfm_hidden_dim, c.model.cfm_blocks, c.model.cfm_attn_heads = 36, 3, 2
c.model.cfm_attn_every, c.model.cfm_time_dim = 3, 16
c.train.checkpoint_dir = str(ckpt_dir)
c.train.cache_dir = str(root / "cache")
c.train.batch_size = 2
c.train.grad_accum_steps = 1
c.train.num_workers = 0
c.train.val_every = 1
c.train.save_every = 1
c.train.sample_every = 0
c.train.hf_backup_every = 0
c.train.max_steps = 3
return c
base_args = Namespace(
subdirs=None, parquet=[str(pq_path)], target_speakers="syspin_male_01,kalita_rasa_male_01,iisc_f_hindi_female_spk001",
all_speakers=False, target_gender=None, batch_size=None, grad_accum_steps=None,
max_epochs=10, max_steps=None, num_workers=None, max_samples=None,
cache_dir=None, checkpoint_dir=None, sample_dir=None,
sample_every=None, hf_backup_every=None, hf_sample_repo=None,
resume=None, init_weights=None,
)
dir_full = root / "full"
train(base_args, make_cfg(dir_full))
full_final = torch.load(dir_full / "murli_v16_final.pt", weights_only=True)
self.assertEqual(full_final["speaker_to_id"], {
"syspin_male_01": 0,
"kalita_rasa_male_01": 1,
"iisc_f_hindi_female_spk001": 2,
})
res_args = Namespace(**vars(base_args))
res_args.resume = str(dir_full / "murli_v16_step_000001.pt")
dir_res = root / "resumed"
train(res_args, make_cfg(dir_res))
res_final = torch.load(dir_res / "murli_v16_final.pt", weights_only=True)
self.assertEqual((full_final["step"], full_final["epoch"], full_final["offset"]),
(res_final["step"], res_final["epoch"], res_final["offset"]))
self.assertTrue(all(torch.equal(v, res_final["model"][k]) for k, v in full_final["model"].items()))
self.assertIsNotNone(full_final.get("ema_model"))
self.assertTrue(all(torch.equal(v, res_final["ema_model"][k]) for k, v in full_final["ema_model"].items()))
self.assertTrue((dir_full / "metrics.jsonl").is_file())
# Default Single-Speaker Only-Hindi (syspin_male_01) training + untrained speaker rejection
single_args = Namespace(**vars(base_args))
single_args.target_speakers = None
dir_single = root / "single"
train(single_args, make_cfg(dir_single))
single_ckpt = dir_single / "murli_v16_final.pt"
single_state = torch.load(single_ckpt, weights_only=True)
self.assertEqual(single_state["speaker_to_id"], {"syspin_male_01": 0})
with self.assertRaises(ValueError):
render(str(single_ckpt), "नमस्ते।", root / "bad.wav", speaker="iisc_female")
def test_flow_loss_fp16_and_guidance(self):
class IdentityField(torch.nn.Module):
mel_dim = 100
def forward(self, x, t, cond, speaker_ids=None, mask=None):
return cond.expand_as(x)
field = IdentityField()
torch.manual_seed(17)
mel = torch.ones((2, 100, 600))
cond = torch.zeros((2, 1, 600), dtype=torch.float16, requires_grad=True)
mask = torch.ones((2, 600), dtype=torch.bool)
loss = compute_cfm_loss(field, mel, cond, mask, torch.zeros(2, dtype=torch.long), cfg_drop_prob=0)
self.assertGreater(loss.item(), 1)
loss.backward()
self.assertGreater(cond.grad.abs().sum().item(), 0)
for scale in (0, 0.5, 1, 1.3):
for solver in ("midpoint", "euler"):
output = sample_ode(field, torch.ones((1, 1, 5)), steps=2, cfg_scale=scale, temperature=0, solver=solver)
torch.testing.assert_close(output, torch.full_like(output, scale))
def test_low_pitch_and_silent_text(self):
proc = AudioProcessor()
t = torch.arange(12000) / proc.cfg.sample_rate
for hz in (50, 65, 100, 150, 440, 550):
_, pitch, _ = proc.extract_features(torch.sin(2 * torch.pi * hz * t))
estimated = float(40 * pitch[5:-5].median().exp())
self.assertAlmostEqual(estimated, hz, delta=hz * 0.025)
tokenizer = BilingualTextTokenizer(use_g2p_en=False)
self.assertEqual(tokenizer.text_to_ids("...!?").numel(), 0)
def test_cache_identity_and_storage_error(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
shard = root / "test.parquet"
t = np.arange(24000) / 24000
def write_tone(hz):
raw = _wav_bytes(0.2 * np.sin(2 * np.pi * hz * t))
table = pa.table({"audio_bytes": [raw], "text": ["hello"], "speaker": ["male"]})
pq.write_table(table, shard, compression=None, use_dictionary=False)
write_tone(150)
ds = MurliV16Dataset(parquet_paths=[str(shard)], cache_dir=str(root / "cache"))
with patch("data.dataset.atomic_save", side_effect=OSError("disk full")):
with self.assertRaisesRegex(OSError, "disk full"):
warm_cache_by_shard(ds, num_workers=1)
self.assertFalse(list((root / "cache").glob("*.bad")))
warm_cache_by_shard(ds, num_workers=1)
pt = next((root / "cache").glob("*.pt"))
pt.write_bytes(b"")
self.assertTrue(torch.isfinite(ds[0]["mel"]).all())
self.assertGreater(pt.stat().st_size, 0)
size = shard.stat().st_size
write_tone(230)
self.assertEqual(shard.stat().st_size, size)
new = MurliV16Dataset(parquet_paths=[str(shard)], cache_dir=str(root / "cache"))
self.assertNotEqual(ds.rows[0]["uid"], new.rows[0]["uid"])
def test_android_onnx_export_and_parity(self):
cfg = MurliV16Config()
self.assertEqual(cfg.train.data_subdirs, ["hindi_50h"])
self.assertEqual(cfg.train.target_speakers, ["syspin_male_01"])
self.assertEqual(cfg.train.language, "hi")
engine = MurliV16Engine(cfg)
tok = BilingualTextTokenizer(use_g2p_en=False)
ids = tok.text_to_ids("नमस्ते राघव बढ़ई")
for spk in (0, 1, 2):
mel = engine.synthesize(ids[None], speaker_id=spk, steps=2)
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)
merged_chunks = list(script_chunks("नमस्ते! आज मौसम अच्छा है।\n\nचलो चलते हैं।", tok, merge_short=True))
self.assertEqual(len(merged_chunks), 2)
self.assertNotIn(":", tok.clean_text("नाम है: पुराना; नया"))
abbr_chunks = list(script_chunks('Dr. Rao arrived early. "Hello!"', tok, language="en"))
self.assertEqual(len(abbr_chunks), 2)
self.assertEqual(abbr_chunks[0][0], "Dr. Rao arrived early.")
with tempfile.TemporaryDirectory() as tmpdir:
fe_path, cfm_path = export_acoustic_onnx(engine, tmpdir, opset=17)
self.assertTrue(os.path.exists(fe_path))
self.assertTrue(os.path.exists(cfm_path))
try:
q_cfm = quantize_onnx_int8(cfm_path)
self.assertTrue(os.path.exists(q_cfm))
self.assertLess(os.path.getsize(q_cfm), os.path.getsize(cfm_path))
except ImportError:
pass
print(
f"[ONNX Sizes] frontend={os.path.getsize(fe_path) / (1024 * 1024):.2f} MiB, "
f"cfm_step={os.path.getsize(cfm_path) / (1024 * 1024):.2f} MiB"
)
if __name__ == "__main__":
unittest.main()