File size: 12,980 Bytes
cc5e704
 
 
 
 
 
 
 
 
25ffc1f
 
cc5e704
 
 
 
25ffc1f
cc5e704
 
 
25ffc1f
cc5e704
25ffc1f
 
 
 
 
 
 
 
 
cc5e704
25ffc1f
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25ffc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5e704
 
 
 
25ffc1f
cc5e704
 
 
 
25ffc1f
cc5e704
 
25ffc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5e704
 
 
 
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
"""

Android / ONNX Runtime Exporter for Murli V1.5.

Exports opset-17 ONNX graphs with dynamic sequence shapes:

  1. murli_v15_frontend.onnx  (token_ids [1, T_text], emotion_id [1], speed [1] -> cond [1, 320, T_mel], prior_mel [1, 100, T_mel])

  2. murli_v15_cfm_step.onnx  (x [B, 100, T_mel], t [B], cond [B, 320, T_mel] -> velocity [B, 100, T_mel])

Waveform decoding uses the separate vocoder.

"""

import argparse
import json
import math
import os
from typing import Tuple

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

from config import EMOTION_TO_ID, MurliV15Config
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 MurliV15Engine
from models.vocoder import MurliVocoder


class MurliV15FrontendONNX(nn.Module):
    """Traces TextEncoder + Emotion + Duration + F0 + Energy + ConvNeXt Prior cleanly for B=1."""

    def __init__(self, engine: MurliV15Engine, 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,

        emotion_id: torch.Tensor,

        speed: torch.Tensor,

    ) -> Tuple[torch.Tensor, torch.Tensor]:
        # token_ids: [1, T_text] int64, emotion_id: [1] int64, speed: [1] float32
        text_mask = torch.ones_like(token_ids, dtype=torch.bool)
        text_feats = self.text_encoder(token_ids, text_mask=text_mask)  # [1, T_text, D]

        emo = self.pa.emotion_emb(emotion_id)  # [1, D]
        text_with_emo = text_feats + emo.unsqueeze(1)
        prior_text = self.pa.compute_prior(text_with_emo, text_mask)  # [1, T_text, 100]

        log_dur = self.pa.dur_predictor(text_feats, emo, 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, emo, mask=text_mask)
        pred_energy = self.pa.energy_predictor(text_feats, emo, mask=text_mask)
        prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)
        token_cond = text_with_emo + self.pa.prosody_proj(prosody_tok)  # [1, T_text, D]

        # Vectorized monotonic duration expansion (zero repeat_interleave / Python loops)
        cum_durs = torch.cumsum(durs, dim=1)  # [1, T_text]
        total_mel = cum_durs[0, -1]
        pos = torch.arange(total_mel, device=token_ids.device, dtype=torch.long).view(1, 1, -1)
        starts = torch.cat([cum_durs.new_zeros((1, 1)), cum_durs[:, :-1]], dim=1).unsqueeze(-1)
        ends = cum_durs.unsqueeze(-1)
        align = ((pos >= starts) & (pos < ends)).to(token_cond.dtype)  # [1, T_text, T_mel]

        cond = torch.bmm(token_cond.transpose(1, 2), align)       # [1, D, T_mel]
        prior_mel = torch.bmm(prior_text.transpose(1, 2), align)  # [1, 100, T_mel]
        return cond, prior_mel


