File size: 12,214 Bytes
e888931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db88d9c
 
 
 
e888931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bd05
e888931
 
 
 
 
 
a11bd05
 
 
e888931
 
c6333a5
e888931
 
c6333a5
a11bd05
 
 
 
e888931
a11bd05
c6333a5
e888931
 
c6333a5
a11bd05
c6333a5
e888931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db88d9c
e888931
 
 
db88d9c
 
e888931
a11bd05
 
e888931
db88d9c
e888931
 
 
 
 
 
 
 
 
 
c6333a5
 
e888931
 
 
 
 
 
 
 
db88d9c
 
e888931
 
 
 
 
 
0daa51d
 
 
 
 
 
 
e888931
 
0daa51d
 
 
 
 
 
 
 
e888931
0daa51d
e888931
 
0daa51d
e888931
 
0daa51d
 
 
 
 
e888931
0daa51d
e888931
0daa51d
c6333a5
e888931
 
0daa51d
e888931
 
 
0daa51d
db88d9c
e888931
db88d9c
 
0daa51d
 
 
 
 
 
 
 
 
e888931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bd05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e888931
 
 
 
 
 
 
 
 
 
 
a11bd05
 
e888931
 
 
 
 
 
 
 
a11bd05
 
 
e888931
 
 
 
 
 
 
 
 
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
"""Export the browser graphs: LM, aggregator, vocoder.

The original export notebook is gone and took its graphs with it, so this is
written against the call patterns that are known to work in inference
(`ar_generate` in train_voices.py): `mm.model(...)` for the backbone,
`mm.linear_proj_audio`, `mm.audio.decode` for the waveform.

Every graph is validated against PyTorch before anything is quantised, and each
section is isolated so one failure does not hide the others.

Contracts (host does the rest):
  lm          inputs_embeds[B,S,896], mask4d[B,1,S,P], position_ids[B,S],
              past_k/v per layer -> hidden[B,S,896], new past_k/v
  aggregator  latent[B,1,64] -> embeds[B,1,896]
  voc         latent[B,T,64] -> waveform[B,1,N]

Stages: STAGE=lm|agg|voc|all, then quantisation runs over whatever exists.
"""
import json
import os
import sys
import time
import traceback
from pathlib import Path

import numpy as np

ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
REPO = ROOT / "Ming-3.0-tts"
MODEL = ROOT / "Ming-3.0-tts-0.5b"
OUT = ROOT / "export"
STAGE = os.environ.get("STAGE", "all")

for p in (OUT,):
    p.mkdir(parents=True, exist_ok=True)


def log(msg: str) -> None:
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def patch_fp32() -> None:
    for name in ("ming_tts.py", "modeling_bailingmm.py"):
        p = REPO / name
        s = p.read_text()
        s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
        s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
        s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
        p.write_text(s)


def np_(t):
    return t.detach().cpu().numpy()


def cosine(a, b) -> float:
    a = np.asarray(a, dtype=np.float64).reshape(-1)
    b = np.asarray(b, dtype=np.float64).reshape(-1)
    na, nb = np.linalg.norm(a), np.linalg.norm(b)
    if na == 0 or nb == 0:
        return 0.0
    return float(a @ b / (na * nb))


