"""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()