File size: 16,662 Bytes
870eedf
42e63f8
870eedf
 
 
 
 
 
b88688a
 
870eedf
b88688a
870eedf
 
 
 
 
b88688a
 
 
 
 
 
 
 
 
 
 
870eedf
b88688a
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
 
 
 
870eedf
 
 
 
 
 
 
42e63f8
 
 
 
 
 
870eedf
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
42e63f8
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
 
 
 
42e63f8
 
8d10455
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
 
8d10455
 
 
 
 
 
 
42e63f8
8d10455
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
42e63f8
 
 
 
 
 
 
 
 
b88688a
 
42e63f8
b88688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
 
b88688a
 
42e63f8
b88688a
 
 
 
 
42e63f8
 
 
 
 
 
b88688a
 
 
42e63f8
 
b88688a
 
 
 
 
 
 
42e63f8
 
 
b88688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870eedf
 
 
 
42e63f8
 
 
 
b88688a
870eedf
 
 
 
 
 
42e63f8
 
b88688a
 
 
 
 
42e63f8
870eedf
42e63f8
 
 
b88688a
 
 
 
 
42e63f8
 
 
 
b88688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""
Android / ONNX Runtime Exporter for Murli V1.6 (Single-Speaker syspin_male_01 & Multi-Speaker Ready).
Exports opset-17 ONNX graphs with dynamic sequence shapes:
  1. murli_v16_frontend.onnx  (token_ids [1, T_text], speaker_id [1], emotion_id [1], speed [1] -> cond [1, 320, T_mel], prior_mel [1, 100, T_mel])
  2. murli_v16_cfm_step.onnx  (x [B, 100, T_mel], t [B], cond [B, 320, T_mel], speaker_id [B] -> velocity [B, 100, T_mel])
