"""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("", a.sim) if __name__ == "__main__": main()