int8: WGSL WebGPU engine (int8/trada-int8.bin) + int8 ONNX graphs
Browse filesFiles changed (15)
- .gitattributes+1
- NOTICE+1-1
- README.md+7-2
- config.json+9
- int8/trada-int8.binAdded+3
- onnx/cfm2.int8.onnxAdded+3
- onnx/dec.int8.onnxAdded+3
- onnx/enc.int8.onnxAdded+3
- scripts/export_int8.pyAdded+78
- trada_tts/infer.py+7-3
- web/app.js+10-10
- web/bench.htmlAdded+74
- web/index.html+3-3
- web/tts.js+30-15
- web/wgpu_engine.jsAdded+279
1 unmodified line2341 unmodified line*.safetensors filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text1 unmodified line23451 unmodified line*.safetensors filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -textint8/trada-int8.bin filter=lfs diff=lfs merge=lfs -text
1 unmodified line23456781 unmodified line==========Code (trada_tts/, scripts/, web/*.js, web/*.html, web/serve.py): Apache License 2.0 (see LICENSE).Model weights (trada-tts-10m.safetensors, trada-tts-10m-2step.safetensors, onnx/enc.onnx, onnx/cfm.onnx, onnx/cfm2.onnx,onnx/dec.onnx, voices/): CC BY-NC-SA 4.0, because they are trained on the viVoice dataset (capleaf/viVoice, CC BY-NC-SA 4.0).They are also trained on about 61 hours of YodaLingua-Vietnamese (Thomcles/YodaLingua-Vietnamese), which its publisherlists as CC BY 4.0. Its transcripts were re-labelled with the ChunkFormer ASR model (khanhld/chunkformer-large-vie).https://creativecommons.org/licenses/by-nc-sa/4.0/ -- non-commercial use, attribution, share-alike.1 unmodified line23456781 unmodified line==========Code (trada_tts/, scripts/, web/*.js, web/*.html, web/serve.py): Apache License 2.0 (see LICENSE).Model weights (trada-tts-10m.safetensors, trada-tts-10m-2step.safetensors, onnx/enc.onnx, onnx/cfm.onnx, onnx/cfm2.onnx,onnx/dec.onnx, onnx/*.int8.onnx, int8/trada-int8.bin, voices/): CC BY-NC-SA 4.0, because they are trained on the viVoice dataset (capleaf/viVoice, CC BY-NC-SA 4.0).They are also trained on about 61 hours of YodaLingua-Vietnamese (Thomcles/YodaLingua-Vietnamese), which its publisherlists as CC BY 4.0. Its transcripts were re-labelled with the ChunkFormer ASR model (khanhld/chunkformer-large-vie).https://creativecommons.org/licenses/by-nc-sa/4.0/ -- non-commercial use, attribution, share-alike.
88 unmodified lines8990919293949514 unmodified lines11011111211311411511611711811912012112212388 unmodified linespython web/serve.py 8000 # then open http://localhost:8000/web/ in Chrome / Edge 113+```The page loads the ONNX files from `onnx/` and runs everything client-side: text normalisation, the model, iSTFT (a WGSL compute shader) and voice cloning. It uses WebGPU when available and falls back to multi-threaded WASM. `serve.py` only adds the COOP/COEP headers that multi-threaded WASM needs; any static host that sends those headers works.## How it works14 unmodified lines| `enc.onnx` | 10 MB | ids, tones [1,N] int64, spk [1,192] → h [1,256,N], logdur [1,N] || `cfm.onnx` | 23 MB | x [1,32,T], cond [1,256,T], t [1], spk [1,192], w [1] → v [1,32,T] (CFG baked in, one batch-2 pass) || `dec.onnx` | 6 MB | z [1,32,T] → mag, phase [1,961,2T]; iSTFT n_fft 1920, hop 480, Hann, center=True || `campplus.onnx` | 28 MB | 80-bin Kaldi fbank [1,T,80] → speaker embedding [1,192]; only needed for cloning |`scripts/export_onnx.py` rebuilds them from `trada-tts-10m.safetensors`.**Verification:**- ONNX vs PyTorch: max relative difference ≤ 2e-6 per graph.- The JavaScript pipeline vs Python on identical noise: same tokens, waveform correlation 1.000000.- WebGPU vs WASM in Chromium: correlation 1.00000.## Evaluation88 unmodified lines8990919293949514 unmodified lines11011111211311411511611711811912012112212312412512612712888 unmodified linespython web/serve.py 8000 # then open http://localhost:8000/web/ in Chrome / Edge 113+```The page runs everything client-side: text normalisation, the model, iSTFT (a WGSL compute shader) and voice cloning. With WebGPU it runs the fast model on the hand-written int8 WGSL engine (`int8/trada-int8.bin`); otherwise it uses multi-threaded WASM with the int8 ONNX graphs. `serve.py` only adds the COOP/COEP headers that multi-threaded WASM needs; any static host that sends those headers works.## How it works14 unmodified lines| `enc.onnx` | 10 MB | ids, tones [1,N] int64, spk [1,192] → h [1,256,N], logdur [1,N] || `cfm.onnx` | 23 MB | x [1,32,T], cond [1,256,T], t [1], spk [1,192], w [1] → v [1,32,T] (CFG baked in, one batch-2 pass) || `dec.onnx` | 6 MB | z [1,32,T] → mag, phase [1,961,2T]; iSTFT n_fft 1920, hop 480, Hann, center=True || `cfm2.onnx` | 24 MB | x [1,32,T], cond [1,256,T], t [1], r [1], spk [1,192] → average velocity over [t, r] (2-step fast model) || `enc/cfm2/dec.int8.onnx` | 3 + 7 + 3 MB | the fast model with dynamic int8 quantization (onnxruntime); `TradaTTSOnnx(..., int8=True)` || `campplus.onnx` | 28 MB | 80-bin Kaldi fbank [1,T,80] → speaker embedding [1,192]; only needed for cloning |`scripts/export_onnx.py` rebuilds them from `trada-tts-10m.safetensors`; `scripts/export_int8.py --onnx` builds the int8 files.**WebGPU int8 engine** (`web/wgpu_engine.js`, weights `int8/trada-int8.bin`, 10.7 MB): the fast model run with hand-written WGSL kernels instead of ONNX Runtime. Every Linear/Conv1d weight is int8 with one fp32 scale per output channel and is dequantized inside a tiled matmul kernel (W8A32); LayerNorm, GELU, the ConvNeXt residual, FiLM and the iSTFT-head exp are fused into the kernels. The web demo uses it whenever WebGPU is available, and the int8 ONNX graphs on WASM otherwise, so the first visit downloads about 11–13 MB instead of 40 MB.**Verification:**- ONNX vs PyTorch: max relative difference ≤ 2e-6 per graph.- The JavaScript pipeline vs Python on identical noise: same tokens, waveform correlation 1.000000.- WebGPU vs WASM in Chromium: correlation 1.00000.- WGSL int8 engine vs PyTorch with the same int8 weights: relative difference ≤ 2e-6 per graph, waveform correlation 1.000000 end to end. Int8 vs fp32 on 48 sentences: syllable errors 3.7% vs 4.1%, DNSMOS 3.27 vs 3.25 (paired difference +0.02 ± 0.02).## Evaluation
93 unmodified lines949596979893 unmodified lines"steps": 2,"onnx": "cfm2.onnx","note": "IntMeanFlow-distilled flow decoder: average velocity over [t, r], text CFG baked in"}}93 unmodified lines94959697989910010110210310410510610793 unmodified lines"steps": 2,"onnx": "cfm2.onnx","note": "IntMeanFlow-distilled flow decoder: average velocity over [t, r], text CFG baked in"},"int8": {"webgpu": "int8/trada-int8.bin","onnx": {"enc": "onnx/enc.int8.onnx","cfm2": "onnx/cfm2.int8.onnx","dec": "onnx/dec.int8.onnx"},"note": "fast (2-step) model with int8 weights: trada-int8.bin for the WebGPU engine (web/wgpu_engine.js, per-channel int8 weights, fp32 math); *.int8.onnx are onnxruntime dynamic-quantized graphs for CPU. Built by scripts/export_int8.py --onnx"}}
123version https://git-lfs.github.com/spec/v1oid sha256:ec30c046c98abaa904d8b795806179edf889e10f2ab34cbb68cc057ef7951005size 10694896123version https://git-lfs.github.com/spec/v1oid sha256:daf51c71a81f0786c36cf48c123b039405cf5c64914b9e77d631f4f538919fd6size 6578061123version https://git-lfs.github.com/spec/v1oid sha256:fb429a225e949fab3a6291632c3ad13f59b0f5bdded2b440452416dbf4df2800size 3008939123version https://git-lfs.github.com/spec/v1oid sha256:4838e2e09080f677f496c10a5de4bc619b9343899534e1958d53e80ed6fe42efsize 3297590123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""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 | blobheader = {"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, sysimport numpy as npfrom 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()157 unmodified lines158159160161162163164165166167168169170171172157 unmodified linesclass TradaTTSOnnx(_Base):"""ONNX Runtime backend (no PyTorch needed). Uses onnx/enc.onnx, cfm.onnx, dec.onnx."""def __init__(self, root, threads=4, providers=None):super().__init__(root)import onnxruntime as ortso = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1pv = providers or ["CPUExecutionProvider"]names = ["enc", "cfm", "dec"] + (["cfm2"] if os.path.exists(os.path.join(root, "onnx", "cfm2.onnx")) else [])self.s = {k: ort.InferenceSession(os.path.join(root, "onnx", f"{k}.onnx"), sess_options=so, providers=pv) for k in names}self.has_fast = "cfm2" in self.s@classmethod157 unmodified lines158159160161162163164165166167168169170171172173174175176157 unmodified linesclass TradaTTSOnnx(_Base):"""ONNX Runtime backend (no PyTorch needed). Uses onnx/enc.onnx, cfm.onnx, dec.onnx (+ cfm2.onnx for fast=True).int8=True loads onnx/{enc,cfm2,dec}.int8.onnx instead: about 3x smaller and faster on CPU, same quality."""def __init__(self, root, threads=4, providers=None, int8=False):super().__init__(root)import onnxruntime as ortso = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1pv = providers or ["CPUExecutionProvider"]names = ["enc", "cfm", "dec"] + (["cfm2"] if os.path.exists(os.path.join(root, "onnx", "cfm2.onnx")) else [])q = self.config.get("int8", {}).get("onnx", {}) if int8 else {} # int8=True: dynamic-int8 enc/cfm2/dec (CPU speed-up)if int8 and not q: raise ValueError("this model folder has no int8 ONNX graphs (config.json 'int8')")self.s = {k: ort.InferenceSession(os.path.join(root, *(q[k].split("/") if k in q else ("onnx", f"{k}.onnx"))), sess_options=so, providers=pv)for k in names}self.has_fast = "cfm2" in self.s@classmethod
1234567358 unmodified lines36636736836937037137255 unmodified lines428429430431432433434435436437438439440441442443444445446447448import * as ort from './ort/ort.webgpu.min.mjs';import { TradaTTS, normalize, normalizePart, JOIN, isAlnum } from './tts.js?v=11220300';import { resample, kaldiFbank } from './audio.js?v=11220300';const VER = '11220300';// model repo root (config.json, onnx/, voices/): the page's parent folder, or window.TRADA_ROOT (e.g. a Hugging Face resolve URL)const ROOT = (window.TRADA_ROOT || new URL('..', import.meta.url).href).replace(/\/$/, '');358 unmodified lines// ---------------- init ----------------function setPill(id, cls, text) { const p = $(id); p.className = 'pill ' + cls; p.lastElementChild.textContent = text; }const PARTS = { enc: 'lp-enc', cfm: 'lp-cfm', dec: 'lp-dec', cfm2: 'lp-cfm' };async function init() {try { const th = localStorage.getItem(THEME); if (th) document.documentElement.dataset.theme = th; } catch {}for (const el of document.querySelectorAll('svg.glass')) el.innerHTML = GLASS;55 unmodified linescatch (e) { console.warn('3D scene unavailable', e); $('brew3d').hidden = true; }const prog = (a, b, got, size) => {const f = b ? a / b : 0; scene?.setProgress(f);$('lMB').textContent = `${(a / 1e6).toFixed(0)} / ${((b || 39e6) / 1e6).toFixed(0)} MB`; $('lBar').style.width = (100 * f).toFixed(1) + '%';for (const [n, id] of Object.entries(PARTS)) if (n in size) $(id).className = size[n] && got[n] >= size[n] ? 'done' : got[n] ? 'going' : '';if (b && a >= b) $('lSub').textContent = S.backend === 'webgpu' ? 'Đang khởi động WebGPU…' : 'Đang khởi động…';};let gpu = false;try { gpu = !!(navigator.gpu && await navigator.gpu.requestAdapter()); } catch { gpu = false; }setPill('pBackend', gpu ? 'ok' : 'warn', gpu ? 'WebGPU' : 'CPU · WASM');const t0 = performance.now();try {if (!gpu) throw new Error('no webgpu');S.backend = 'webgpu'; await initGPUistft();S.tts = await TradaTTS.load(ort, ROOT, { executionProviders: ['webgpu'], graphOptimizationLevel: 'all' }, istftGPU, prog);} catch (e) {if (gpu) { console.warn('WebGPU init failed, using WASM', e); setPill('pBackend', 'warn', 'CPU · WASM (WebGPU lỗi)'); }S.backend = 'wasm'; S.tts = await TradaTTS.load(ort, ROOT, { executionProviders: ['wasm'] }, null, prog);}setPill('pLoad', '', `pha xong ${((performance.now() - t0) / 1000).toFixed(1)} s`);scene?.setProgress(1); $('lSub').textContent = 'Trà đã pha xong.';1234567358 unmodified lines36636736836937037137255 unmodified lines428429430431432433434435436437438439440441442443444445446447448import * as ort from './ort/ort.webgpu.min.mjs';import { TradaTTS, normalize, normalizePart, JOIN, isAlnum } from './tts.js?v=11220400';import { resample, kaldiFbank } from './audio.js?v=11220400';const VER = '11220400';// model repo root (config.json, onnx/, voices/): the page's parent folder, or window.TRADA_ROOT (e.g. a Hugging Face resolve URL)const ROOT = (window.TRADA_ROOT || new URL('..', import.meta.url).href).replace(/\/$/, '');358 unmodified lines// ---------------- init ----------------function setPill(id, cls, text) { const p = $(id); p.className = 'pill ' + cls; p.lastElementChild.textContent = text; }const PART_NAMES = { all: 'Trọng số int8', enc: 'Đọc chữ', cfm2: 'Sinh âm', cfm: 'Sinh âm', dec: 'Giải mã' };async function init() {try { const th = localStorage.getItem(THEME); if (th) document.documentElement.dataset.theme = th; } catch {}for (const el of document.querySelectorAll('svg.glass')) el.innerHTML = GLASS;55 unmodified linescatch (e) { console.warn('3D scene unavailable', e); $('brew3d').hidden = true; }const prog = (a, b, got, size) => {const f = b ? a / b : 0; scene?.setProgress(f);$('lMB').textContent = `${(a / 1e6).toFixed(0)} / ${((b || 11e6) / 1e6).toFixed(0)} MB`; $('lBar').style.width = (100 * f).toFixed(1) + '%';$('lParts').innerHTML = Object.keys(size).map(n => `<span><i class="${size[n] && got[n] >= size[n] ? 'done' : got[n] ? 'going' : ''}"></i>${PART_NAMES[n] || n}${size[n] ? ` · ${(size[n] / 1e6).toFixed(0)} MB` : ''}</span>`).join('');if (b && a >= b) $('lSub').textContent = S.backend === 'webgpu' ? 'Đang khởi động WebGPU…' : 'Đang khởi động…';};let gpu = false;try { gpu = !!(navigator.gpu && await navigator.gpu.requestAdapter()); } catch { gpu = false; }setPill('pBackend', gpu ? 'ok' : 'warn', gpu ? 'WebGPU · int8' : 'CPU · WASM · int8');const t0 = performance.now();try {if (!gpu) throw new Error('no webgpu');S.backend = 'webgpu'; await initGPUistft();S.tts = await TradaTTS.load(ort, ROOT, {}, istftGPU, prog, 'auto', { engine: 'wgpu' }); // hand-written WGSL kernels, int8 weights} catch (e) {if (gpu) { console.warn('WebGPU init failed, using WASM', e); setPill('pBackend', 'warn', 'CPU · WASM · int8 (WebGPU lỗi)'); }S.backend = 'wasm'; S.tts = await TradaTTS.load(ort, ROOT, { executionProviders: ['wasm'] }, null, prog, 'auto', { int8: true });}setPill('pLoad', '', `pha xong ${((performance.now() - t0) / 1000).toFixed(1)} s`);scene?.setProgress(1); $('lSub').textContent = 'Trà đã pha xong.';
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Trà Đá · benchmark int8</title><style>body{font:14px/1.5 system-ui,sans-serif;margin:0;padding:20px 16px;background:#f5efe3;color:#2b1e13}@media (prefers-color-scheme:dark){body{background:#16110c;color:#f4eadb}}table{border-collapse:collapse;font-variant-numeric:tabular-nums;margin-top:12px}td,th{border:1px solid #8885;padding:4px 10px;text-align:right}th:first-child,td:first-child{text-align:left}button{font:inherit;padding:8px 16px;border-radius:8px;border:1px solid #8886;cursor:pointer}pre{white-space:pre-wrap;font-size:12px}</style><h2>Trà Đá · int8 benchmark</h2><p>Cùng một đầu vào (câu ~60 ký tự, ~7 s audio). <b>WGSL int8</b>: engine WebGPU tự viết, trọng số int8 (bản demo đang dùng). <b>fp32</b> / <b>int8</b>: onnxruntime-web với ONNX fp32 và ONNX int8 động. Thời gian là trung vị 10 lần sau 2 lần khởi động; tổng = enc + 2×cfm2 + dec (một câu chế độ 2 bước). "lệch" = sai khác tương đối của magnitude giải mã so với dòng đầu tiên của cùng backend.</p><button id="go">Chạy</button> <span id="st"></span><div id="out"></div><pre id="log"></pre><script type="module">import * as ort from './ort/ort.webgpu.min.mjs';import { GpuEngine } from './wgpu_engine.js?v=11220400';ort.env.wasm.wasmPaths = new URL('./ort/', import.meta.url).href;ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(8, navigator.hardwareConcurrency || 4) : 1;const ROOT = new URL('..', import.meta.url).href;const V = { fp32: g => `onnx/${g}.onnx`, int8: g => `onnx/${g}.int8.onnx` };const $ = id => document.getElementById(id), log = s => { $('log').textContent += s + '\n'; };let seed = 1; const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };const gauss = n => Float32Array.from({ length: n }, () => Math.sqrt(-2 * Math.log(rnd() + 1e-9)) * Math.cos(2 * Math.PI * rnd()));const N = 60, T = 200;function inputs() { seed = 1; return { enc: { ids: new ort.Tensor('int64', BigInt64Array.from({ length: N }, () => BigInt(2 + Math.floor(rnd() * 30))), [1, N]), tones: new ort.Tensor('int64', BigInt64Array.from({ length: N }, () => BigInt(Math.floor(rnd() * 6))), [1, N]), spk: new ort.Tensor('float32', gauss(192), [1, 192]) }, cfm2: { x: new ort.Tensor('float32', gauss(32 * T), [1, 32, T]), cond: new ort.Tensor('float32', gauss(256 * T), [1, 256, T]), t: new ort.Tensor('float32', new Float32Array([0]), [1]), r: new ort.Tensor('float32', new Float32Array([0.5]), [1]), spk: new ort.Tensor('float32', gauss(192), [1, 192]) }, dec: { z: new ort.Tensor('float32', gauss(32 * T), [1, 32, T]) } };}const med = a => { const s = [...a].sort((x, y) => x - y); return s[s.length >> 1]; };// the hand-written WGSL engine (wgpu_engine.js) on int8/trada-int8.bin; runs first so its dec output is the referenceasync function benchWgsl(inp, ref) { const buf = await (await fetch(`${ROOT}int8/trada-int8.bin`)).arrayBuffer(), eng = await GpuEngine.create(buf), row = { ep: 'webgpu', v: 'WGSL int8 (mới)', mb: buf.byteLength / 1e6 }; for (const g of ['enc', 'cfm2', 'dec']) { const ts = []; let out; for (let k = 0; k < 12; k++) { const t0 = performance.now(); out = await eng[g].run(inp[g]); const dt = performance.now() - t0; if (k >= 2) ts.push(dt); } row[g] = med(ts); if (g === 'dec') ref.dec = out.mag.data; } row.total = row.enc + 2 * row.cfm2 + row.dec; return row;}async function bench(ep, v, inp, ref) { const row = { ep, v }; let mb = 0; for (const g of ['enc', 'cfm2', 'dec']) { const buf = new Uint8Array(await (await fetch(`${ROOT}${V[v](g)}`)).arrayBuffer()); mb += buf.length / 1e6; let s; try { s = await ort.InferenceSession.create(buf, { executionProviders: [ep], graphOptimizationLevel: 'all' }); } catch (e) { row[g] = 'lỗi'; log(`${ep} ${v} ${g}: ${e.message}`); continue; } const ts = []; let out; for (let k = 0; k < 12; k++) { const t0 = performance.now(); out = await s.run(inp[g]); const dt = performance.now() - t0; if (k >= 2) ts.push(dt); } row[g] = med(ts); if (g === 'dec') { const o = out.mag.data; if (!ref.dec) ref.dec = o; else { let num = 0, den = 0; for (let i = 0; i < o.length; i++) { num += (o[i] - ref.dec[i]) ** 2; den += ref.dec[i] ** 2; } row.err = Math.sqrt(num / den); } } await s.release?.(); } row.mb = mb; row.total = (row.enc || 0) + 2 * (row.cfm2 || 0) + (row.dec || 0); return row;}$('go').onclick = async () => { $('go').disabled = true; $('log').textContent = ''; let gpu = false; try { gpu = !!(navigator.gpu && await navigator.gpu.requestAdapter()); } catch {} const eps = gpu ? ['webgpu', 'wasm'] : ['wasm']; const rows = []; log(`WebGPU: ${gpu ? 'có' : 'không'} · threads ${ort.env.wasm.numThreads} · ${navigator.userAgent}`); for (const ep of eps) { const ref = {}; if (ep === 'webgpu') { $('st').textContent = 'WGSL int8…'; rows.push(await benchWgsl(inputs(), ref)); render(rows); } for (const v of Object.keys(V)) { $('st').textContent = `${ep} · ${v}…`; const inp = inputs(); rows.push(await bench(ep, v, inp, ref)); render(rows); if (location.hash === '#auto') fetch('../_r?' + encodeURIComponent(JSON.stringify(rows.at(-1)))).catch(() => {}); } } $('st').textContent = 'Xong. Chụp màn hình bảng này gửi lại nhé.'; $('go').disabled = false; document.title = 'DONE';};if (location.hash === '#auto') setTimeout(() => $('go').click(), 100);const f = x => typeof x === 'number' ? x.toFixed(1) : (x ?? '');function render(rows) { $('out').innerHTML = `<table><tr><th>Backend · bản</th><th>MB</th><th>enc ms</th><th>cfm2 ms</th><th>dec ms</th><th>tổng (enc+2·cfm2+dec)</th><th>lệch</th></tr>` + rows.map(r => `<tr><td>${r.ep} · ${r.v}</td><td>${f(r.mb)}</td><td>${f(r.enc)}</td><td>${f(r.cfm2)}</td><td>${f(r.dec)}</td><td>${f(r.total)}</td><td>${r.err === undefined ? '—' : r.err.toExponential(1)}</td></tr>`).join('') + '</table>';}</script>313 unmodified lines31431531631731831932032132260 unmodified lines383384385386387388313 unmodified lines<div class="lcard" role="dialog" aria-modal="true" aria-label="Đang tải mô hình"><canvas id="brew3d" aria-hidden="true"></canvas><div class="meta"><div class="row"><b style="font-weight:600">Đang pha trà…</b><span class="spacer"></span><span id="lMB" style="font-variant-numeric:tabular-nums;color:#d6c6b0">0 / 39 MB</span></div><div class="lbar"><div id="lBar"></div></div><div class="parts"><span><i id="lp-enc"></i>Đọc chữ · 10 MB</span><span><i id="lp-cfm"></i>Sinh âm · 23 MB</span><span><i id="lp-dec"></i>Giải mã · 6 MB</span></div><div class="sub" id="lSub">Chỉ tải lần đầu, lần sau mở ngay.</div></div></div>60 unmodified lines<span>Các giọng mẫu là giọng tổng hợp (trộn nhiều người nói), không phải giọng của một người thật.</span></footer></div><script type="module" src="app.js?v=11220300"></script></body></html>313 unmodified lines31431531631731831932032132260 unmodified lines383384385386387388313 unmodified lines<div class="lcard" role="dialog" aria-modal="true" aria-label="Đang tải mô hình"><canvas id="brew3d" aria-hidden="true"></canvas><div class="meta"><div class="row"><b style="font-weight:600">Đang pha trà…</b><span class="spacer"></span><span id="lMB" style="font-variant-numeric:tabular-nums;color:#d6c6b0">0 / 11 MB</span></div><div class="lbar"><div id="lBar"></div></div><div class="parts" id="lParts"></div><div class="sub" id="lSub">Chỉ tải lần đầu, lần sau mở ngay.</div></div></div>60 unmodified lines<span>Các giọng mẫu là giọng tổng hợp (trộn nhiều người nói), không phải giọng của một người thật.</span></footer></div><script type="module" src="app.js?v=11220400"></script></body></html>
1234567119 unmodified lines1271281291301311326 unmodified lines139140141142143144145146147148149150151152153154155156157158159160161// Trà Đá TTS inference in JavaScript, backend-agnostic: pass an `ort` module (onnxruntime-web in the browser,// onnxruntime-node in tests). Mirrors trada_tts/text.py + trada_tts/infer.py.import { textNormalize } from './vi_normalize.js?v=11220300';import { fixNumbers } from './vi_fix.js?v=11220300';const TONE_MARK = { '̀': 2, '́': 3, '̉': 4, '̃': 5, '̣': 6 };const WORD_RE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu; // == Python re r"\w+|[^\w\s]" on NFC text119 unmodified linesreturn out.slice(NF >> 1, len - (NF >> 1));}export class TradaTTS {constructor(ort, sessions, config, istft = null, root = null, opts = {}) {this.ort = ort; this.s = sessions; this.cfg = config; this.sr = config.sample_rate; this.root = root; this.opts = opts;6 unmodified linesreturn this.s[name];}// root = repo root URL (holds config.json and onnx/). flow: 'cfm2' (2-step, default when available) or 'cfm' (16-step)static async load(ort, root, opts = {}, istft = null, onProgress = null, flow = 'auto') {const cfg = await (await fetch(`${root}/config.json`)).json();if (flow === 'auto') flow = cfg.fast ? 'cfm2' : 'cfm';const names = ['enc', flow, 'dec'], bufs = {}, got = {}, size = {};const report = () => { if (!onProgress) return; // total = real sizes once every file has answeredconst a = names.reduce((s, n) => s + (got[n] || 0), 0), known = names.every(n => size[n]);onProgress(a, known ? names.reduce((s, n) => s + size[n], 0) : Math.max(a + 1, 39.3e6), { ...got }, { ...size }); };await Promise.all(names.map(async n => { // streamed, so the page can show byte progress per fileconst r = await fetch(`${root}/onnx/${n}.onnx`); size[n] = +r.headers.get('content-length') || 0;if (!r.body || !size[n]) { bufs[n] = new Uint8Array(await r.arrayBuffer()); got[n] = size[n] = bufs[n].length; report(); return; }const buf = new Uint8Array(size[n]), rd = r.body.getReader(); let o = 0;for (;;) { const { done, value } = await rd.read(); if (done) break; buf.set(value, o); o += value.length; got[n] = o; report(); }bufs[n] = buf;}));const s = {};for (const n of names) s[n] = await ort.InferenceSession.create(bufs[n], opts);return new TradaTTS(ort, s, cfg, istft, root, opts);}// one chunk of NORMALISED text -> Float32Array @24 kHzasync synthChunk(norm, spk, { w = 3.0, steps = 16, speed = 1.0, seed = 0, noise = null, breaks = null, minSyllableMs = 160, fast = false, onStep = null, onTiming = null } = {}) {1234567119 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481496 unmodified lines156157158159160161162163164165166167168169170171172173174175176// Trà Đá TTS inference in JavaScript, backend-agnostic: pass an `ort` module (onnxruntime-web in the browser,// onnxruntime-node in tests). Mirrors trada_tts/text.py + trada_tts/infer.py.import { textNormalize } from './vi_normalize.js?v=11220400';import { fixNumbers } from './vi_fix.js?v=11220400';const TONE_MARK = { '̀': 2, '́': 3, '̉': 4, '̃': 5, '̣': 6 };const WORD_RE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu; // == Python re r"\w+|[^\w\s]" on NFC text119 unmodified linesreturn out.slice(NF >> 1, len - (NF >> 1));}// fetch several files in parallel, streamed, reporting (bytes so far, total, got{name}, size{name}) for a progress barasync function fetchAll(urls, onProgress = null, estimate = 0) {const names = Object.keys(urls), bufs = {}, got = {}, size = {};const report = () => { if (!onProgress) return; // total = real sizes once every file has answeredconst a = names.reduce((s, n) => s + (got[n] || 0), 0), known = names.every(n => size[n]);onProgress(a, known ? names.reduce((s, n) => s + size[n], 0) : Math.max(a + 1, estimate), { ...got }, { ...size }); };await Promise.all(names.map(async n => {const r = await fetch(urls[n]); if (!r.ok) throw new Error(`${urls[n]}: HTTP ${r.status}`);size[n] = +r.headers.get('content-length') || 0;if (!r.body || !size[n]) { bufs[n] = new Uint8Array(await r.arrayBuffer()); got[n] = size[n] = bufs[n].length; report(); return; }const buf = new Uint8Array(size[n]), rd = r.body.getReader(); let o = 0;for (;;) { const { done, value } = await rd.read(); if (done) break; buf.set(value, o); o += value.length; got[n] = o; report(); }bufs[n] = buf;}));return bufs;}export class TradaTTS {constructor(ort, sessions, config, istft = null, root = null, opts = {}) {this.ort = ort; this.s = sessions; this.cfg = config; this.sr = config.sample_rate; this.root = root; this.opts = opts;6 unmodified linesreturn this.s[name];}// root = repo root URL (holds config.json and onnx/). flow: 'cfm2' (2-step, default when available) or 'cfm' (16-step)// engine 'wgpu': the hand-written WebGPU engine (wgpu_engine.js) on int8 weights, fast model only.// engine 'ort' : onnxruntime-web sessions; int8 = true loads the dynamically quantized ONNX graphs (config.int8.onnx).static async load(ort, root, opts = {}, istft = null, onProgress = null, flow = 'auto', { engine = 'ort', int8 = false } = {}) {const cfg = await (await fetch(`${root}/config.json`)).json();if (flow === 'auto') flow = cfg.fast ? 'cfm2' : 'cfm';if (engine === 'wgpu') {const [{ GpuEngine }, bufs] = await Promise.all([import('./wgpu_engine.js?v=11220400'), fetchAll({ all: `${root}/${cfg.int8.webgpu}` }, onProgress, 10.7e6)]);const eng = await GpuEngine.create(bufs.all.buffer);const t = new TradaTTS(ort, { enc: eng.enc, cfm2: eng.cfm2, dec: eng.dec }, cfg, istft, root, opts); t.engine = 'wgpu'; return t;}const names = ['enc', flow, 'dec'], q = int8 && cfg.int8 && cfg.int8.onnx;const bufs = await fetchAll(Object.fromEntries(names.map(n => [n, `${root}/${q && q[n] ? q[n] : `onnx/${n}.onnx`}`])), onProgress, q ? 12.9e6 : 39.3e6);const s = {};for (const n of names) s[n] = await ort.InferenceSession.create(bufs[n], opts);const t = new TradaTTS(ort, s, cfg, istft, root, opts); t.engine = q ? 'ort-int8' : 'ort'; return t;}// one chunk of NORMALISED text -> Float32Array @24 kHzasync synthChunk(norm, spk, { w = 3.0, steps = 16, speed = 1.0, seed = 0, noise = null, breaks = null, minSyllableMs = 160, fast = false, onStep = null, onTiming = null } = {}) {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279// Trà Đá WebGPU engine: the fast (2-step) model run with hand-written WGSL kernels and int8 weights (W8A32).// Weights come from int8/trada-int8.bin (scripts/export_int8.py): every Linear / Conv1d weight is int8 with one fp32// scale per output channel and is dequantized inside the matmul kernel; activations stay fp32.// The three graphs expose the same run() interface as onnxruntime-web sessions (enc, cfm2, dec), so TradaTTS uses// them unchanged. Layout everywhere is [channels, time], row-major, like the ONNX tensors [1, C, T].
const NONE = 0xffffffff;const WGSL = /* wgsl */`struct P { O:u32, I:u32, T:u32, K:u32, pad:u32, J:u32, Jp:u32, woff:u32, soff:u32, boff:u32, mode:u32, goff:u32, voff:u32, v2off:u32, Tin:u32, n:u32 };@group(0) @binding(0) var<storage, read> Wb: array<u32>;@group(0) @binding(1) var<storage, read> X: array<f32>;@group(0) @binding(2) var<storage, read_write> Y: array<f32>;@group(0) @binding(3) var<storage, read> R: array<f32>;@group(0) @binding(4) var<storage, read> V: array<f32>;@group(0) @binding(5) var<uniform> p: P;const NONE = 0xffffffffu;fn wf(i: u32) -> f32 { return bitcast<f32>(Wb[i]); }fn erf_(x: f32) -> f32 { // Abramowitz-Stegun 7.1.26, |error| < 1.5e-7 let a = abs(x); let t = 1.0 / (1.0 + 0.3275911 * a); let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-a * a); return select(-y, y, x >= 0.0);}fn gelu(x: f32) -> f32 { return 0.5 * x * (1.0 + erf_(x * 0.7071067811865476)); }
// Y[o,t] = epilogue( s[o] * sum_j W[o,j] * X[j/K, t + j%K - pad] + b[o] ) (Linear when K = 1)// epilogue (p.mode): 0 none · 1 GELU · 2 ConvNeXt residual R + gamma*y + V[voff] · 3 FiLM y*(1+V[voff])+V[v2off]// 4 iSTFT head: exp(y) clamped at 100 on the first p.n channels (magnitude), phase as isconst TS = 16u; // output tile: 16 channels x 64 time steps; each thread owns 4 time steps (stride 16)var<workgroup> Ws: array<array<f32, 16>, 16>;var<workgroup> Xs: array<array<f32, 64>, 16>;@compute @workgroup_size(16, 16)fn qconv(@builtin(local_invocation_id) l: vec3<u32>, @builtin(workgroup_id) g: vec3<u32>) { let t0 = g.x * 64u; let o = g.y * TS + l.y; let rw = p.Jp / 4u; var acc = vec4<f32>(0.0); for (var j0 = 0u; j0 < p.J; j0 += TS) { let wj = j0 + l.x; var wv = 0.0; if (o < p.O && wj < p.J) { let word = Wb[p.woff + o * rw + (wj >> 2u)]; wv = f32(bitcast<i32>(((word >> ((wj & 3u) * 8u)) & 0xffu) << 24u) >> 24u); } Ws[l.y][l.x] = wv; let xj = j0 + l.y; let c = xj / p.K; let sh = i32(xj % p.K) - i32(p.pad); for (var q = 0u; q < 4u; q++) { let xt = t0 + l.x + 16u * q; var xv = 0.0; if (xj < p.J && xt < p.T) { let tt = i32(xt) + sh; if (tt >= 0 && tt < i32(p.Tin)) { xv = X[c * p.Tin + u32(tt)]; } } Xs[l.y][l.x + 16u * q] = xv; } workgroupBarrier(); for (var jj = 0u; jj < TS; jj++) { let w = Ws[l.y][jj]; acc = fma(vec4<f32>(w), vec4<f32>(Xs[jj][l.x], Xs[jj][l.x + 16u], Xs[jj][l.x + 32u], Xs[jj][l.x + 48u]), acc); } workgroupBarrier(); } if (o >= p.O) { return; } let sc = wf(p.soff + o); let bi = wf(p.boff + o); for (var q = 0u; q < 4u; q++) { let t = t0 + l.x + 16u * q; if (t < p.T) { var y = acc[q] * sc + bi; switch p.mode { case 1u: { y = gelu(y); } case 2u: { var v = 0.0; if (p.voff != NONE) { v = V[p.voff + o]; } y = R[o * p.T + t] + wf(p.goff + o) * y + v; } case 3u: { y = y * (1.0 + V[p.voff + o]) + V[p.v2off + o]; } case 4u: { if (o < p.n) { y = min(exp(y), 100.0); } } default: {} } Y[o * p.T + t] = y; } }}
// depthwise Conv1d, kernel 7, padding 3 (fp32 weights [C,1,7])@compute @workgroup_size(64)fn dwconv(@builtin(global_invocation_id) gi: vec3<u32>) { let i = gi.x; if (i >= p.O * p.T) { return; } let c = i / p.T; let t = i % p.T; var acc = wf(p.boff + c); for (var k = 0u; k < 7u; k++) { let tt = i32(t) + i32(k) - 3; if (tt >= 0 && tt < i32(p.T)) { acc = fma(wf(p.woff + c * 7u + k), X[c * p.T + u32(tt)], acc); } } Y[i] = acc;}
// LayerNorm over channels at each time step (eps 1e-5), one thread per t@compute @workgroup_size(64)fn lnorm(@builtin(global_invocation_id) gi: vec3<u32>) { let t = gi.x; if (t >= p.T) { return; } var m = 0.0; for (var c = 0u; c < p.O; c++) { m += X[c * p.T + t]; } m /= f32(p.O); var v = 0.0; for (var c = 0u; c < p.O; c++) { let d = X[c * p.T + t] - m; v += d * d; } v /= f32(p.O); let r = inverseSqrt(v + 1e-5); for (var c = 0u; c < p.O; c++) { Y[c * p.T + t] = (X[c * p.T + t] - m) * r * wf(p.woff + c) + wf(p.boff + c); }}
// Y[c,t] = X[c,t] + V[voff + c]@compute @workgroup_size(64)fn addvec(@builtin(global_invocation_id) gi: vec3<u32>) { let i = gi.x; if (i >= p.O * p.T) { return; } Y[i] = X[i] + V[p.voff + i / p.T];}
// ConvTranspose1d(I -> O, kernel 4, stride 2, padding 1) + GELU, fp32 weights [I,O,4]; Tin -> T = 2*Tin@compute @workgroup_size(64)fn convt(@builtin(global_invocation_id) gi: vec3<u32>) { let i = gi.x; if (i >= p.O * p.T) { return; } let o = i / p.T; let t2 = i32(i % p.T); var acc = wf(p.boff + o); for (var k = 0; k < 4; k++) { let num = t2 + 1 - k; if (num >= 0 && (num & 1) == 0 && num / 2 < i32(p.Tin)) { let t = u32(num / 2); for (var c = 0u; c < p.I; c++) { acc = fma(wf(p.woff + (c * p.O + o) * 4u + u32(k)), X[c * p.Tin + t], acc); } } } Y[i] = gelu(acc);}`;
// ---------- CPU helpers (the small speaker / timestep vectors) ----------function erf(x) { const a = Math.abs(x), t = 1 / (1 + 0.3275911 * a); const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-a * a); return x >= 0 ? y : -y; }const gelu = x => 0.5 * x * (1 + erf(x * Math.SQRT1_2));function timestepEmbed(t, dim = 128) { const half = dim / 2, e = new Float32Array(dim); for (let i = 0; i < half; i++) { const a = Math.fround(t * Math.fround(Math.exp(-Math.log(10000) * i / half))); e[i] = Math.sin(a); e[half + i] = Math.cos(a); } return e;}
export class GpuEngine { // buf: ArrayBuffer of trada-int8.bin static async create(buf, device = null) { const u8 = new Uint8Array(buf); if (String.fromCharCode(...u8.subarray(0, 4)) !== 'TRQ8') throw new Error('not a TRQ8 weight file'); const hl = new DataView(buf).getUint32(4, true), hdr = JSON.parse(new TextDecoder().decode(u8.subarray(8, 8 + hl))); const base = Math.ceil((8 + hl) / 16) * 16, blob = buf.slice(base); if (!device) { const ad = await navigator.gpu.requestAdapter(); if (!ad) throw new Error('no WebGPU adapter'); device = await ad.requestDevice({ requiredLimits: { maxStorageBufferBindingSize: ad.limits.maxStorageBufferBindingSize, maxBufferSize: ad.limits.maxBufferSize } }); } return new GpuEngine(device, hdr, blob); } constructor(dev, hdr, blob) { this.dev = dev; this.T = hdr.tensors; this.cfg = hdr.config; this.blob = blob; const W = dev.createBuffer({ size: blob.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); dev.queue.writeBuffer(W, 0, blob); this.W = W; const mod = dev.createShaderModule({ code: WGSL }), ents = []; for (let i = 0; i < 5; i++) ents.push({ binding: i, visibility: GPUShaderStage.COMPUTE, buffer: { type: i === 2 ? 'storage' : 'read-only-storage' } }); ents.push({ binding: 5, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } }); this.bgl = dev.createBindGroupLayout({ entries: ents }); const layout = dev.createPipelineLayout({ bindGroupLayouts: [this.bgl] }); this.P = {}; for (const e of ['qconv', 'dwconv', 'lnorm', 'addvec', 'convt']) this.P[e] = dev.createComputePipeline({ layout, compute: { module: mod, entryPoint: e } }); this.dummy = dev.createBuffer({ size: 16, usage: GPUBufferUsage.STORAGE }); const A = this.cfg.arch; this.enc = { run: f => this.runEnc(f) }; this.cfm2 = { run: f => this.runCfm(f) }; this.dec = { run: f => this.runDec(f) }; this.A = A; } t(name) { const t = this.T[name]; if (!t) throw new Error('missing tensor ' + name); return t; } w4(name) { return this.t(name).off / 4; } // word offset into the weight buffer f32(name) { const t = this.t(name); return new Float32Array(this.blob, t.off, t.shape.reduce((a, b) => a * b, 1)); } // y = W x + b on the CPU (W int8 or fp32), for the per-utterance vectors lin(name, x) { const t = this.t(name + '.weight'), b = this.f32(name + '.bias'), O = t.shape[0], y = new Float32Array(O); if (t.dtype === 'q8') { const q = new Int8Array(this.blob, t.off, O * t.cols_pad), s = new Float32Array(this.blob, t.soff, O); for (let o = 0; o < O; o++) { let a = 0; const r = o * t.cols_pad; for (let j = 0; j < t.cols; j++) a += q[r + j] * x[j]; y[o] = a * s[o] + b[o]; } } else { const w = this.f32(name + '.weight'), J = w.length / O; for (let o = 0; o < O; o++) { let a = 0; for (let j = 0; j < J; j++) a += w[o * J + j] * x[j]; y[o] = a + b[o]; } } return y; }
// ---------- one graph = one command buffer ---------- begin(vecs) { // vecs: Float32Array pieces packed into the V buffer; returns their offsets const offs = []; let n = 0; for (const v of vecs) { offs.push(n); n += v.length; } const all = new Float32Array(Math.max(4, n)); vecs.forEach((v, i) => all.set(v, offs[i])); const V = this.dev.createBuffer({ size: all.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); this.dev.queue.writeBuffer(V, 0, all); return { V, offs, passes: [], bufs: [V] }; } buf(g, n, data = null) { const b = this.dev.createBuffer({ size: Math.max(16, n * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); if (data) this.dev.queue.writeBuffer(b, 0, data); g.bufs.push(b); return b; } pass(g, kernel, prm, X, Y, R = null, wg = null) { const u = { O: 0, I: 0, T: 0, K: 1, pad: 0, J: 0, Jp: 0, woff: 0, soff: 0, boff: 0, mode: 0, goff: 0, voff: NONE, v2off: NONE, Tin: 0, n: 0, ...prm }; g.passes.push({ kernel, u, X, Y, R, wg }); } async finish(g, reads) { // reads: [[buffer, n floats], ...] -> Float32Arrays const dev = this.dev, n = g.passes.length, U = new Uint32Array(n * 64); const keys = ['O', 'I', 'T', 'K', 'pad', 'J', 'Jp', 'woff', 'soff', 'boff', 'mode', 'goff', 'voff', 'v2off', 'Tin', 'n']; g.passes.forEach((ps, i) => keys.forEach((k, j) => { U[i * 64 + j] = ps.u[k] >>> 0; })); const UB = dev.createBuffer({ size: U.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); dev.queue.writeBuffer(UB, 0, U); g.bufs.push(UB); const enc = dev.createCommandEncoder(), cp = enc.beginComputePass(); g.passes.forEach((ps, i) => { const res = [this.W, ps.X || this.dummy, ps.Y, ps.R || this.dummy, g.V]; const bg = dev.createBindGroup({ layout: this.bgl, entries: [...res.map((b, k) => ({ binding: k, resource: { buffer: b } })), { binding: 5, resource: { buffer: UB, offset: i * 256, size: 64 } }] }); cp.setPipeline(this.P[ps.kernel]); cp.setBindGroup(0, bg); if (ps.kernel === 'qconv') cp.dispatchWorkgroups(Math.ceil(ps.u.T / 64), Math.ceil(ps.u.O / 16)); else cp.dispatchWorkgroups(Math.ceil(ps.wg / 64)); }); cp.end(); const rbs = reads.map(([b, k]) => { const rb = dev.createBuffer({ size: k * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); enc.copyBufferToBuffer(b, 0, rb, 0, k * 4); return rb; }); dev.queue.submit([enc.finish()]); const out = []; for (let i = 0; i < rbs.length; i++) { await rbs[i].mapAsync(GPUMapMode.READ); out.push(new Float32Array(rbs[i].getMappedRange()).slice()); rbs[i].destroy(); } for (const b of g.bufs) b.destroy(); return out; } // matmul / conv with int8 weights: name = layer prefix ('.weight', '.bias') qconv(g, name, X, Tin, Y, { T = Tin, K = 1, pad = 0, mode = 0, R = null, goff = 0, voff = NONE, v2off = NONE, n = 0 } = {}) { const t = this.t(name + '.weight'); this.pass(g, 'qconv', { O: t.rows, J: t.cols, Jp: t.cols_pad, K, pad, T, Tin, woff: t.off / 4, soff: t.soff / 4, boff: this.w4(name + '.bias'), mode, goff, voff, v2off, n }, X, Y, R); return t.rows; } // ConvNeXt block on the residual stream A ([C,T]); returns the new stream buffer block(g, pre, C, T, A, tmp, condOff = NONE) { const [B, Cn, H, D] = tmp; this.pass(g, 'dwconv', { O: C, T, woff: this.w4(pre + '.dw.weight'), boff: this.w4(pre + '.dw.bias') }, A, B, null, C * T); this.pass(g, 'lnorm', { O: C, T, woff: this.w4(pre + '.norm.weight'), boff: this.w4(pre + '.norm.bias') }, B, Cn, null, T); this.qconv(g, pre + '.pw1', Cn, T, H, { mode: 1 }); this.qconv(g, pre + '.pw2', H, T, D, { mode: 2, R: A, goff: this.w4(pre + '.gamma'), voff: condOff }); tmp[3] = A; return D; } stream(g, C, T, mult = 3) { return [this.buf(g, C * T), this.buf(g, C * T), this.buf(g, mult * C * T), this.buf(g, C * T)]; }
// ---------- graphs (same feeds / outputs as the ONNX sessions) ---------- async runEnc({ ids, tones, spk }) { const N = ids.dims[1], C = this.A.enc_dim, s = spk.data, x = new Float32Array(C * N); const E = this.f32('enc.emb.weight'), Tn = this.f32('enc.tone_emb.weight'); for (let i = 0; i < N; i++) { const a = Number(ids.data[i]), b = Number(tones.data[i]); for (let c = 0; c < C; c++) x[c * N + i] = E[a * C + c] + Tn[b * C + c]; } const vecs = []; for (let k = 0; k < this.A.enc_blocks; k++) vecs.push(this.lin(`enc.blocks.${k}.cond`, s)); vecs.push(this.lin('dur.spk', s)); const g = this.begin(vecs); let A = this.buf(g, C * N, x); const tmp = this.stream(g, C, N); for (let k = 0; k < this.A.enc_blocks; k++) A = this.block(g, `enc.blocks.${k}`, C, N, A, tmp, g.offs[k]); const h = this.buf(g, C * N); this.pass(g, 'lnorm', { O: C, T: N, woff: this.w4('enc.norm.weight'), boff: this.w4('enc.norm.bias') }, A, h, null, N); const hs = this.buf(g, C * N), d1 = this.buf(g, 160 * N), d2 = this.buf(g, 160 * N), ld = this.buf(g, N); this.pass(g, 'addvec', { O: C, T: N, voff: g.offs[this.A.enc_blocks] }, h, hs, null, C * N); this.qconv(g, 'dur.net.0', hs, N, d1, { K: 3, pad: 1, mode: 1 }); this.qconv(g, 'dur.net.3', d1, N, d2, { K: 3, pad: 1, mode: 1 }); this.qconv(g, 'dur.net.6', d2, N, ld); const [hd, ldd] = await this.finish(g, [[h, C * N], [ld, N]]); return { h: { data: hd, dims: [1, C, N] }, logdur: { data: ldd, dims: [1, N] } }; } async runCfm({ x, cond, t, r, spk }) { const L = this.cfg.latent_dim, Ce = this.A.enc_dim, C = this.A.cfm_dim, T = x.dims[2], s = spk.data, P = 'cfm2'; const si = this.lin(P + '.spk_in', s), film = this.lin(P + '.film', s); const mlp = (pre, v) => this.lin(pre + '.2', this.lin(pre + '.0', v).map(gelu)); const gv = mlp(P + '.tmlp', timestepEmbed(t.data[0])), sg = this.lin(P + '.spk_g', s), rv = mlp(P + '.rmlp', timestepEmbed(r.data[0])); for (let i = 0; i < C; i++) gv[i] += sg[i] + rv[i]; const vecs = [film.subarray(0, C), film.subarray(C)]; for (let k = 0; k < this.A.cfm_blocks; k++) vecs.push(this.lin(`${P}.blocks.${k}.cond`, gv)); const inp = new Float32Array((L + Ce + si.length) * T); inp.set(x.data, 0); inp.set(cond.data, L * T); for (let c = 0; c < si.length; c++) inp.fill(si[c], (L + Ce + c) * T, (L + Ce + c + 1) * T); const g = this.begin(vecs), X0 = this.buf(g, inp.length, inp); let A = this.buf(g, C * T); const tmp = this.stream(g, C, T); this.qconv(g, P + '.inp', X0, T, A, { mode: 3, voff: g.offs[0], v2off: g.offs[1] }); for (let k = 0; k < this.A.cfm_blocks; k++) A = this.block(g, `${P}.blocks.${k}`, C, T, A, tmp, g.offs[2 + k]); const nb = this.buf(g, C * T), v = this.buf(g, L * T); this.pass(g, 'lnorm', { O: C, T, woff: this.w4(P + '.norm.weight'), boff: this.w4(P + '.norm.bias') }, A, nb, null, T); this.qconv(g, P + '.out', nb, T, v); const [vd] = await this.finish(g, [[v, L * T]]); return { v: { data: vd, dims: [1, L, T] } }; } async runDec({ z }) { const L = this.cfg.latent_dim, C = this.A.dec_dim, T = z.dims[2], T2 = 2 * T, F = this.A.n_fft / 2 + 1; const m = this.f32('latent_mean'), sd = this.f32('latent_std'), zz = new Float32Array(L * T); for (let l = 0; l < L; l++) for (let i = 0; i < T; i++) zz[l * T + i] = z.data[l * T + i] * sd[l] + m[l]; const g = this.begin([]), Z = this.buf(g, L * T, zz), h0 = this.buf(g, C * T); this.qconv(g, 'decoder.inp', Z, T, h0, { K: 7, pad: 3 }); let A = this.buf(g, C * T2); const tmp = this.stream(g, C, T2); this.pass(g, 'convt', { O: C, I: C, T: T2, Tin: T, woff: this.w4('decoder.up.weight'), boff: this.w4('decoder.up.bias') }, h0, A, null, C * T2); for (let k = 0; k < this.A.dec_blocks; k++) A = this.block(g, `decoder.blocks.${k}`, C, T2, A, tmp); const nb = this.buf(g, C * T2), out = this.buf(g, 2 * F * T2); this.pass(g, 'lnorm', { O: C, T: T2, woff: this.w4('decoder.norm.weight'), boff: this.w4('decoder.norm.bias') }, A, nb, null, T2); this.qconv(g, 'decoder.head.out', nb, T2, out, { mode: 4, n: F }); const [o] = await this.finish(g, [[out, 2 * F * T2]]); return { mag: { data: o.subarray(0, F * T2), dims: [1, F, T2] }, phase: { data: o.subarray(F * T2), dims: [1, F, T2] } }; }}.gitattributes+1
NOTICE+1-1
README.md+7-2
config.json+9
int8/trada-int8.binAdded+3
onnx/cfm2.int8.onnxAdded+3
onnx/dec.int8.onnxAdded+3
onnx/enc.int8.onnxAdded+3
scripts/export_int8.pyAdded+78
trada_tts/infer.py+7-3
web/app.js+10-10
web/bench.htmlAdded+74
web/index.html+3-3
web/tts.js+30-15
web/wgpu_engine.jsAdded+279