// Backend manager: loads the ONNX graphs of a model set, chooses WebGPU or WebAssembly **per graph** with a start-up // self-test against PyTorch reference cases (05 - browser/README.md: never trust WebGPU untested), and falls back to // WebAssembly per graph if a WebGPU call fails during a run. Works in a Web Worker or on the page. // // const b = new Backend(ort, { baseUrl, threads, preferWebgpu, onState, log }); // await b.init(); // loads, verifies SHA-256, self-tests, creates sessions // const outs = await b.run("f0_step", feeds); // → output data arrays in the graph's output order // b.state → { graphs: { name: { backend, selftest, reason } }, webgpu: { available, adapter }, threads } export const GRAPHS = ["f0_cond", "f0_step", "ac_cond", "ac_step", "vocoder"]; export const MODULE_OF = { f0_cond: "score features", ac_cond: "score features", f0_step: "F0 generator", ac_step: "acoustic generator", vocoder: "vocoder" }; const ARRAYS = { float32: Float32Array, int64: BigInt64Array, int32: Int32Array, bool: Uint8Array }; async function sha256Hex(buf) { const h = await crypto.subtle.digest("SHA-256", buf); return [...new Uint8Array(h)].map((b) => b.toString(16).padStart(2, "0")).join(""); } export class Backend { constructor(ort, { baseUrl, threads = 1, preferWebgpu = true, onState = () => {}, log = () => {}, fetchFn = (...a) => fetch(...a), cacheName = "m01-models" }) { Object.assign(this, { ort, baseUrl: baseUrl.replace(/\/$/, ""), threads, preferWebgpu, onState, log, fetchFn, cacheName }); this.sessions = {}; this.bytes = {}; this.state = { graphs: {}, webgpu: { available: false }, threads }; } async fetchBytes(file, sha) { const url = `${this.baseUrl}/${file}`; let cache = null; try { cache = typeof caches !== "undefined" ? await caches.open(this.cacheName) : null; } catch { cache = null; } const key = sha ? `${url}?sha256=${sha}` : null; if (cache && key) { const hit = await cache.match(key); if (hit) return new Uint8Array(await hit.arrayBuffer()); } const r = await this.fetchFn(url); if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`); const buf = new Uint8Array(await r.arrayBuffer()); if (sha) { const got = await sha256Hex(buf); if (got !== sha) throw new Error(`${file}: SHA-256 ${got.slice(0, 12)}… does not match the manifest (${sha.slice(0, 12)}…)`); if (cache) { try { await cache.put(key, new Response(buf)); } catch { /* storage full or unavailable */ } } } return buf; } async json(file) { return JSON.parse(new TextDecoder().decode(await this.fetchBytes(file, this.manifest?.files?.[file]?.sha256))); } async init(progress = () => {}) { const ort = this.ort; ort.env.wasm.numThreads = this.threads; this.manifest = JSON.parse(new TextDecoder().decode(await this.fetchBytes("manifest.json"))); this.constants = await this.json("m01_constants.json"); const tol = this.constants.selftest_tolerance; // WebGPU availability if (this.preferWebgpu && typeof navigator !== "undefined" && navigator.gpu) { try { const ad = await navigator.gpu.requestAdapter(); if (ad) this.state.webgpu = { available: true, adapter: { vendor: ad.info?.vendor, architecture: ad.info?.architecture } }; else this.state.webgpu = { available: false, reason: "no WebGPU adapter" }; } catch (e) { this.state.webgpu = { available: false, reason: String(e) }; } } else { this.state.webgpu = { available: false, reason: this.preferWebgpu ? "WebGPU not supported by this browser" : "WebAssembly chosen in the settings" }; } let i = 0; for (const g of GRAPHS) { progress({ stage: "loading models", done: i++, total: GRAPHS.length }); this.bytes[g] = await this.fetchBytes(`${g}.onnx`, this.manifest.files[`${g}.onnx`].sha256); const st = { backend: "wasm", selftest: null, reason: null }; if (this.state.webgpu.available) { try { const s = await ort.InferenceSession.create(this.bytes[g], { executionProviders: ["webgpu"] }); const r = await this.selftest(s, g, tol[g] ?? tol.default); st.selftest = r; if (r.pass) { this.sessions[g] = s; st.backend = "webgpu"; } else { st.reason = `WebGPU self-test failed (relative difference ${r.relative.toExponential(1)})`; await s.release(); } } catch (e) { st.reason = `WebGPU unavailable for this graph: ${e.message ?? e}`; } } else st.reason = this.state.webgpu.reason; if (st.backend === "wasm") { this.sessions[g] = await ort.InferenceSession.create(this.bytes[g], { executionProviders: ["wasm"] }); if (st.reason) this.log(`${g}: WebAssembly (${st.reason})`); } else this.log(`${g}: WebGPU (self-test relative difference ${st.selftest.relative.toExponential(1)})`); this.state.graphs[g] = st; this.onState(this.state); } progress({ stage: "loading models", done: GRAPHS.length, total: GRAPHS.length }); return this.state; } async selftest(session, g, tol) { const man = await this.json(`selftest/${g}.json`); const feeds = {}, refs = {}; for (const [k, v] of Object.entries(man.inputs)) feeds[k] = new this.ort.Tensor(v.dtype, new ARRAYS[v.dtype]((await this.fetchBytes(`selftest/${v.file}`, this.manifest.files[`selftest/${v.file}`]?.sha256)).buffer), v.dims); for (const [k, v] of Object.entries(man.outputs)) refs[k] = new Float32Array((await this.fetchBytes(`selftest/${v.file}`, this.manifest.files[`selftest/${v.file}`]?.sha256)).buffer); const out = await session.run(feeds); let rel = 0; for (const [k, ref] of Object.entries(refs)) { const got = out[k].data; let d = 0, sc = 0; for (let i = 0; i < ref.length; i++) { const e = Math.abs(got[i] - ref[i]); d = Number.isNaN(e) ? Infinity : Math.max(d, e); sc = Math.max(sc, Math.abs(ref[i])); } rel = Math.max(rel, d / Math.max(sc, 1e-12)); } return { relative: rel, tolerance: tol, pass: rel < tol }; } /** Run a graph; on a WebGPU error, switch this graph to WebAssembly (logged, state updated) and retry once. */ async run(g, feeds) { const s = this.sessions[g]; try { const out = await s.run(feeds); return s.outputNames.map((k) => out[k].data); } catch (e) { if (this.state.graphs[g].backend !== "webgpu") throw e; this.log(`${g}: WebGPU failed during the run (${e.message ?? e}); switching this graph to WebAssembly`); try { await s.release(); } catch { /* ignore */ } this.sessions[g] = await this.ort.InferenceSession.create(this.bytes[g], { executionProviders: ["wasm"] }); this.state.graphs[g] = { ...this.state.graphs[g], backend: "wasm", reason: `fell back during a run: ${e.message ?? e}` }; this.onState(this.state); const s2 = this.sessions[g]; const out = await s2.run(feeds); return s2.outputNames.map((k) => out[k].data); } } }