Text-to-Speech
ONNX
Vietnamese
vietnamese
flow-matching
webgpu
on-device
trada-tts / scripts /export_int8.py
tsdocode's picture
int8: WGSL WebGPU engine (int8/trada-int8.bin) + int8 ONNX graphs
511b660 verified
Raw History Blame Contribute Delete
4.74 kB
"""Pack the fast (2-step) model into one int8 weight file for the WebGPU engine (web/wgpu_engine.js).
Every Linear / non-depthwise Conv1d weight is stored as int8 with one fp32 scale per output channel (symmetric,
round-to-nearest). Rows are zero-padded to a multiple of 4 so a shader can read 4 weights per u32. Embeddings,
depthwise convs, the transposed conv, norms, biases and gammas stay fp32 (they are <3% of the parameters).
File layout: b"TRQ8" | u32 header_len | header JSON (utf-8) | zero pad to 16 | blob
header = {"config": {...}, "tensors": {name: {"dtype": "q8"|"f32", "shape": [...], "off": int, "rows": O, "cols": J,
"cols_pad": Jp, "soff": int}}} (offsets are byte offsets into the blob, 16-aligned)
With --onnx it also writes onnx/{enc,cfm2,dec}.int8.onnx: onnxruntime dynamic int8 quantization (MatMul/Gemm,
per-channel weights, int8 activations at run time) for CPU / WASM backends.
usage: python scripts/export_int8.py [--out int8/trada-int8.bin] [--sim DIR] [--onnx]
--sim DIR also writes DIR/trada-tts-10m(-2step).safetensors with the int8 weights dequantized back to fp32, so the
PyTorch backend can measure the quality effect of the quantization alone."""
import argparse, json, os, struct, sys
import numpy as np
from safetensors.numpy import load_file, save_file
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KEEP_F32 = ("dw.weight", "emb.weight", "tone_emb.weight", "decoder.up.weight")
def quantize(w):
O = w.shape[0]; m = w.reshape(O, -1).astype(np.float32)
s = np.maximum(np.abs(m).max(1), 1e-12) / 127.0
q = np.clip(np.rint(m / s[:, None]), -127, 127).astype(np.int8)
return q, s.astype(np.float32)
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--out", default=os.path.join(ROOT, "int8", "trada-int8.bin")); ap.add_argument("--sim"); ap.add_argument("--onnx", action="store_true")
a = ap.parse_args()
cfg = json.load(open(os.path.join(ROOT, "config.json"), encoding="utf-8"))
base = load_file(os.path.join(ROOT, cfg["weights"])); fast = load_file(os.path.join(ROOT, cfg["fast"]["weights"]))
W = {k: v for k, v in base.items() if not k.startswith("cfm.")} # the web demo only runs the 2-step flow
W.update(fast)
tensors, chunks, off = {}, [], 0
sim = {}
def put(b):
nonlocal off
o = off; chunks.append(b); off += len(b); pad = (-off) % 16; chunks.append(b"\0" * pad); off += pad; return o
for k in sorted(W):
v = W[k].astype(np.float32)
if k.endswith(".weight") and v.ndim >= 2 and not k.endswith(KEEP_F32):
q, s = quantize(v); O, J = q.shape; Jp = (J + 3) // 4 * 4
qp = np.zeros((O, Jp), np.int8); qp[:, :J] = q
tensors[k] = dict(dtype="q8", shape=list(v.shape), rows=O, cols=J, cols_pad=Jp, off=put(qp.tobytes()), soff=put(s.tobytes()))
sim[k] = (q.astype(np.float32) * s[:, None]).reshape(v.shape)
else:
tensors[k] = dict(dtype="f32", shape=list(v.shape), off=put(np.ascontiguousarray(v).tobytes()))
sim[k] = v
meta = {k: cfg[k] for k in ("name", "sample_rate", "latent_dim", "enc_dim", "arch", "speaker_dim")}
meta["fast_steps"] = cfg["fast"]["steps"]
hdr = json.dumps(dict(config=meta, tensors=tensors), separators=(",", ":")).encode()
head = b"TRQ8" + struct.pack("<I", len(hdr)) + hdr; head += b"\0" * ((-len(head)) % 16)
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
with open(a.out, "wb") as f:
f.write(head); [f.write(c) for c in chunks]
nq = sum(int(np.prod(t["shape"])) for t in tensors.values() if t["dtype"] == "q8"); nt = sum(int(np.prod(t["shape"])) for t in tensors.values())
print(f"{a.out}: {os.path.getsize(a.out) / 1e6:.1f} MB, {len(tensors)} tensors, int8 share {100 * nq / nt:.1f}% of {nt / 1e6:.2f}M params")
if a.onnx:
from onnxruntime.quantization import quantize_dynamic, QuantType
for n in ("enc", "cfm2", "dec"):
src, dst = os.path.join(ROOT, "onnx", f"{n}.onnx"), os.path.join(ROOT, "onnx", f"{n}.int8.onnx")
quantize_dynamic(src, dst, op_types_to_quantize=["MatMul", "Gemm"], per_channel=True, weight_type=QuantType.QInt8)
print(f"{dst}: {os.path.getsize(dst) / 1e6:.1f} MB")
if a.sim:
os.makedirs(a.sim, exist_ok=True)
save_file({k: v for k, v in sim.items() if not k.startswith("cfm2.")} | {k: base[k] for k in base if k.startswith("cfm.")},
os.path.join(a.sim, cfg["weights"]))
save_file({k: v for k, v in sim.items() if k.startswith("cfm2.")}, os.path.join(a.sim, cfg["fast"]["weights"]))
print("dequantized copy ->", a.sim)
if __name__ == "__main__":
main()