"""Export trada-tts-10m.safetensors to ONNX (used by TradaTTSOnnx and the WebGPU demo) and check against PyTorch. enc.onnx : ids[1,N] int64, tones[1,N] int64, spk[1,192] -> h[1,256,N], logdur[1,N] cfm.onnx : x[1,32,T], cond[1,256,T], t[1], spk[1,192], w[1] -> v[1,32,T] (text CFG baked in: one batch-2 pass) dec.onnx : z[1,32,T] (normalised latent) -> mag[1,961,2T], phase[1,961,2T] (iSTFT done by the caller) usage: python scripts/export_onnx.py [--out onnx]""" import argparse, json, os, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); sys.path.insert(0, ROOT) import numpy as np, torch, torch.nn as nn from safetensors.torch import load_file from trada_tts.model import TradaTTSModel class Enc(nn.Module): def __init__(s, n): super().__init__(); s.n = n def forward(s, ids, tones, spk): h = s.n.enc(ids, tones, spk); return h, s.n.dur(h, spk) class CFM(nn.Module): def __init__(s, n): super().__init__(); s.n = n def forward(s, x, cond, t, spk, w): return s.n.velocity_cfg(x, cond, t, spk, w) class CFM2(nn.Module): """2-step IntMeanFlow flow: average velocity over [t, r], CFG baked in (no w input)""" def __init__(s, f): super().__init__(); s.f = f def forward(s, x, cond, t, r, spk): return s.f(x, cond, t, spk, r) class Dec(nn.Module): def __init__(s, n): super().__init__(); s.n = n def forward(s, z): return s.n.decode(z) def main(): ap = argparse.ArgumentParser(); ap.add_argument("--out", default=os.path.join(ROOT, "onnx")); a = ap.parse_args() os.makedirs(a.out, exist_ok=True) cfg = json.load(open(os.path.join(ROOT, "config.json"), encoding="utf-8")) net = TradaTTSModel(n_symbols=len(cfg["symbols"]), n_tones=cfg["num_tones"], **cfg["arch"]).eval() net.load_state_dict(load_file(os.path.join(ROOT, cfg["weights"]))) enc, cfm, dec = Enc(net).eval(), CFM(net).eval(), Dec(net).eval() L, C, NS, NT = cfg["latent_dim"], cfg["enc_dim"], len(cfg["symbols"]), cfg["num_tones"] N, T = 23, 70 ids = torch.randint(2, NS, (1, N)); tones = torch.randint(0, NT, (1, N)); spk = torch.randn(1, 192) x, cond, t, w, z = torch.randn(1, L, T), torch.randn(1, C, T), torch.tensor([0.3]), torch.tensor([3.0]), torch.randn(1, L, T) kw = dict(opset_version=17, do_constant_folding=True) torch.onnx.export(enc, (ids, tones, spk), f"{a.out}/enc.onnx", input_names=["ids", "tones", "spk"], output_names=["h", "logdur"], dynamic_axes={"ids": {1: "N"}, "tones": {1: "N"}, "h": {2: "N"}, "logdur": {1: "N"}}, **kw) torch.onnx.export(cfm, (x, cond, t, spk, w), f"{a.out}/cfm.onnx", input_names=["x", "cond", "t", "spk", "w"], output_names=["v"], dynamic_axes={"x": {2: "T"}, "cond": {2: "T"}, "v": {2: "T"}}, **kw) torch.onnx.export(dec, (z,), f"{a.out}/dec.onnx", input_names=["z"], output_names=["mag", "phase"], dynamic_axes={"z": {2: "T"}, "mag": {2: "T2"}, "phase": {2: "T2"}}, **kw) fast = cfg.get("fast"); cfm2 = None if fast and os.path.exists(os.path.join(ROOT, fast["weights"])): from trada_tts.model import FlowDecoder A = cfg["arch"]; f2 = FlowDecoder(A["latent_dim"], A["enc_dim"], A["cfm_dim"], A["cfm_blocks"], interval=True).eval() f2.load_state_dict({k[5:]: v for k, v in load_file(os.path.join(ROOT, fast["weights"])).items()}); cfm2 = CFM2(f2).eval() torch.onnx.export(cfm2, (x, cond, t, torch.tensor([0.5]), spk), f"{a.out}/cfm2.onnx", input_names=["x", "cond", "t", "r", "spk"], output_names=["v"], dynamic_axes={"x": {2: "T"}, "cond": {2: "T"}, "v": {2: "T"}}, **kw) import onnxruntime as ort worst = {} def chk(name, feeds, ref): o = ort.InferenceSession(f"{a.out}/{name}", providers=["CPUExecutionProvider"]).run(None, feeds) for k, (u, v) in enumerate(zip(o, ref)): r = float(np.abs(u - v.numpy()).max() / (np.abs(v.numpy()).max() + 1e-9)); worst[f"{name}:{k}"] = max(worst.get(f"{name}:{k}", 0), r) with torch.no_grad(): for N2, T2 in ((9, 31), (41, 140)): ids = torch.randint(2, NS, (1, N2)); tones = torch.randint(0, NT, (1, N2)); spk = torch.randn(1, 192) * 4 chk("enc.onnx", {"ids": ids.numpy(), "tones": tones.numpy(), "spk": spk.numpy()}, enc(ids, tones, spk)) x, cond, z = torch.randn(1, L, T2), torch.randn(1, C, T2), torch.randn(1, L, T2) chk("cfm.onnx", {"x": x.numpy(), "cond": cond.numpy(), "t": t.numpy(), "spk": spk.numpy(), "w": w.numpy()}, [cfm(x, cond, t, spk, w)]) chk("dec.onnx", {"z": z.numpy()}, dec(z)) if cfm2 is not None: r = torch.tensor([0.5]); chk("cfm2.onnx", {"x": x.numpy(), "cond": cond.numpy(), "t": torch.tensor([0.0]).numpy(), "r": r.numpy(), "spk": spk.numpy()}, [cfm2(x, cond, torch.tensor([0.0]), r, spk)]) for k, v in worst.items(): print(f"{k:12s} max rel |onnx - torch| {v:.1e}") assert max(worst.values()) < 1e-3, worst print({f: round(os.path.getsize(f"{a.out}/{f}") / 1e6, 1) for f in sorted(os.listdir(a.out)) if f.endswith(".onnx")}) if __name__ == "__main__": main()