"""

import argparse
import json
import math
import os
from typing import Dict, Optional, Tuple

import numpy as np
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F

from config import EMOTION_TO_ID, AudioConfig, ModelConfig, MurliV16Config
from data.text_cleaner import (
    HI_CONSONANTS,
    HI_INDEP_VOWELS,
    HI_MATRAS,
    ROMAN_HINDI_LEXICON,
    TOKEN_TO_ID,
    VARGA_NASAL,
)
from models.tts_engine import MurliV16Engine
from models.vocoder import MurliVocoder


class MurliV16FrontendONNX(nn.Module):
    """Traces TextEncoder + Speaker + Emotion + Duration/F0/Energy + FrameProsodyRefiner cleanly for B=1."""

    def __init__(self, engine: MurliV16Engine, min_frames: int = 2):
        super().__init__()
        self.text_encoder = engine.text_encoder
        self.pa = engine.prosody_aligner
        self.min_frames = float(min_frames)

    def forward(
        self,
        token_ids: torch.Tensor,
        speaker_id: torch.Tensor,
        emotion_id: torch.Tensor,
        speed: torch.Tensor,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        text_mask = torch.ones_like(token_ids, dtype=torch.bool)
        text_feats = self.text_encoder(token_ids, text_mask=text_mask)

        style = self.pa.speaker_emb(speaker_id) + self.pa.emotion_emb(emotion_id)  # [1, D]
        text_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_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)
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)  # [1, T_text, 2]

        cum_durs = torch.cumsum(durs, dim=1)
        total_mel = cum_durs[0, -1]
        # Scatter a token boundary at each start, then integrate to get the frame-to-token map.
        starts = cum_durs[0, :-1]
        boundaries = torch.zeros_like(torch.arange(total_mel, device=token_ids.device))
        indices = boundaries.scatter(0, starts, torch.ones_like(starts)).cumsum(0)
        expanded_h = text_with_style.index_select(1, indices)
        coarse_frame_prosody = prosody_tok.index_select(1, indices)
        mel_mask = torch.ones((1, total_mel), dtype=torch.bool, device=token_ids.device)
        refined_frame_prosody = self.pa.frame_prosody_net(
            expanded_h, coarse_frame_prosody, self.pa.prosody_proj, mask=mel_mask
        )

        cond = (expanded_h + self.pa.prosody_proj(refined_frame_prosody)).transpose(1, 2)  # [1, D, T_mel]
        prior_mel = prior_text.transpose(1, 2).index_select(2, indices)  # [1, 100, T_mel]
        return cond, prior_mel


class MurliV16CFMStepONNX(nn.Module):
    """Single Hybrid DiT+ConvNeXt OT-CFM velocity evaluation supporting batch=1 or batched CFG (batch=2)."""

    def __init__(self, engine: MurliV16Engine):
        super().__init__()
        self.vf = engine.vector_field

    def forward(
        self,
        x: torch.Tensor,
        t: torch.Tensor,
        cond: torch.Tensor,
        speaker_id: torch.Tensor,
    ) -> torch.Tensor:
        return self.vf(x, t, cond, speaker_ids=speaker_id, mask=None)


def export_acoustic_onnx(engine: MurliV16Engine, out_dir: str, opset: int = 17, speaker_id: int = 0) -> Tuple[str, str]:
    os.makedirs(out_dir, exist_ok=True)
    engine.eval()

    frontend = MurliV16FrontendONNX(engine, min_frames=engine.cfg.model.min_frames).eval()
    cfm_step = MurliV16CFMStepONNX(engine).eval()

    dummy_ids = torch.randint(1, engine.cfg.model.vocab_size, (1, 18), dtype=torch.long)
    dummy_spk = torch.tensor([speaker_id], dtype=torch.long)
    dummy_emo = torch.zeros((1,), dtype=torch.long)
    dummy_speed = torch.tensor([0.92], dtype=torch.float32)

    frontend_path = os.path.join(out_dir, "murli_v16_frontend.onnx")
    torch.onnx.export(
        frontend,
        (dummy_ids, dummy_spk, dummy_emo, dummy_speed),
        frontend_path,
        opset_version=opset,
        input_names=["token_ids", "speaker_id", "emotion_id", "speed"],
        output_names=["cond", "prior_mel"],
        dynamic_axes={
            "token_ids": {1: "t_text"},
            "cond": {2: "t_mel"},
            "prior_mel": {2: "t_mel"},
        },
        dynamo=False,
    )

    dummy_x = torch.randn((2, engine.cfg.model.mel_dim, 64), dtype=torch.float32)
    dummy_t = torch.tensor([0.25, 0.25], dtype=torch.float32)
    dummy_cond = torch.randn((2, engine.cfg.model.text_dim, 64), dtype=torch.float32)
    dummy_spk_b = torch.tensor([speaker_id, speaker_id], dtype=torch.long)

    cfm_path = os.path.join(out_dir, "murli_v16_cfm_step.onnx")
    torch.onnx.export(
        cfm_step,
        (dummy_x, dummy_t, dummy_cond, dummy_spk_b),
        cfm_path,
        opset_version=opset,
        input_names=["x", "t", "cond", "speaker_id"],
        output_names=["velocity"],
        dynamic_axes={
            "x": {0: "batch", 2: "t_mel"},
            "t": {0: "batch"},
            "cond": {0: "batch", 2: "t_mel"},
            "speaker_id": {0: "batch"},
            "velocity": {0: "batch", 2: "t_mel"},
        },
        dynamo=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 shapes
    fe_cases = [
        (dummy_ids, dummy_spk, dummy_emo, dummy_speed),
        (torch.randint(1, engine.cfg.model.vocab_size, (1, 7), dtype=torch.long), torch.tensor([speaker_id], dtype=torch.long),
         torch.tensor([min(1, engine.cfg.model.num_emotions - 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(),
            },
        )
        np.testing.assert_allclose(ort_cond, pt_cond.numpy(), atol=1e-4, rtol=1e-4, err_msg="Frontend cond parity mismatch")
        np.testing.assert_allclose(ort_prior, pt_prior.numpy(), atol=1e-4, rtol=1e-4, err_msg="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([speaker_id], 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(),
            },
        )
        np.testing.assert_allclose(ort_vel, pt_vel.numpy(), atol=1e-4, rtol=1e-4, err_msg="CFM step parity mismatch")
    return frontend_path, cfm_path


def quantize_onnx_int8(onnx_path: str, out_path: Optional[str] = None) -> str:
    """Apply dynamic QUInt8 quantization for compact Android CPU inference."""
    from onnxruntime.quantization import QuantType, quantize_dynamic

    target = out_path or onnx_path.replace(".onnx", "_int8.onnx")
    quantize_dynamic(onnx_path, target, weight_type=QuantType.QUInt8)
    return target


class PureConvISTFT(nn.Module):
    """Pure ConvTranspose1d ISTFT replacement for Vocos (opset-17 Android ORT Mobile safe)."""

    def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str):
        super().__init__()
        self.n_fft = n_fft
        self.hop_length = hop_length
        self.win_length = win_length
        self.pad = (win_length // 2) if padding == "center" else ((win_length - hop_length) // 2)

        window = torch.hann_window(win_length, dtype=torch.float32)
        n_bins = n_fft // 2 + 1
        k = torch.arange(n_bins, dtype=torch.float32).unsqueeze(1)
        n = torch.arange(win_length, dtype=torch.float32).unsqueeze(0)
        angles = 2.0 * math.pi * k * n / float(n_fft)

        scale = torch.full((n_bins, 1), 2.0 / float(n_fft), dtype=torch.float32)
        scale[0] = 1.0 / float(n_fft)
        scale[-1] = 1.0 / float(n_fft)

        cos_basis = torch.cos(angles) * scale * window.unsqueeze(0)
        sin_basis = -torch.sin(angles) * scale * window.unsqueeze(0)
        self.register_buffer("basis", torch.cat([cos_basis, sin_basis], dim=0).unsqueeze(1))
        self.register_buffer("win_sq", (window * window).view(1, 1, win_length))

    def forward(self, real: torch.Tensor, imag: torch.Tensor) -> torch.Tensor:
        y = F.conv_transpose1d(torch.cat([real, imag], dim=1), self.basis, stride=self.hop_length).squeeze(1)
        ones = real[:, :1, :] * 0.0 + 1.0
        env = F.conv_transpose1d(ones, self.win_sq, stride=self.hop_length).squeeze(1)
        if self.pad > 0:
            y = y[:, self.pad : -self.pad]
            env = env[:, self.pad : -self.pad]
        return y / torch.clamp(env, min=1e-11)


class VocosONNX(nn.Module):
    """ONNX-compatible Vocos 24kHz wrapper using PureConvISTFT (no complex irfft ops)."""

    def __init__(self, vocos_model):
        super().__init__()
        self.feature_extractor = vocos_model.feature_extractor
        self.backbone = vocos_model.backbone
        self.out = vocos_model.head.out
        istft = vocos_model.head.istft
        self.pure_istft = PureConvISTFT(
            n_fft=istft.n_fft,
            hop_length=istft.hop_length,
            win_length=istft.win_length,
            padding=istft.padding,
        )

    def forward(self, mel: torch.Tensor) -> torch.Tensor:
        feats = self.backbone(mel)
        x = self.out(feats).transpose(1, 2)
        mag, phase = x.chunk(2, dim=1)
        mag = torch.clamp(torch.exp(mag), max=100.0)
        return self.pure_istft(mag * torch.cos(phase), mag * torch.sin(phase))


def export_vocos_onnx(out_dir: str, repo_id: str = "charactr/vocos-mel-24khz", opset: int = 17) -> str:
    """Export pretrained Vocos 24kHz decoder via PureConvISTFT and verify ORT parity."""
    os.makedirs(out_dir, exist_ok=True)
    voc = MurliVocoder(repo_id=repo_id)
    vocos_model = voc.load(torch.device("cpu")).eval()
    wrapper = VocosONNX(vocos_model).eval()
    dummy_mel = torch.randn((1, 100, 80), dtype=torch.float32)
    voc_path = os.path.join(out_dir, "vocos_24khz.onnx")
    torch.onnx.export(
        wrapper,
        (dummy_mel,),
        voc_path,
        opset_version=opset,
        input_names=["mel"],
        output_names=["audio"],
        dynamic_axes={"mel": {0: "batch", 2: "t_mel"}, "audio": {0: "batch", 1: "t_samples"}},
        do_constant_folding=True,
        dynamo=False,
    )
    sess = ort.InferenceSession(voc_path, providers=["CPUExecutionProvider"])
    with torch.no_grad():
        native = voc.decode(dummy_mel).cpu().numpy()
    (ort_wav,) = sess.run(["audio"], {"mel": dummy_mel.numpy()})
    max_err = float(np.max(np.abs(native - ort_wav)))
    assert max_err < 1e-4, f"Vocos ONNX parity mismatch: {max_err}"
    print(f"[ONNX Vocoder OK] vocos_24khz.onnx ({os.path.getsize(voc_path)/(1024*1024):.2f} MiB) | max_diff={max_err:.2e}")
    return voc_path


def export_tokenizer_json(cfg: MurliV16Config, out_dir: str, speaker_to_id: Optional[Dict[str, int]] = None) -> str:
    os.makedirs(out_dir, exist_ok=True)
    tok_path = os.path.join(out_dir, "tokenizer_v16.json")
    payload = {
        "model": "Murli-V1.6",
        "sample_rate": cfg.audio.sample_rate,
        "hop_length": cfg.audio.hop_length,
        "n_mels": cfg.audio.n_mels,
        "mel_mean": cfg.audio.mel_mean,
        "mel_std": cfg.audio.mel_std,
        "min_frames": cfg.model.min_frames,
        "default_speaker_id": 0,
        "default_speed": cfg.model.default_speed,
        "default_steps": 16,
        "default_cfg_scale": cfg.model.default_cfg_scale,
        "default_temperature": cfg.model.default_temperature,
        "default_sway": -1.0,
        "colon_to_comma": True,
        "merge_short_words": 3,
        "lead_silence_ms": 150,
        "speaker_to_id": speaker_to_id or {"syspin_male_01": 0},
        "emotion_to_id": EMOTION_TO_ID,
        "token_to_id": TOKEN_TO_ID,
        "hi_consonants": HI_CONSONANTS,
        "hi_indep_vowels": HI_INDEP_VOWELS,
        "hi_matras": HI_MATRAS,
        "varga_nasal": VARGA_NASAL,
        "roman_hindi_lexicon": ROMAN_HINDI_LEXICON,
    }
    with open(tok_path, "w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False, indent=2)
    print(f"[Tokenizer OK] {tok_path}")
    return tok_path


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--checkpoint", type=str, required=True)
    p.add_argument("--out_dir", type=str, default="onnx_v1_6")
    p.add_argument("--speaker_id", type=int, default=0)
    p.add_argument("--no_ema", action="store_true")
    p.add_argument("--quantize_int8", action="store_true")
    p.add_argument("--export_vocos", action="store_true")
    p.add_argument("--upload_repo", type=str, default=None)
    args = p.parse_args()

    cfg = MurliV16Config()
    ckpt = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
    if "model_config" in ckpt:
        cfg.model = ModelConfig(**ckpt["model_config"])
    if "audio_config" in ckpt:
        cfg.audio = AudioConfig(**ckpt["audio_config"])
    # Apply current natural defaults when exporting release artifacts
    cfg.model.default_speed = MurliV16Config().model.default_speed
    cfg.model.default_temperature = MurliV16Config().model.default_temperature
    spk_map = ckpt.get("speaker_to_id") or {"syspin_male_01": 0}
    if args.speaker_id not in spk_map.values():
        raise ValueError(f"Speaker {args.speaker_id} was not trained in this checkpoint")
    engine = MurliV16Engine(cfg)
    weights = ckpt["model"] if args.no_ema else (ckpt.get("ema_model") or ckpt["model"])
    engine.load_state_dict(weights)
    fe, cfm = export_acoustic_onnx(engine, args.out_dir, speaker_id=args.speaker_id)
    tok_json = export_tokenizer_json(cfg, args.out_dir, speaker_to_id=spk_map)
    print(f"[ONNX OK] Exported & verified:\n  - {fe}\n  - {cfm}\n  - {tok_json}")
    voc_p = None
    if args.export_vocos or args.upload_repo:
        voc_p = export_vocos_onnx(args.out_dir, repo_id=cfg.model.vocoder_repo)
    if args.quantize_int8:
        q_fe = quantize_onnx_int8(fe)
        q_cfm = quantize_onnx_int8(cfm)
        print(f"[ONNX INT8] Quantized:\n  - {q_fe}\n  - {q_cfm}")

    if args.upload_repo:
        from dotenv import load_dotenv
        from huggingface_hub import CommitOperationAdd, HfApi
        load_dotenv()
        load_dotenv("../TTS_10M/.env")
        api = HfApi(token=os.getenv("HF_TOKEN"))
        api.create_repo(args.upload_repo, repo_type="model", exist_ok=True)
        ops = [
            CommitOperationAdd(path_in_repo="murli_v16_frontend.onnx", path_or_fileobj=fe),
            CommitOperationAdd(path_in_repo="murli_v16_cfm_step.onnx", path_or_fileobj=cfm),
            CommitOperationAdd(path_in_repo="vocos_24khz.onnx", path_or_fileobj=voc_p),
            CommitOperationAdd(path_in_repo="tokenizer_v16.json", path_or_fileobj=tok_json),
        ]
        info = api.create_commit(
            repo_id=args.upload_repo,
            repo_type="model",
            operations=ops,
            commit_message="Upload Murli V1.6 (150k EMA) Android ONNX release + tokenizer_v16.json",
        )
        print(f"[HF Release OK] {info.commit_url}")


if __name__ == "__main__":
    main()