Experimental opt-in ?capture=1: A/B of ORT WebGPU graph capture for the speech-to-motion step and the renderer
Browse filesOpt-in only; failures are caught and printed. Verified on a software adapter only: a tiny model replays correctly, the real flow graph runs once but a second replay errors there, so real-GPU behaviour is unknown.
33 unmodified lines34353637383940116 unmodified lines1571581591601611621635 unmodified lines1691701711721731741758 unmodified lines18418518618718818919019119219319433 unmodified linesfor (let i = 0; i < 65536; i++) { const s = i & 0x8000 ? -1 : 1, e = (i >> 10) & 31, f = i & 1023; HALF[i] = e === 0 ? s * f * 2 ** -24 : e === 31 ? (f ? NaN : s * Infinity) : s * (1 + f / 1024) * 2 ** (e - 15); }// ------------------------------------------------------------ model loadinglet flowSess = null, frameMedian = 0, sess = null, F16 = false, basis = null, feats = null, xr = null, running = false, token = 0;async function fetchBytes(url, label, base, span) { // download with progress; the browser cache keeps it for next timeconst r = await fetch(url); if (!r.ok) throw new Error(`${label}: HTTP ${r.status}`);116 unmodified linesconst med = (a) => a.slice().sort((x, y) => x - y)[a.length >> 1], p95 = (a) => a.slice().sort((x, y) => x - y)[Math.floor(a.length * 0.95)];const m = med(tot), msg = `${ui.gpu.textContent}\nframe (render + read back + paint): median ${m.toFixed(1)} ms, p95 ${p95(tot).toFixed(1)} ms, render+read back median ${med(gpu).toFixed(1)} ms\n` +`= ${(1000 / m).toFixed(1)} fps; a 10-frame block takes about ${(10 * m).toFixed(0)} ms of the 400 ms budget (the speech-to-motion step still has to fit in the rest)`;frameMedian = m; ui.out.textContent = msg; ui.out.hidden = false; status('Benchmark done.', 1);if (was) { running = true; loop(token); }}5 unmodified linestry {const dt = q.get('flow') === '32' ? 'fp32' : (F16 ? 'fp16' : 'fp32'), half = dt === 'fp16';if (!flowSess || flowSess.dt !== dt) {const b = await fetchBytes(`${MODELS}flow_step_${dt}.onnx`, `speech-to-motion step (${dt})`, 0, 0.8);status('Preparing the GPU programs…', 0.85); const t = performance.now();flowSess = { dt, s: await ort.InferenceSession.create(b, { executionProviders: ['webgpu'], graphOptimizationLevel: 'all', logSeverityLevel: 3 }), ms: Math.round(performance.now() - t) };}8 unmodified lineslet msg = `speech-to-motion step (${dt}): median ${med.toFixed(1)} ms per pass; a block needs about 9 passes = ${(9 * med).toFixed(0)} ms (GPU programs built in ${flowSess.ms} ms)\n`;msg += fm ? `renderer: ${(10 * fm).toFixed(0)} ms for 10 frames (from the last Benchmark)\nESTIMATED BLOCK: ${(9 * med + 10 * fm).toFixed(0)} ms of the 400 ms budget (${(400 / (9 * med + 10 * fm)).toFixed(2)}× real time; above 1.0 is fast enough)\nNote: random inputs, passes run one after another (a single GPU queue does not overlap them with rendering), no speech recognition, language model or voice counted.`: 'Run Benchmark first to add the renderer time and get the full-block estimate.';ui.out.textContent = (ui.out.hidden ? '' : ui.out.textContent + '\n\n') + msg; ui.out.hidden = false; status('Full-block test done.', 1);} catch (e) { console.error(e); status(`Full-block test failed: ${e.message || e}`, null, true); }ui.bflow.disabled = false; if (was) { running = true; loop(token); }}// ------------------------------------------------------------ UIasync function checkFeats(src) {if (!GPUFEATS || featsChecked) return;33 unmodified lines34353637383940116 unmodified lines1571581591601611621631641651661671681691701711721731741755 unmodified lines1811821831841851861878 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424533 unmodified linesfor (let i = 0; i < 65536; i++) { const s = i & 0x8000 ? -1 : 1, e = (i >> 10) & 31, f = i & 1023; HALF[i] = e === 0 ? s * f * 2 ** -24 : e === 31 ? (f ? NaN : s * Infinity) : s * (1 + f / 1024) * 2 ** (e - 15); }// ------------------------------------------------------------ model loadinglet flowBytes = null, flowSess = null, frameMedian = 0, sess = null, F16 = false, basis = null, feats = null, xr = null, running = false, token = 0;async function fetchBytes(url, label, base, span) { // download with progress; the browser cache keeps it for next timeconst r = await fetch(url); if (!r.ok) throw new Error(`${label}: HTTP ${r.status}`);116 unmodified linesconst med = (a) => a.slice().sort((x, y) => x - y)[a.length >> 1], p95 = (a) => a.slice().sort((x, y) => x - y)[Math.floor(a.length * 0.95)];const m = med(tot), msg = `${ui.gpu.textContent}\nframe (render + read back + paint): median ${m.toFixed(1)} ms, p95 ${p95(tot).toFixed(1)} ms, render+read back median ${med(gpu).toFixed(1)} ms\n` +`= ${(1000 / m).toFixed(1)} fps; a 10-frame block takes about ${(10 * m).toFixed(0)} ms of the 400 ms budget (the speech-to-motion step still has to fit in the rest)`;frameMedian = m;if (q.has('capture')) { // optional A/B: ?capture=1 (or a frame count)try {const shapes = { wa: [1, 512] }; FEAT_SHAPES.forEach((sh, i) => { shapes[`f${i}`] = sh; });const wa = style(0, +ui.amp.value, +ui.spd.value); const data = { wa: { data: wa.data } };for (let i = 0; i < FEAT_SHAPES.length; i++) { const d = await feats[i].getData(); data[`f${i}`] = { data: d }; }const dtype = F16 ? 'float16' : 'float32', mk = (k) => new ort.Tensor(dtype, data[k].data, shapes[k]);const plainRun = async () => exclusive(async () => { const o = await sess.dec.run(Object.fromEntries(Object.keys(shapes).map((k) => [k, mk(k)]))); return await o.img.getData(); });const ab = await captureAB('Renderer', modelBytes.dec, shapes, 'img', [1, 3, SIZE, SIZE], data, plainRun, +q.get('capture') > 1 ? +q.get('capture') : 20, F16);msg += `\nGRAPH CAPTURE (renderer): ${ab.batched.toFixed(1)} ms per frame when frames are chained, ${ab.withRead.toFixed(1)} ms per frame with a read-back after each (plain: ${m.toFixed(1)} ms); a 10-frame block: ${(10 * ab.batched).toFixed(0)} ms chained / ${(10 * ab.withRead).toFixed(0)} ms with read-backs. Check vs plain: max pixel difference ${ab.maxDiff.toExponential(2)}.`;} catch (e) { console.error(e); msg += `\nGRAPH CAPTURE (renderer) failed: ${e.message || e}`; }}ui.out.textContent = msg; ui.out.hidden = false; status('Benchmark done.', 1);if (was) { running = true; loop(token); }}5 unmodified linestry {const dt = q.get('flow') === '32' ? 'fp32' : (F16 ? 'fp16' : 'fp32'), half = dt === 'fp16';if (!flowSess || flowSess.dt !== dt) {const b = await fetchBytes(`${MODELS}flow_step_${dt}.onnx`, `speech-to-motion step (${dt})`, 0, 0.8); flowBytes = b;status('Preparing the GPU programs…', 0.85); const t = performance.now();flowSess = { dt, s: await ort.InferenceSession.create(b, { executionProviders: ['webgpu'], graphOptimizationLevel: 'all', logSeverityLevel: 3 }), ms: Math.round(performance.now() - t) };}8 unmodified lineslet msg = `speech-to-motion step (${dt}): median ${med.toFixed(1)} ms per pass; a block needs about 9 passes = ${(9 * med).toFixed(0)} ms (GPU programs built in ${flowSess.ms} ms)\n`;msg += fm ? `renderer: ${(10 * fm).toFixed(0)} ms for 10 frames (from the last Benchmark)\nESTIMATED BLOCK: ${(9 * med + 10 * fm).toFixed(0)} ms of the 400 ms budget (${(400 / (9 * med + 10 * fm)).toFixed(2)}× real time; above 1.0 is fast enough)\nNote: random inputs, passes run one after another (a single GPU queue does not overlap them with rendering), no speech recognition, language model or voice counted.`: 'Run Benchmark first to add the renderer time and get the full-block estimate.';if (q.has('capture')) { // optional A/B: ?capture=1try {const feedCheck = {}; for (const k of Object.keys(shapes)) feedCheck[k] = feed[k];const plainRun = async () => { const r = await exclusive(async () => { const o = await flowSess.s.run(feed); return await o.y.getData(); }); return r; };const ab = await captureAB('Speech-to-motion step', flowBytes, shapes, 'y', [2, 12, 512], Object.fromEntries(Object.entries(feed).map(([k, t]) => [k, { data: t.data }])), plainRun, +q.get('capture') > 1 ? +q.get('capture') : 15, half);msg += `\nGRAPH CAPTURE (speech-to-motion step): ${ab.batched.toFixed(1)} ms per pass when passes are chained, ${ab.withRead.toFixed(1)} ms per pass with a read-back after each (plain: ${med.toFixed(1)} ms); block of 9 passes: ${(9 * ab.batched).toFixed(0)} ms chained / ${(9 * ab.withRead).toFixed(0)} ms with read-backs. Check vs plain: max difference ${ab.maxDiff.toExponential(2)} (mean |output| ${ab.meanRef.toFixed(2)}).`;} catch (e) { console.error(e); msg += `\nGRAPH CAPTURE failed: ${e.message || e}`; }}ui.out.textContent = (ui.out.hidden ? '' : ui.out.textContent + '\n\n') + msg; ui.out.hidden = false; status('Full-block test done.', 1);} catch (e) { console.error(e); status(`Full-block test failed: ${e.message || e}`, null, true); }ui.bflow.disabled = false; if (was) { running = true; loop(token); }}// ------------------------------------------------------------ graph capture A/B (timing on random inputs)// ORT's WebGPU "graph capture" records the GPU commands once and replays them, which removes the per-call CPU cost when the CPU is the bottleneck.// Inputs/outputs live in GPU buffers that we fill with queue.writeBuffer. NOTE: do not call promise-based GPU APIs (mapAsync, onSubmittedWorkDone) on ORT's device:// results are read back through a plain "identity" ONNX session instead (ORT does the download itself).const gauss = () => Math.sqrt(-2 * Math.log(Math.random() + 1e-12)) * Math.cos(2 * Math.PI * Math.random());async function ortDevice() { let d = ort.env.webgpu.device; if (d && typeof d.then === 'function') d = await d; return d; }async function captureAB(label, bytes, shapes, outName, outDims, plainFeed, plainRun, n, half) {const device = await ortDevice(); if (!device) throw new Error('no GPU device from ORT');const dtype = half ? 'float16' : 'float32', bpe = half ? 2 : 4, dt = half ? 'fp16' : 'fp32';const toBits = (a) => (half ? Uint16Array.from(a, toHalf) : a);status(`${label}: building the captured session…`, 0.92);const cs = await ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], enableGraphCapture: true, graphOptimizationLevel: 'all', logSeverityLevel: 3, preferredOutputLocation: { [outName]: 'gpu-buffer' } });const rd = await ort.InferenceSession.create(await (await fetch(`${MODELS}ident_r${outDims.length}_${dt}.onnx`)).arrayBuffer(), { executionProviders: ['webgpu'], logSeverityLevel: 3 });const bufs = {}, tens = {}, round = (x) => Math.ceil(x / 16) * 16;for (const [k, sh] of Object.entries(shapes)) {const cnt = sh.reduce((a, b) => a * b, 1); bufs[k] = device.createBuffer({ size: round(cnt * bpe), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });device.queue.writeBuffer(bufs[k], 0, plainFeed[k].data); tens[k] = ort.Tensor.fromGpuBuffer(bufs[k], { dataType: dtype, dims: sh });}const outCnt = outDims.reduce((a, b) => a * b, 1), outBuf = device.createBuffer({ size: round(outCnt * bpe), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });const outT = ort.Tensor.fromGpuBuffer(outBuf, { dataType: dtype, dims: outDims });const readOut = async () => { const d = await (await rd.run({ x: outT })).y.getData(); return d instanceof Uint16Array ? Float32Array.from(d, (v) => HALF[v]) : Float32Array.from(d); };await cs.run(tens, { [outName]: outT }); const capOut = await readOut(); // first run records the graphconst ref = await plainRun(); const refArr = ref instanceof Uint16Array ? Float32Array.from(ref, (v) => HALF[v]) : Float32Array.from(ref);let mx = 0, sa = 0; for (let i = 0; i < capOut.length; i++) { const d = Math.abs(capOut[i] - refArr[i]); if (d > mx) mx = d; sa += Math.abs(refArr[i]); }for (let i = 0; i < 3; i++) await cs.run(tens, { [outName]: outT }); await readOut();let t = performance.now(); for (let i = 0; i < n; i++) await cs.run(tens, { [outName]: outT }); await readOut(); const batched = (performance.now() - t) / n; // many passes, one read-back at the endt = performance.now(); for (let i = 0; i < n; i++) { await cs.run(tens, { [outName]: outT }); await readOut(); } const withRead = (performance.now() - t) / n; // a read-back after every passfor (const b of Object.values(bufs)) b.destroy?.(); outBuf.destroy?.();return { batched, withRead, maxDiff: mx, meanRef: sa / capOut.length };}// ------------------------------------------------------------ UIasync function checkFeats(src) {if (!GPUFEATS || featsChecked) return;
app.js+54-3