def stage_lm(mm, torch) -> dict:
    """One graph for both prefill and decode: past_len and seq_len are dynamic."""
    import onnxruntime as ort

    lm = mm.model
    cfg = lm.config
    n = cfg.num_hidden_layers
    kv_heads = getattr(cfg, "num_key_value_heads", cfg.num_attention_heads)
    head_dim = cfg.hidden_size // cfg.num_attention_heads
    log(f"lm: {n} layers, {kv_heads} kv heads, head_dim {head_dim}, "
        f"hidden {cfg.hidden_size}, vocab {cfg.vocab_size}")

    class Wrapper(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.lm = lm

        def forward(self, inputs_embeds, attention_mask, position_ids, *past):
            # past arrives as [k0..k(n-1), v0..v(n-1)]; keep that order on the way out too.
            k, v = past[:n], past[n:]
            cache = tuple((k[i], v[i]) for i in range(n))
            out = self.lm(inputs_embeds=inputs_embeds, attention_mask=attention_mask,
                          position_ids=position_ids, past_key_values=cache,
                          use_cache=True, output_hidden_states=True, return_dict=True)
            new = out.past_key_values
            ks = [new[i][0] for i in range(n)]
            vs = [new[i][1] for i in range(n)]
            return (out.hidden_states[-1], *ks, *vs)

    wrapper = Wrapper().float().eval()
    dev = next(lm.parameters()).device
    B, S, P = 1, 4, 6
    H = cfg.hidden_size
    embeds = torch.randn(B, S, H, device=dev)
    # Qwen2 adds this mask to the attention scores, so blocked positions need a
    # large negative value; 0/1 would let the model attend to the future.
    neg = torch.finfo(torch.float32).min / 2
    mask = torch.full((B, 1, S, P + S), neg, device=dev)
    for i in range(S):
        mask[:, :, i, :P + i + 1] = 0.0
    pos = torch.arange(P, P + S, device=dev).unsqueeze(0)
    past = []
    for _ in range(n):
        past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))
    for _ in range(n):
        past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))

    with torch.no_grad():
        ref = wrapper(embeds, mask, pos, *past)

    names_in = ["inputs_embeds", "attention_mask", "position_ids"]
    names_in += [f"past_k_{i}" for i in range(n)] + [f"past_v_{i}" for i in range(n)]
    names_out = ["hidden"]
    names_out += [f"out_k_{i}" for i in range(n)] + [f"out_v_{i}" for i in range(n)]

    dyn = {"inputs_embeds": {1: "s"}, "attention_mask": {2: "s", 3: "p"},
           "position_ids": {1: "s"}}
    for i in range(n):
        dyn[f"past_k_{i}"] = {2: "p"}
        dyn[f"past_v_{i}"] = {2: "p"}

    path = OUT / "lm.onnx"
    log(f"exporting {path.name} (this takes a few minutes)")
    torch.onnx.export(wrapper, (embeds, mask, pos, *past), str(path),
                      input_names=names_in, output_names=names_out,
                      dynamic_axes=dyn, opset_version=20, do_constant_folding=True,
                      dynamo=False)
    log(f"{path.name}: {path.stat().st_size / 1e6:.0f} MB")

    sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
    feeds = {"inputs_embeds": np_(embeds), "attention_mask": np_(mask),
             "position_ids": np_(pos)}
    for i in range(n):
        feeds[f"past_k_{i}"] = np_(past[i])
        feeds[f"past_v_{i}"] = np_(past[n + i])
    got = sess.run(None, feeds)
    cos = [cosine(np_(ref[i]), got[i]) for i in range(3)]
    log(f"validate hidden cos={cos[0]:.6f} k0={cos[1]:.6f} v0={cos[2]:.6f}")
    return {"graph": "lm", "mb": round(path.stat().st_size / 1e6, 1),
            "cos_hidden": cos[0], "layers": n}


def stage_agg(mm, torch) -> dict:
    import onnxruntime as ort

    lin = mm.linear_proj_audio
    dim_in = mm.latent_dim
    dev = next(lin.parameters()).device
    dummy = torch.randn(1, 1, dim_in, device=dev)
    with torch.no_grad():
        ref = lin(dummy)
    path = OUT / "aggregator.onnx"
    torch.onnx.export(lin.float().eval(), (dummy,), str(path),
                      input_names=["latent"], output_names=["embeds"],
                      dynamic_axes={"latent": {1: "t"}}, opset_version=20,
                      do_constant_folding=True, dynamo=False)
    sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
    got = sess.run(None, {"latent": np_(dummy)})[0]
    c = cosine(np_(ref), got)
    log(f"aggregator.onnx {path.stat().st_size / 1e6:.0f} MB cos={c:.6f}")
    return {"graph": "aggregator", "mb": round(path.stat().st_size / 1e6, 1),
            "cos": c, "dim_in": dim_in, "dim_out": int(ref.shape[-1])}


