File size: 15,636 Bytes
870eedf
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
8d10455
88e817e
870eedf
42e63f8
 
870eedf
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850083c
 
 
870eedf
 
 
 
 
 
 
 
 
8d10455
870eedf
 
 
 
 
8d10455
 
 
42e63f8
 
870eedf
 
 
 
8d10455
 
 
42e63f8
 
 
 
 
 
8d10455
 
 
 
 
 
 
 
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
870eedf
 
 
 
 
 
 
 
 
 
88e817e
 
 
42e63f8
 
 
 
 
850083c
 
 
88e817e
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870eedf
 
 
850083c
 
 
870eedf
 
 
 
 
 
 
 
8d10455
 
 
 
 
 
 
 
 
 
870a8cd
 
 
42e63f8
 
 
8d10455
870eedf
 
 
 
42e63f8
 
 
 
 
 
870eedf
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""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()