class MurliV15CFMStepONNX(nn.Module):
    """Single OT-CFM velocity evaluation supporting batch=1 or batched CFG (batch=2)."""

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

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


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

    frontend = MurliV15FrontendONNX(engine, min_frames=engine.cfg.model.min_frames).eval()
    cfm_step = MurliV15CFMStepONNX(engine).eval()

    dummy_ids = torch.randint(1, 60, (1, 18), 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_v15_frontend.onnx")
    torch.onnx.export(
        frontend,
        (dummy_ids, dummy_emo, dummy_speed),
        frontend_path,
        opset_version=opset,
        input_names=["token_ids", "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)

    cfm_path = os.path.join(out_dir, "murli_v15_cfm_step.onnx")
    torch.onnx.export(
        cfm_step,
        (dummy_x, dummy_t, dummy_cond),
        cfm_path,
        opset_version=opset,
        input_names=["x", "t", "cond"],
        output_names=["velocity"],
        dynamic_axes={
            "x": {0: "batch", 2: "t_mel"},
            "t": {0: "batch"},
            "cond": {0: "batch", 2: "t_mel"},
            "velocity": {0: "batch", 2: "t_mel"},
        },
        dynamo=False,
    )

    # Verify ONNX Runtime parity
    with torch.no_grad():
        pt_cond, pt_prior = frontend(dummy_ids, dummy_emo, dummy_speed)
        pt_vel = cfm_step(dummy_x, dummy_t, dummy_cond)

    fe_sess = ort.InferenceSession(frontend_path, providers=["CPUExecutionProvider"])
    ort_cond, ort_prior = fe_sess.run(
        None,
        {
            "token_ids": dummy_ids.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()},
    )
    assert np.allclose(pt_vel.numpy(), ort_vel, atol=1e-4, rtol=1e-4), "CFM step parity mismatch"
    return frontend_path, cfm_path


class PureConvISTFT(nn.Module):
    """Pure ConvTranspose1d ISTFT replacement for opset-17 ONNX Runtime Mobile."""

    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)
        basis = torch.cat([cos_basis, sin_basis], dim=0).unsqueeze(1)
        self.register_buffer("basis", basis)
        self.register_buffer("win_sq", (window * window).view(1, 1, win_length))

    def forward(self, real: torch.Tensor, imag: torch.Tensor) -> torch.Tensor:
        spec_ri = torch.cat([real, imag], dim=1)
        y = F.conv_transpose1d(spec_ri, 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):
    def __init__(self, vocos_model):
        super().__init__()
        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, opset: int = 17) -> str:
    os.makedirs(out_dir, exist_ok=True)
    voc = MurliVocoder()
    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,
    )
    onnx.checker.check_model(voc_path)
    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 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: MurliV15Config, out_dir: str) -> str:
    os.makedirs(out_dir, exist_ok=True)
    tok_path = os.path.join(out_dir, "tokenizer_v15.json")
    payload = {
        "model": "Murli-V1.5",
        "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_speed": cfg.model.default_speed,
        "default_steps": 16,
        "default_cfg_scale": cfg.model.default_cfg_scale,
        "default_temperature": cfg.model.default_temperature,
        "token_to_id": TOKEN_TO_ID,
        "emotion_to_id": EMOTION_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_5")
    p.add_argument("--upload_repo", type=str, default=None)
    args = p.parse_args()

    cfg = MurliV15Config()
    engine = MurliV15Engine(cfg)
    ckpt = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
    engine.load_state_dict(ckpt["model"])
    fe, cfm = export_acoustic_onnx(engine, args.out_dir)
    voc = export_vocos_onnx(args.out_dir)
    tok_json = export_tokenizer_json(cfg, args.out_dir)
    print(f"[ONNX OK] Exported & verified:\n  - {fe}\n  - {cfm}\n  - {voc}\n  - {tok_json}")

    if args.upload_repo:
        from dotenv import load_dotenv
        from huggingface_hub import CommitOperationAdd, HfApi
        load_dotenv()
        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_v15_frontend.onnx", path_or_fileobj=fe),
            CommitOperationAdd(path_in_repo="murli_v15_cfm_step.onnx", path_or_fileobj=cfm),
            CommitOperationAdd(path_in_repo="vocos_24khz.onnx", path_or_fileobj=voc),
            CommitOperationAdd(path_in_repo="tokenizer_v15.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.5 (150k) Android ONNX models + tokenizer_v15.json",
        )
        print(f"[Uploaded ONNX Release] -> {info.commit_url}")


if __name__ == "__main__":
    main()