def stage_voc(mm, torch) -> dict:
    """Export the vocoder up to the ISTFT head's linear projection.

    `decode` ends in a complex STFT, which ONNX cannot represent. The head does
    `linear -> (mag, phase) -> complex -> istft`, so the last real-valued tensor
    is the projection output. The host does the rest, matching the documented
    `voc -> spec` contract.
    """
    import onnxruntime as ort

    dec = mm.audio.decoder
    head = dec.head
    lin = getattr(head, "linear", None)
    if lin is None:
        lin = next((m for m in head.modules() if isinstance(m, torch.nn.Linear)), None)
    if lin is None:
        raise RuntimeError("could not find the ISTFT head projection layer")
    log(f"head projection: out_features={getattr(lin, 'out_features', '?')}")

    class VocSpec(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.dec = dec

        def forward(self, latent):
            x = self.dec.fc1(latent)
            if getattr(self.dec, "patch_size", -1) != -1:
                x = self.dec.upsampling.upsampler(x.transpose(1, 2)).transpose(1, 2)
            x = self.dec.decoder(inputs_embeds=x).last_hidden_state
            return lin(x)

    voc = VocSpec().float().eval()
    T = 8
    dev = next(dec.parameters()).device
    dummy = torch.randn(1, T, mm.latent_dim, device=dev)
    with torch.no_grad():
        ref = voc(dummy)
    log(f"spec shape {tuple(ref.shape)}")

    path = OUT / "voc.onnx"
    torch.onnx.export(voc, (dummy,), str(path), input_names=["latent"],
                      output_names=["spec"], dynamic_axes={"latent": {1: "t"}},
                      opset_version=20, do_constant_folding=True, dynamo=False)
    sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
    got = sess.run(None, {"latent": np_(dummy)})[0]
    c = cosine(np_(ref), got)
    log(f"voc.onnx {path.stat().st_size / 1e6:.0f} MB cos={c:.6f} spec={got.shape}")

    meta = {"n_fft": int(head.n_fft), "hop_length": int(head.hop_length),
            "padding": str(getattr(head, "padding", "same")),
            "spec_bins": int(got.shape[-1]), "frames_per_latent": T}
    (OUT / "voc_meta.json").write_text(json.dumps(meta, indent=1))
    log(f"voc meta {meta}")
    return {"graph": "voc", "mb": round(path.stat().st_size / 1e6, 1), "cos": c,
            "spec_shape": list(got.shape)}


def quantize(paths: list[Path], bits: int = 4) -> list[dict]:
    from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer

    rows = []
    for src in paths:
        if not src.exists():
            continue
        dst = src.with_name(src.stem + f"_int{bits}.onnx")
        try:
            q = MatMulNBitsQuantizer(str(src), bits=bits, block_size=32, is_symmetric=True,
                                     accuracy_level=4, op_types_to_quantize=("MatMul", "Gemm"))
            q.process()
            q.model.save_model_to_file(str(dst), use_external_data_format=False)
            rows.append({"graph": src.stem, "fp32_mb": round(src.stat().st_size / 1e6, 1),
                         "int_mb": round(dst.stat().st_size / 1e6, 1)})
            log(f"quantise {src.stem}: {src.stat().st_size/1e6:.0f} -> "
                f"{dst.stat().st_size/1e6:.0f} MB (int{bits})")
        except Exception:
            log(f"quantise {src.stem} failed\n{traceback.format_exc()}")
    return rows


def stage_probe_audio(mm) -> dict:
    """Dump the audio VAE surface so the vocoder export can stop before ISTFT.

    `decode` builds a complex STFT internally, which the ONNX exporter refuses
    ("Unknown number type: complex"). The fix is to return the spectrum and do
    the inverse transform on the host, but that needs the real method names.
    """
    import inspect

    audio = mm.audio
    text = []
    text.append("class: " + type(audio).__name__)
    text.append("\nattrs: " + ", ".join(a for a in dir(audio) if not a.startswith("__")))
    for name in dir(audio):
        if name.startswith("__"):
            continue
        fn = getattr(audio, name)
        if not callable(fn):
            continue
        try:
            src = inspect.getsource(fn)
        except Exception:
            continue
        if any(k in src for k in ("istft", "stft", "complex", "spectrogram", "def decode", "def encode")):
            text.append(f"\n\n===== {name} =====\n{src}")
    out = OUT / "audio_src.txt"
    out.write_text("\n".join(text))
    log(f"wrote {out} ({len(text)} blocks)")
    for line in text[:80]:
        log(line)
    return {"graph": "probe_audio", "chars": sum(len(t) for t in text)}


def main() -> None:
    import torch

    sys.path.insert(0, str(REPO))
    patch_fp32()
    from ming_tts import MingTTS

    tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
    mm = tts.model
    results = []

    for name, fn in (("lm", stage_lm), ("agg", stage_agg), ("probe", lambda m, t: stage_probe_audio(m)),
                     ("voc", stage_voc)):
        if STAGE not in (name, "all"):
            continue
        try:
            results.append(fn(mm, torch))
        except Exception:
            log(f"stage {name} FAILED\n{traceback.format_exc()}")

    q = quantize([OUT / "lm.onnx", OUT / "aggregator.onnx", OUT / "voc.onnx"])
    (OUT / "sizes.json").write_text(json.dumps(
        {p_.name: round(p_.stat().st_size / 1e6, 1) for p_ in sorted(OUT.glob("*.onnx"))},
        indent=1))
    (OUT / "report.json").write_text(json.dumps({"graphs": results, "quant": q},
                                                ensure_ascii=False, indent=1))
    log("done")


if __name__ == "__main__":
    main()