Spaces:
Running

phonon-2-webgpu / worker.js
mfn
Initial WebGPU demo
5ad985a
Raw History Blame Contribute Delete
7.76 kB
// Phonon-2 in the browser: onnxruntime-web, encoder on WebGPU, greedy TDT decode in JS.
// Weights: https://huggingface.co/tiyuvta/Phonon-2-ONNX (onnx-asr nemo-conformer-tdt layout).
const ORT_VERSION = "1.30.0";
const ORT_BASE = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`;
const REPO = "https://huggingface.co/tiyuvta/Phonon-2-ONNX/resolve/main/";
const FILES = {
pre: "preprocessor-model.onnx",
enc: "encoder-model.exact4x2.onnx",
dec: "decoder_joint-model.onnx",
vocab: "vocab.txt",
};
const CACHE_NAME = "phonon2-onnx-v1";
const SR = 16000;
const BLANK = 8192;
const N_DUR = 5; // durations 0..4
const MAX_SYMBOLS = 10;
const FRAME_SEC = 0.08; // 10 ms hop x 8 subsampling
const CHUNK_SEC = 30; // cut long audio at pauses, <= 30 s per chunk
let ort = null;
let sessions = null;
let vocab = null;
let backend = "wasm";
const post = (type, data = {}) => self.postMessage({ type, ...data });
async function fetchWithProgress(name, onBytes) {
const url = REPO + name;
let cache = null;
try {
cache = await caches.open(CACHE_NAME);
const hit = await cache.match(url);
if (hit) {
const buf = new Uint8Array(await hit.arrayBuffer());
onBytes(buf.byteLength, buf.byteLength, true);
return buf;
}
} catch (_) {
cache = null;
}
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} for ${name}`);
const total = Number(res.headers.get("content-length")) || 0;
const reader = res.body.getReader();
const parts = [];
let got = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
parts.push(value);
got += value.byteLength;
onBytes(got, total || got, false);
}
const buf = new Uint8Array(got);
let off = 0;
for (const p of parts) {
buf.set(p, off);
off += p.byteLength;
}
if (cache) {
try {
await cache.put(url, new Response(buf, { headers: { "content-type": "application/octet-stream" } }));
} catch (_) {
/* quota or private mode: ignore */
}
}
return buf;
}
async function load(useWebGPU) {
post("status", { text: "Loading runtime" });
ort = await import(ORT_BASE + "ort.webgpu.min.mjs");
ort.env.wasm.wasmPaths = ORT_BASE;
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
const names = Object.keys(FILES);
const progress = Object.fromEntries(names.map((k) => [k, { got: 0, total: 0 }]));
const report = () => {
let got = 0, total = 0;
for (const k of names) {
got += progress[k].got;
total += progress[k].total;
}
post("progress", { got, total, files: progress });
};
const bufs = await Promise.all(
names.map((k) =>
fetchWithProgress(FILES[k], (got, total) => {
progress[k] = { got, total };
report();
}).then((b) => [k, b])
)
);
const b = Object.fromEntries(bufs);
vocab = new TextDecoder().decode(b.vocab).split("\n").reduce((acc, line) => {
const i = line.lastIndexOf(" ");
if (i > 0) acc[Number(line.slice(i + 1))] = line.slice(0, i);
return acc;
}, []);
post("status", { text: "Creating sessions" });
const wasmOpts = { executionProviders: ["wasm"], graphOptimizationLevel: "all" };
let enc = null;
if (useWebGPU) {
try {
enc = await ort.InferenceSession.create(b.enc, { executionProviders: ["webgpu"], graphOptimizationLevel: "all" });
backend = "webgpu";
} catch (e) {
post("warn", { text: `WebGPU session failed (${e.message || e}); falling back to WASM.` });
}
}
if (!enc) {
enc = await ort.InferenceSession.create(b.enc, wasmOpts);
backend = "wasm";
}
const pre = await ort.InferenceSession.create(b.pre, wasmOpts);
const dec = await ort.InferenceSession.create(b.dec, wasmOpts);
sessions = { pre, enc, dec };
post("ready", { backend, threads: ort.env.wasm.numThreads });
}
function splitChunks(wav) {
const max = CHUNK_SEC * SR;
const out = [];
let start = 0;
const win = SR / 10;
while (wav.length - start > max) {
const lo = start + max - 5 * SR;
let best = lo, bestE = Infinity;
for (let s = lo; s + win <= start + max; s += win / 2) {
let e = 0;
for (let i = s; i < s + win; i++) e += wav[i] * wav[i];
if (e < bestE) {
bestE = e;
best = s + win / 2;
}
}
out.push([start, best]);
start = best;
}
out.push([start, wav.length]);
return out;
}
function argmax(arr, from, to) {
let bi = from, bv = arr[from];
for (let i = from + 1; i < to; i++) if (arr[i] > bv) { bv = arr[i]; bi = i; }
return bi - from;
}
async function transcribeChunk(wav, offsetSec) {
const { pre, enc, dec } = sessions;
const T = ort.Tensor;
const p = await pre.run({
waveforms: new T("float32", wav, [1, wav.length]),
waveforms_lens: new T("int64", BigInt64Array.from([BigInt(wav.length)]), [1]),
});
const e = await enc.run({ audio_signal: p.features, length: p.features_lens });
const encOut = e.outputs; // [1, 1024, T']
const D = encOut.dims[1];
const Tp = Number(e.encoded_lengths.data[0]);
const stride = encOut.dims[2];
const encData = encOut.data instanceof Float32Array ? encOut.data : await encOut.getData();
const frame = new Float32Array(D);
let s1 = new T("float32", new Float32Array(2 * 640), [2, 1, 640]);
let s2 = new T("float32", new Float32Array(2 * 640), [2, 1, 640]);
let prev = BLANK;
const tokens = [];
let t = 0, onFrame = 0;
const tl = new T("int32", Int32Array.from([1]), [1]);
while (t < Tp) {
for (let d = 0; d < D; d++) frame[d] = encData[d * stride + t];
const out = await dec.run({
encoder_outputs: new T("float32", frame, [1, D, 1]),
targets: new T("int32", Int32Array.from([prev]), [1, 1]),
target_length: tl,
input_states_1: s1,
input_states_2: s2,
});
const logits = out.outputs.data;
const tok = argmax(logits, 0, BLANK + 1);
let dur = argmax(logits, BLANK + 1, BLANK + 1 + N_DUR);
if (tok !== BLANK) {
tokens.push({ id: tok, t });
prev = tok;
s1 = out.output_states_1;
s2 = out.output_states_2;
onFrame++;
}
if (tok === BLANK && dur === 0) dur = 1;
if (dur === 0 && onFrame >= MAX_SYMBOLS) dur = 1;
if (dur > 0) onFrame = 0;
t += dur;
}
const words = [];
let text = "";
for (const { id, t: ft } of tokens) {
const piece = vocab[id] || "";
if (piece === "<unk>" || piece === "<pad>" || /^<\|.*\|>$/.test(piece)) continue;
const s = piece.replace(/▁/g, " ");
text += s;
const time = offsetSec + ft * FRAME_SEC;
if (s.startsWith(" ") || !words.length) words.push({ w: s.trim(), t: time });
else words[words.length - 1].w += s;
}
return { text: text.trim(), words: words.filter((w) => w.w) };
}
async function transcribe(wav) {
const t0 = performance.now();
const chunks = splitChunks(wav);
const texts = [];
const words = [];
for (let i = 0; i < chunks.length; i++) {
const [a, b] = chunks[i];
post("status", { text: chunks.length > 1 ? `Transcribing chunk ${i + 1}/${chunks.length}` : "Transcribing" });
const r = await transcribeChunk(wav.subarray(a, b), a / SR);
texts.push(r.text);
words.push(...r.words);
post("partial", { text: texts.filter(Boolean).join(" ") });
}
const secs = (performance.now() - t0) / 1000;
post("result", { text: texts.filter(Boolean).join(" "), words, secs, audioSecs: wav.length / SR, backend });
}
self.onmessage = async ({ data }) => {
try {
if (data.type === "load") await load(data.webgpu);
else if (data.type === "transcribe") await transcribe(data.audio);
} catch (e) {
post("error", { text: String((e && e.message) || e) });
}
};