Keep the identity features on the GPU between encoder and renderer (no 36 MB re-upload per frame); falls back automatically. ?gpufeats=0 turns it off for A/B
Browse filesVerified pixel-identical to the previous path on a software WebGPU adapter. Note: drawing to a canvas from ORT's device breaks later ORT runs (and so do queue.onSubmittedWorkDone / popErrorScope on that device), so a direct GPU-to-canvas path is not used.
50 unmodified lines5152535455565758596061626364656667596869701 unmodified line7273747576686977787980818212 unmodified lines959697989910010117 unmodified lines11912012111112212312412512612712812913013113257 unmodified lines1901911921931941951961971981992002011822022032042058 unmodified lines21421521619721721821922050 unmodified lines return { a, f16: a.features.has('shader-f16'), name: [i.vendor, i.architecture, i.description].filter(Boolean).join(' ') || 'unknown GPU', soft: /swiftshader|llvmpipe|software/i.test(`${i.architecture} ${i.description}`) };}
let modelBytes = null, GPUFEATS = false, featsChecked = false;const FEAT_NAMES = FEAT_SHAPES.map((_, i) => `f${i}`);async function makeSessions(gpuFeats) { // gpuFeats: the 7 identity feature maps (~36 MB in fp16) stay on the GPU instead of being re-uploaded for every frame const base = { executionProviders: ['webgpu'], graphOptimizationLevel: 'all', logSeverityLevel: 3 }; const encOpts = gpuFeats ? { ...base, preferredOutputLocation: { x_r: 'cpu', ...Object.fromEntries(FEAT_NAMES.map((n) => [n, 'gpu-buffer'])) } } : base; const t = performance.now(); sess = { enc: await ort.InferenceSession.create(modelBytes.enc, encOpts), dec: await ort.InferenceSession.create(modelBytes.dec, base) }; sess.load = Math.round(performance.now() - t);}async function loadModels() { if (sess) return; const info = await adapterInfo(); const want16 = info.f16 && q.get('fp') !== '32'; ort.env.wasm.numThreads = 1; ort.env.webgpu.powerPreference = 'high-performance'; ort.env.logLevel = 'error'; const opts = { executionProviders: ['webgpu'], graphOptimizationLevel: 'all', logSeverityLevel: 3 }; const bb = await fetchBytes(MODELS + 'motion_basis_512x20.f32', 'motion basis', 0, 0.01); basis = new Float32Array(bb.buffer, bb.byteOffset, 512 * 20); for (const half of want16 ? [true, false] : [false]) { // fp16 first (smaller, faster); if this GPU/browser rejects it, fall back to fp32 const dt = half ? 'fp16' : 'fp32'; F16 = half;1 unmodified line try { const encB = await fetchBytes(`${MODELS}encoder_${dt}.onnx`, `portrait encoder (${dt})`, 0.01, 0.2); const decB = await fetchBytes(`${MODELS}decoder_${dt}.onnx`, `renderer (${dt})`, 0.21, 0.4); modelBytes = { enc: encB, dec: decB }; status('Preparing the GPU programs (first time only, can take a little while)…', 0.62); const t = performance.now(); sess = { enc: await ort.InferenceSession.create(encB, opts), dec: await ort.InferenceSession.create(decB, opts), load: Math.round(performance.now() - t) }; GPUFEATS = q.get('gpufeats') !== '0'; try { await makeSessions(GPUFEATS); } catch (e) { if (!GPUFEATS) throw e; console.warn('GPU-resident features failed, using plain tensors:', e); GPUFEATS = false; await makeSessions(false); } ui.gpu.textContent += GPUFEATS ? ' · features kept on GPU' : ' · features re-uploaded per frame'; status(`Models ready (GPU programs built in ${sess.load} ms).`, 1); return; } catch (e) { console.warn(`${dt} models failed:`, e); sess = null; if (!half) throw e; status('fp16 did not work on this GPU, trying fp32…', 0.3); } }12 unmodified lines const out = await exclusive(() => sess.enc.run({ img: tensorFrom(x, [1, 3, SIZE, SIZE]) })); const encMs = Math.round(performance.now() - t); const xd = await out.x_r.getData(); xr = xd instanceof Uint16Array ? Float32Array.from(xd, (v) => HALF[v]) : Float32Array.from(xd); // fp16 comes back as raw bits (Uint16Array) or, in current Chrome, as a Float16Array of real numbers if (feats) for (const t of feats) { try { t.dispose(); } catch { /* already released */ } } // free the previous portrait's GPU buffers feats = FEAT_SHAPES.map((_, i) => out[`f${i}`]); // stay as tensors: they are fed to the renderer every frame ctx2d.drawImage(c, 0, 0); return encMs;17 unmodified lines for (let j = 0; j < 512; j++) { let s = xr[j]; for (let i = 0; i < 20; i++) s += basis[j * 20 + i] * lam[i]; wa[j] = s; } return tensorFrom(wa, [1, 512]);}async function frame(t) {async function frameCpu(t) { const feed = { wa: style(t, +ui.amp.value, +ui.spd.value) }; FEAT_SHAPES.forEach((_, i) => { feed[`f${i}`] = feats[i]; }); const t0 = performance.now(); const out = await exclusive(async () => { const o = await sess.dec.run(feed); o.u = await o.img.getData(); return o; }); const u = out.u; const t1 = performance.now(); paint(u); const t2 = performance.now(); out.img.dispose?.(); return { gpu: t1 - t0, draw: t2 - t1 };}
const frame = frameCpu;const ema = { gpu: 0, draw: 0, tot: 0 };async function loop(my) { let last = performance.now(), t0 = last, n = 0;57 unmodified lines}
// ------------------------------------------------------------ UIasync function checkFeats(src) { if (!GPUFEATS || featsChecked) return; try { await frameCpu(0); featsChecked = true; } catch (e) { console.warn('GPU-resident features failed on the first frame, using plain tensors:', e); GPUFEATS = false; status('Falling back to the plain path…', 0.7); await makeSessions(false); await loadPortrait(src); ui.gpu.textContent = ui.gpu.textContent.replace('features kept on GPU', 'features re-uploaded per frame'); }}async function useAvatar(src) { try { token++; running = false; ui.pause.textContent = 'Pause'; status('Reading the portrait…', 0.7); await loadModels(); const ms = await loadPortrait(src); try { token++; running = false; ui.pause.textContent = 'Pause'; status('Reading the portrait…', 0.7); await loadModels(); const ms = await loadPortrait(src); await checkFeats(src); status(`Portrait encoded in ${ms} ms. Press Start.`, 1); ui.start.disabled = false; ui.bench.disabled = false; ui.bflow.disabled = false; ui.pause.disabled = true; } catch (e) { console.error(e); status(e.message || String(e), null, true); }}8 unmodified linesui.bench.addEventListener('click', benchmark);ui.bflow.addEventListener('click', flowBenchmark);document.addEventListener('visibilitychange', () => { if (document.hidden && running) { running = false; ui.pause.textContent = 'Resume'; } }); // do not burn the GPU in a background tabwindow.__av = { useAvatar, benchmark, frame, paint, pixel: (x, y) => [...imgData.data.slice((y * SIZE + x) * 4, (y * SIZE + x) * 4 + 4)], state: () => ({ F16, ema }) }; // test hookwindow.__av = { useAvatar, benchmark, frame, paint, gpufeats: () => GPUFEATS, pixel: (x, y) => [...imgData.data.slice((y * SIZE + x) * 4, (y * SIZE + x) * 4 + 4)], state: () => ({ F16, ema }) }; // test hookadapterInfo().then((i) => { // check the GPU up front so nobody clicks a portrait and waits just to be told no ui.gpu.textContent = `${i.name} · shader-f16: ${i.f16 ? 'yes' : 'no'}${i.soft ? ' · SOFTWARE adapter, timings are meaningless' : ''}`; status(`Pick a portrait to begin (about ${i.f16 && q.get('fp') !== '32' ? 100 : 185} MB of models, downloaded once).`, 0);app.js+26-6