File size: 19,627 Bytes
be19578 bf2fce9 be19578 b01a2b5 be19578 0355509 be19578 0355509 be19578 0355509 be19578 f57d8e2 0355509 be19578 f57d8e2 be19578 f57d8e2 be19578 0355509 be19578 0355509 be19578 f57d8e2 be19578 b01a2b5 be19578 bf2fce9 b01a2b5 bf2fce9 be19578 0355509 be19578 0355509 bf2fce9 be19578 bf2fce9 be19578 0355509 be19578 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | // Avatar Forcing renderer in the browser (WebGPU, onnxruntime-web).
// The model (Ki et al., CVPR 2026) turns ONE portrait plus a stream of 20-number "motion" vectors into video frames.
// This page runs the real portrait encoder and the real StyleGAN-style decoder on your GPU and drives them with a synthetic motion
// signal, so you can see the quality and measure whether your GPU can render the 25 frames per second a live avatar needs.
// Not included yet: the speech-to-motion transformer, speech recognition, the language model and voice (see the notes on the page).
import * as ort from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
const q = new URLSearchParams(location.search);
const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // same-origin test hook only
const MODELS = local(q.get('models')) || 'https://huggingface.co/WeReCooking/AvatarForcing-ONNX-WebGPU/resolve/main/';
const $ = (id) => document.getElementById(id);
const ui = { status: $('status'), bar: $('bar').firstElementChild, canvas: $('view'), fps: $('fps'), ms: $('ms'), verdict: $('verdict'), gpu: $('gpu'),
start: $('start'), pause: $('pause'), bench: $('bench'), bflow: $('bflow'), amp: $('amp'), spd: $('spd'), file: $('file'), avatars: $('avatars'), out: $('benchout') };
const ctx2d = ui.canvas.getContext('2d');
const AVATARS = [['rumi', 'Rumi'], ['vicky', 'Vicky'], ['ken', 'Ken'], ['amber', 'Amber']];
const SIZE = 512, FEAT_SHAPES = [[1, 512, 8, 8], [1, 512, 16, 16], [1, 512, 32, 32], [1, 256, 64, 64], [1, 128, 128, 128], [1, 64, 256, 256], [1, 32, 512, 512]];
const mb = (b) => `${Math.round(b / 1e6)} MB`;
// ORT-Web's WebGPU backend hangs if two session.run() calls overlap (verified), and Pause / Benchmark / switching portrait can overlap a frame in flight: one lock for all runs.
let lock = Promise.resolve();
const exclusive = (fn) => { const r = lock.then(fn); lock = r.catch(() => {}); return r; };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const yieldNow = () => new Promise((r) => { const c = new MessageChannel(); c.port1.onmessage = () => r(); c.port2.postMessage(0); }); // no 4 ms setTimeout clamp between frames
function status(t, frac = null, bad = false) { ui.status.textContent = t; ui.status.classList.toggle('bad', bad); if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`; }
// ------------------------------------------------------------ float16 helpers (Float16Array is not in every browser yet)
const f32 = new Float32Array(1), u32 = new Uint32Array(f32.buffer);
function toHalf(v) {
f32[0] = v; const x = u32[0], s = (x >>> 16) & 0x8000; let e = ((x >>> 23) & 0xff) - 112, m = x & 0x7fffff;
if (e <= 0) { if (e < -10) return s; m = (m | 0x800000) >> (1 - e); return s | ((m + 0x1000) >> 13); }
if (e >= 31) return s | 0x7c00;
return s | (e << 10) | ((m + 0x1000) >> 13);
}
const HALF = new Float32Array(65536);
for (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 loading
let 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 time
const r = await fetch(url); if (!r.ok) throw new Error(`${label}: HTTP ${r.status}`);
const total = +r.headers.get('content-length') || 0, reader = r.body.getReader(), parts = []; let got = 0;
for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); got += value.length; status(`Downloading ${label}: ${mb(got)}${total ? ' of ' + mb(total) : ''}`, base + span * (total ? got / total : 0)); }
const out = new Uint8Array(got); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; } return out;
}
async function adapterInfo() {
if (!navigator.gpu) throw new Error('This browser has no WebGPU. Use a current Chrome or Edge on a desktop with a dedicated GPU.');
const a = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
if (!a) throw new Error('WebGPU is present but no GPU adapter was found.');
const i = a.info || {};
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 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;
ui.gpu.textContent = `${info.name} · shader-f16: ${info.f16 ? 'yes' : 'no'} · using ${dt} models${info.soft ? ' · SOFTWARE adapter, timings are meaningless' : ''}`;
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);
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); }
}
}
// ------------------------------------------------------------ portrait -> identity features (once per portrait)
function tensorFrom(arr32, dims) { return F16 ? new ort.Tensor('float16', Uint16Array.from(arr32, toHalf), dims) : new ort.Tensor('float32', arr32, dims); }
async function loadPortrait(src) {
const img = await new Promise((res, rej) => { const i = new Image(); i.crossOrigin = 'anonymous'; i.onload = () => res(i); i.onerror = () => rej(new Error('could not read that image')); i.src = src; });
const c = document.createElement('canvas'); c.width = c.height = SIZE; const g = c.getContext('2d');
const s = Math.min(img.width, img.height); g.drawImage(img, (img.width - s) / 2, (img.height - s) / 2, s, s, 0, 0, SIZE, SIZE); // centre-crop to a square
const px = g.getImageData(0, 0, SIZE, SIZE).data, n = SIZE * SIZE, x = new Float32Array(3 * n);
for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) x[k * n + i] = px[i * 4 + k] / 127.5 - 1;
const t = performance.now();
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;
}
// ------------------------------------------------------------ rendering
const imgData = ctx2d.createImageData(SIZE, SIZE);
function paint(u) { // decoder output [1,3,512,512] in [-1,1] -> canvas
const n = SIZE * SIZE, d = imgData.data, bits = u instanceof Uint16Array; // raw fp16 bits need the lookup table; Float16Array / Float32Array already hold numbers
if (!(u[n >> 1] === u[n >> 1]) && !bits) throw new Error('The GPU returned invalid numbers (NaN). Reload the page with ?fp=32 to use the fp32 models.');
for (let i = 0; i < n; i++) {
const r = bits ? HALF[u[i]] : u[i], gg = bits ? HALF[u[n + i]] : u[n + i], b = bits ? HALF[u[2 * n + i]] : u[2 * n + i];
const o = i * 4; d[o] = (r * 0.5 + 0.5) * 255; d[o + 1] = (gg * 0.5 + 0.5) * 255; d[o + 2] = (b * 0.5 + 0.5) * 255; d[o + 3] = 255;
}
ctx2d.putImageData(imgData, 0, 0);
}
const PH = Array.from({ length: 20 }, (_, i) => 0.37 * i + 1), FR = Array.from({ length: 20 }, (_, i) => 0.55 + 0.23 * ((i * 7) % 11) / 11);
function style(t, amp, spd) { // wa = identity style + sum_i lambda_i * basis_i (a smooth synthetic motion)
const lam = new Float32Array(20); for (let i = 0; i < 20; i++) lam[i] = amp * Math.sin(spd * FR[i] * t * 2 * Math.PI * 0.35 + PH[i]);
const wa = new Float32Array(512);
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 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;
while (running && my === token) {
let r; try { r = await frame((performance.now() - t0) / 1000); } catch (e) { console.error(e); running = false; ui.pause.textContent = 'Resume'; status(e.message || String(e), null, true); return; } const now = performance.now(), dt = now - last; last = now; n++;
const k = n < 3 ? 1 : 0.1; ema.gpu += k * (r.gpu - ema.gpu); ema.draw += k * (r.draw - ema.draw); ema.tot += k * (dt - ema.tot);
if (n === 1 || n % 3 === 0) show();
await yieldNow();
}
}
function show() {
const fps = 1000 / ema.tot;
ui.fps.textContent = `${fps.toFixed(1)} fps`; ui.ms.textContent = `${ema.tot.toFixed(0)} ms/frame (render + read back ${ema.gpu.toFixed(0)} ms, paint ${ema.draw.toFixed(0)} ms)`;
ui.verdict.textContent = fps >= 25 ? `Fast enough for live use: ${(fps / 25).toFixed(1)}× the 25 fps needed.` : `${(fps / 25).toFixed(2)}× of the 25 fps needed for live use.`;
ui.verdict.className = fps >= 25 ? 'ok' : 'slow';
}
async function benchmark() {
if (!sess || !feats) return;
try { await benchmark2(); } catch (e) { console.error(e); status(`Benchmark failed: ${e.message || e}`, null, true); }
}
async function benchmark2() {
const was = running; running = false; token++; await sleep(50);
const W = q.has('bw') ? +q.get('bw') : 5, N = +q.get('bn') || 40; // frame counts are overridable for testing on slow software GPUs
status(`Benchmark: ${W} warm-up frames, then ${N} timed frames…`, 0.5); const gpu = [], tot = [];
for (let i = 0; i < W; i++) await frame(i / 25);
for (let i = 0; i < N; i++) { const a = performance.now(); const r = await frame(i / 25); tot.push(performance.now() - a); gpu.push(r.gpu); }
const 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); }
}
// ------------------------------------------------------------ speech-to-motion step: timing only (random inputs)
// One block of 10 frames needs ~9 passes of this 8-layer transformer (2 guidance branches, 12 tokens, KV cache) plus 10 renderer frames.
async function flowBenchmark() {
if (!sess) return;
const was = running; running = false; token++; ui.bflow.disabled = true;
try {
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) };
}
const shapes = { x: [2, 12, 512], c: [2, 12, 1024], wr: [2, 12, 512], freqs: [12, 128], ada: [2, 12, 6144], fada: [2, 12, 2048] };
for (let i = 0; i < 8; i++) { shapes['sk' + i] = [2, 8, 38, 128]; shapes['sv' + i] = [2, 8, 38, 128]; shapes['ck' + i] = [2, 8, 2, 128]; shapes['cv' + i] = [2, 8, 2, 128]; }
const gauss = () => Math.sqrt(-2 * Math.log(Math.random() + 1e-12)) * Math.cos(2 * Math.PI * Math.random());
const feed = {}; for (const [k, sh] of Object.entries(shapes)) { const n = sh.reduce((a, b) => a * b, 1), a = new Float32Array(n), sc = k === 'ada' || k === 'fada' ? 0.1 : 1; for (let i = 0; i < n; i++) a[i] = gauss() * sc; feed[k] = half ? new ort.Tensor('float16', Uint16Array.from(a, toHalf), sh) : new ort.Tensor('float32', a, sh); }
const W = q.has('fw') ? +q.get('fw') : 3, N = +q.get('fn') || 15, times = [];
status(`Timing the speech-to-motion step: ${W} warm-up, ${N} timed passes…`, 0.9);
for (let i = 0; i < W + N; i++) { const t = performance.now(); const o = await exclusive(async () => { const r = await flowSess.s.run(feed); await r.y.getData(); return r; }); if (i >= W) times.push(performance.now() - t); }
const med = times.slice().sort((a, b) => a - b)[times.length >> 1], fm = frameMedian || 0;
let 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); }
}
// ------------------------------------------------------------ UI
async 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); 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); }
}
for (const [id, name] of AVATARS) {
const b = document.createElement('button'); b.type = 'button'; b.className = 'av'; b.title = name; b.setAttribute('aria-label', name);
const im = document.createElement('img'); im.src = `avatars/${id}.jpg`; im.alt = name; im.width = im.height = 64; b.append(im);
b.addEventListener('click', () => { [...ui.avatars.children].forEach((c) => c.classList.toggle('on', c === b)); useAvatar(`avatars/${id}.jpg`); }); ui.avatars.append(b);
}
ui.file.addEventListener('change', () => { const f = ui.file.files[0]; if (f) { [...ui.avatars.children].forEach((c) => c.classList.remove('on')); useAvatar(URL.createObjectURL(f)); } });
ui.start.addEventListener('click', () => { if (!feats) return; status('Rendering live. Motion is synthetic (not speech).', 1); running = true; token++; ui.start.disabled = true; ui.pause.disabled = false; loop(token); });
ui.pause.addEventListener('click', () => { running = !running; ui.pause.textContent = running ? 'Pause' : 'Resume'; if (running) { token++; loop(token); } });
ui.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 tab
window.__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 hook
adapterInfo().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);
}).catch((e) => { status(e.message, null, true); document.querySelectorAll('.av, #file').forEach((el) => { el.disabled = true; }); });
|