File size: 11,963 Bytes
a5b5524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Android / ONNX Runtime Exporter for Murli V1.0 (`ViuAI/Murli-V1.0`).
Exports 3 self-contained opset-17 ONNX graphs with dynamic sequence shapes:
  1. murli_frontend.onnx  (text_ids [1, T_text], speed [1] -> cond [1, 256, T_mel], prior_mel [1, 100, T_mel])
  2. murli_cfm_step.onnx  (x [B, 100, T_mel], t [B], cond [B, 256, T_mel] -> velocity [B, 100, T_mel])
  3. vocos_24khz.onnx     (mel [B, 100, T_mel] -> audio [B, T_samples])

Verifies numerical parity across multiple dynamic shapes using onnxruntime before finishing,
and can optionally upload all 3 ONNX files to `ViuAI/Murli-V1.0`.
"""

import argparse
import math
import os
import tempfile
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 dotenv import load_dotenv
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download

from config import TTS10MConfig
from models.tts_engine import TTS10MEngine
from utils.checkpoint import load_checkpoint


class MurliFrontendONNX(nn.Module):
    """Traces TextEncoder + DurationPredictor + Prior + Duration Expansion cleanly for B=1."""

    def __init__(self, engine: TTS10MEngine, min_frames: int = 2):
        super().__init__()
        self.text_encoder = engine.text_encoder
        self.duration_predictor = engine.duration_predictor
        self.prior_proj = engine.prior_proj
        self.min_frames = float(min_frames)

    def forward(self, text_ids: torch.Tensor, speed: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        # text_ids: [1, T_text] int64, speed: [1] float32
        t_text = text_ids.shape[1]
        text_lengths = text_ids.new_full((1,), t_text, dtype=torch.long)
        text_mask = torch.ones_like(text_ids, dtype=torch.bool)

        h_text = self.text_encoder(text_ids, text_lengths=text_lengths)  # [1, T_text, 256]
        log_dur = self.duration_predictor(h_text, mask=text_mask)       # [1, T_text]
        dur_raw = torch.exp(log_dur) / speed.view(1, 1)
        durs = torch.clamp(torch.round(dur_raw), min=self.min_frames).long()

        # Vectorized monotonic duration expansion (zero repeat_interleave / Python loop)
        cum_durs = torch.cumsum(durs, dim=1)                            # [1, T_text]
        total_mel = cum_durs[0, -1]
        pos = torch.arange(total_mel, device=text_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(h_text.dtype)       # [1, T_text, T_mel]

        cond = torch.bmm(h_text.transpose(1, 2), align)                 # [1, 256, T_mel]
        prior_text = self.prior_proj(h_text)                            # [1, T_text, 100]
        prior_mel = torch.bmm(prior_text.transpose(1, 2), align)        # [1, 100, T_mel]
        return cond, prior_mel


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

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


class PureConvISTFT(nn.Module):
    """
    Pure real-valued ConvTranspose1d replacement for Vocos `ISTFT` (`irfft` + `fold`)
    using precomputed DFT cosine/sine basis and Hann^2 overlap-add normalization.
    Exports cleanly to standard opset-17 ONNX Runtime Mobile with ~1e-5 parity.
    """

    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.padding = padding
        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)

        # Normalize to match torch.fft.irfft(..., norm="backward") * hann_window
        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)  # [n_fft + 2, 1, win_length]
        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:
        # real, imag: [B, n_bins, T]
        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):
    """ONNX-compatible Vocos 24kHz wrapper replacing complex `ISTFT` with `PureConvISTFT`."""

    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:
        # mel: [B, 100, T]
        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)
        real = mag * torch.cos(phase)
        imag = mag * torch.sin(phase)
        return self.pure_istft(real, imag)


def _export_and_verify(
    model: nn.Module,
    sample_inputs: tuple,
    input_names: list,
    output_names: list,
    dynamic_axes: dict,
    out_path: str,
    test_cases: list,
) -> float:
    model.eval()
    torch.onnx.export(
        model,
        sample_inputs,
        out_path,
        input_names=input_names,
        output_names=output_names,
        dynamic_axes=dynamic_axes,
        opset_version=17,
        do_constant_folding=True,
        dynamo=False,
    )
    onnx.checker.check_model(out_path)
    sess = ort.InferenceSession(out_path, providers=["CPUExecutionProvider"])

    max_err = 0.0
    for case in test_cases:
        with torch.no_grad():
            pt_out = model(*case)
            if not isinstance(pt_out, tuple):
                pt_out = (pt_out,)
        ort_inputs = {name: t.cpu().numpy() for name, t in zip(input_names, case)}
        ort_out = sess.run(output_names, ort_inputs)
        for p, o in zip(pt_out, ort_out):
            diff = float(np.max(np.abs(p.cpu().numpy() - o)))
            max_err = max(max_err, diff)
            assert np.isfinite(o).all(), f"Non-finite values in {out_path}"
    size_mb = os.path.getsize(out_path) / (1024 * 1024)
    print(f"[ONNX OK] {os.path.basename(out_path)} ({size_mb:.2f} MB) | max_abs_diff vs PyTorch = {max_err:.2e}")
    return max_err


def export_all_onnx(checkpoint_path: str, out_dir: str, upload_repo: str = None, token: str = None) -> None:
    os.makedirs(out_dir, exist_ok=True)
    cfg = TTS10MConfig()
    engine = load_checkpoint(TTS10MEngine(cfg.model, cfg.training), checkpoint_path, device="cpu").eval()
    engine.vocoder.load_vocoder(torch.device("cpu"))

    # 1. Frontend ONNX
    frontend = MurliFrontendONNX(engine, min_frames=2).eval()
    t1 = (torch.randint(2, 200, (1, 18), dtype=torch.long), torch.tensor([0.92], dtype=torch.float32))
    t2 = (torch.randint(2, 200, (1, 35), dtype=torch.long), torch.tensor([1.00], dtype=torch.float32))
    fe_path = os.path.join(out_dir, "murli_frontend.onnx")
    _export_and_verify(
        frontend,
        t1,
        ["text_ids", "speed"],
        ["cond", "prior_mel"],
        {
            "text_ids": {1: "t_text"},
            "cond": {2: "t_mel"},
            "prior_mel": {2: "t_mel"},
        },
        fe_path,
        [t1, t2],
    )

    # 2. CFM Step ONNX
    cfm_step = MurliCFMStepONNX(engine).eval()
    c1 = (torch.randn(1, 100, 80), torch.tensor([0.35], dtype=torch.float32), torch.randn(1, 256, 80))
    c2 = (torch.randn(2, 100, 140), torch.tensor([0.80, 0.80], dtype=torch.float32), torch.randn(2, 256, 140))
    cfm_path = os.path.join(out_dir, "murli_cfm_step.onnx")
    _export_and_verify(
        cfm_step,
        c1,
        ["x", "t", "cond"],
        ["velocity"],
        {
            "x": {0: "batch", 2: "t_mel"},
            "t": {0: "batch"},
            "cond": {0: "batch", 2: "t_mel"},
            "velocity": {0: "batch", 2: "t_mel"},
        },
        cfm_path,
        [c1, c2],
    )

    # 3. Vocos 24kHz ONNX (verified directly against official PyTorch Vocos.decode!)
    vocos_onnx = VocosONNX(engine.vocoder.model).eval()
    v1 = (torch.randn(1, 100, 64),)
    v2 = (torch.randn(1, 100, 110),)
    voc_path = os.path.join(out_dir, "vocos_24khz.onnx")
    _export_and_verify(
        vocos_onnx,
        v1,
        ["mel"],
        ["audio"],
        {"mel": {0: "batch", 2: "t_mel"}, "audio": {0: "batch", 1: "t_samples"}},
        voc_path,
        [v1, v2],
    )

    # Cross-check PureConvISTFT VocosONNX directly against native engine.vocoder.decode!
    sess_voc = ort.InferenceSession(voc_path, providers=["CPUExecutionProvider"])
    for mel_in in [v1[0], v2[0]]:
        with torch.no_grad():
            native_wav = engine.vocoder.decode(mel_in).cpu().numpy()
        onnx_wav = sess_voc.run(["audio"], {"mel": mel_in.numpy()})[0]
        assert native_wav.shape == onnx_wav.shape, f"Shape mismatch {native_wav.shape} vs {onnx_wav.shape}"
        voc_err = float(np.max(np.abs(native_wav - onnx_wav)))
        print(f"  Vocos iSTFT parity check (shape={onnx_wav.shape}): max_abs_diff = {voc_err:.2e}")
        assert voc_err < 1e-4, f"Vocos ONNX diverged from PyTorch decode: {voc_err}"

    if upload_repo:
        api = HfApi(token=token)
        ops = [
            CommitOperationAdd(path_in_repo="murli_frontend.onnx", path_or_fileobj=fe_path),
            CommitOperationAdd(path_in_repo="murli_cfm_step.onnx", path_or_fileobj=cfm_path),
            CommitOperationAdd(path_in_repo="vocos_24khz.onnx", path_or_fileobj=voc_path),
        ]
        info = api.create_commit(
            repo_id=upload_repo,
            repo_type="model",
            operations=ops,
            commit_message="Upload Android ONNX runtime graphs (murli_frontend, murli_cfm_step, vocos_24khz)",
        )
        print(f"Uploaded all 3 ONNX files -> {info.commit_url}")


if __name__ == "__main__":
    load_dotenv()
    p = argparse.ArgumentParser(description="Export Murli V1.0 to 3 Android ONNX models")
    p.add_argument("--checkpoint", type=str, default=None, help="Path to model.safetensors (auto-downloads from ViuAI/Murli-V1.0 if omitted)")
    p.add_argument("--out_dir", type=str, default="onnx_export")
    p.add_argument("--upload_repo", type=str, default=None, help="Optional HF repo_id to upload the 3 ONNX files (e.g. ViuAI/Murli-V1.0)")
    args = p.parse_args()

    tok = os.environ.get("HF_TOKEN")
    ckpt = args.checkpoint or hf_hub_download("ViuAI/Murli-V1.0", "model.safetensors", token=tok)
    export_all_onnx(ckpt, args.out_dir, upload_repo=args.upload_repo, token=tok)