Text-to-Speech
ONNX
Vietnamese
vietnamese
flow-matching
webgpu
on-device
trada-tts / web /wgpu_engine.js
tsdocode's picture
int8: WGSL WebGPU engine (int8/trada-int8.bin) + int8 ONNX graphs
511b660 verified
Raw History Blame Contribute Delete
17.4 kB
// 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 is
const 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] } };
}
}