Spaces:
Running
Running
Ship one app.js: a private static Space returns 401 for module imports
Browse filesFiles changed (6)
- app.jsAdded
- dflow.jsDeleted-329
- index.html+1-1
- main.jsDeleted-190
- preview.jsonDeleted
- prompt.jsDeleted-19
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329// dflow_2b + 4-step eDMD/LADD LoRA, in the browser with ONNX Runtime Web.// Text graph on WASM (Gemma activations stay fp32), denoiser and decoder on WebGPU.// Port of dflow/{rope3d,schedules,solvers}.py and dinac3 RoPE; every table mirrors// work/ropes.py, which the ONNX export was verified against.import { tokenizePrompt } from './prompt.js';
const fr = Math.fround;export const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];export const CACHE = 'dflow2-web-v1';// Beta(1.25, 1.25) quantiles of linspace(0, 1, steps + 1), float32 (scipy.stats.beta.ppf).const BETA_GRID = { 1: [0, 1], 2: [0, 0.5, 1], 3: [0, 0.35325562953948975, 0.6467443108558655, 1], 4: [0, 0.2776529788970947, 0.5, 0.7223470211029053, 1], 5: [0, 0.23080690205097198, 0.4123722314834595, 0.5876277685165405, 0.7691931128501892, 1], 6: [0, 0.19865159690380096, 0.35325562953948975, 0.5, 0.6467443108558655, 0.8013483881950378, 1], 8: [0, 0.15698565542697906, 0.2776529788970947, 0.39030271768569946, 0.5, 0.6096972823143005, 0.7223470211029053, 0.8430143594741821, 1],};
// ---------- schedule ----------export function timesteps(width, height, steps = 4) { const base = BETA_GRID[steps]; if (!base) throw new Error(`steps must be one of ${Object.keys(BETA_GRID)}`); const shift = Math.min(0, -0.25 - Math.log((width * height) / 65536)); const eps = 1.1920928955078125e-07, tiny = 1.1754943508222875e-38; const out = base.map((t) => { if (t === 0 || t === 1 || Math.abs(shift) <= 1e-9) return t; const c = Math.min(Math.max(t, tiny), 1 - eps); const lg = Math.log(c / (1 - c)) - 0.5 * shift; return fr(1 / (1 + Math.exp(-lg))); }); return out.reverse();}
export function selfAttentionGain(width, height) { const area = width * height; if (area <= 1.05e6) return -0.03; const frac = Math.log(area / 1.05e6) / Math.log(2.5e6 / 1.05e6); return -0.03 * Math.max(0, 1 - frac);}
// ---------- RoPE tables ----------const AXES = [[32, 0], [48, 32], [48, 80]]; // [dim, channel offset] per axis, head width 128
function dflowRows(positions, n) { // positions: Float64Array [n*3] const sin = new Float32Array(n * 128), cos = new Float32Array(n * 128); for (const [axis, [dim, off]] of AXES.entries()) { for (let k = 0; k < dim / 2; k++) { const f = 1 / Math.pow(10000, (2 * k) / dim); for (let i = 0; i < n; i++) { const a = fr(positions[i * 3 + axis] * f); const s = fr(Math.sin(a)), c = fr(Math.cos(a)), o = i * 128 + off + 2 * k; sin[o] = s; sin[o + 1] = s; cos[o] = c; cos[o + 1] = c; } } } return { sin, cos };}
function textPositions(L) { const p = new Float64Array(L * 3); for (let i = 0; i < L; i++) p[i * 3] = i + 1; return p;}
function jointPositions(L, gh, gw) { const n = gh * gw, p = new Float64Array((n + L) * 3); for (let i = 0; i < n; i++) { const r = Math.floor(i / gw), c = i % gw; p[i * 3] = L + 1; p[i * 3 + 1] = r - (gh - 1) / 2; p[i * 3 + 2] = c - (gw - 1) / 2; } p.set(textPositions(L), n * 3); return p;}
function gemmaTables(L) { const out = {}; for (const [name, theta, factor] of [['s', 10000, 1], ['f', 1000000, 8]]) { const inv = new Float32Array(128); for (let k = 0; k < 128; k++) inv[k] = fr(fr(1 / fr(Math.pow(theta, fr((2 * k) / 256)))) / factor); const c = new Float32Array(L * 256), s = new Float32Array(L * 256); for (let i = 0; i < L; i++) for (let k = 0; k < 128; k++) { const a = fr(i * inv[k]), cv = fr(Math.cos(a)), sv = fr(Math.sin(a)); c[i * 256 + k] = cv; c[i * 256 + 128 + k] = cv; s[i * 256 + k] = sv; s[i * 256 + 128 + k] = sv; } out[`g_cos_${name}`] = c; out[`g_sin_${name}`] = s; } return out;}
function vaeTables(gh, gw) { const per = new Float32Array(16); for (let i = 0; i < 16; i++) per[i] = fr(Math.pow(10000, fr((2 * i) / 32))); const n = gh * gw, sin = new Float32Array(n * 64), cos = new Float32Array(n * 64); for (let t = 0; t < n; t++) { const coord = [Math.floor(t / gw), t % gw]; for (let ax = 0; ax < 2; ax++) for (let i = 0; i < 16; i++) { const a = fr(coord[ax] / per[i]), s = fr(Math.sin(a)), c = fr(Math.cos(a)); const o = t * 64 + ax * 32 + 2 * i; sin[o] = s; sin[o + 1] = s; cos[o] = c; cos[o + 1] = c; } } return { sin, cos };}
// ---------- noise ----------export function gaussianNoise(count, seed) { let s = (seed >>> 0) || 1; const next = () => { // mulberry32 s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const out = new Float32Array(count); for (let i = 0; i < count; i += 2) { const u = Math.max(next(), 1e-12), v = next(), r = Math.sqrt(-2 * Math.log(u)); out[i] = r * Math.cos(2 * Math.PI * v); if (i + 1 < count) out[i + 1] = r * Math.sin(2 * Math.PI * v); } return out;}
// ---------- downloads ----------async function openCache() { try { return await caches.open(CACHE); } catch { return null; }}
export async function fetchBytes(url, onBytes) { const cache = await openCache(); let resp = cache && await cache.match(url); const cached = Boolean(resp); if (!resp) { resp = await fetch(url); if (!resp.ok) throw new Error(`${resp.status} ${url}`); const total = Number(resp.headers.get('content-length')) || 0; const reader = resp.body.getReader(); // Fill one buffer as the stream arrives: no Blob (large Blobs spill to disk and can // become unreadable when storage is short) and no second copy. let bytes = new Uint8Array(total || 1 << 20), got = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; if (got + value.length > bytes.length) { const grown = new Uint8Array(Math.max(bytes.length * 2, got + value.length)); grown.set(bytes.subarray(0, got)); bytes = grown; } bytes.set(value, got); got += value.length; onBytes?.(got, total); } if (got !== bytes.length) bytes = bytes.slice(0, got); if (cache) { try { await cache.put(url, new Response(bytes)); } catch (e) { console.warn(`not cached (${e.name}): ${url}`); } } return { bytes, cached }; } const bytes = new Uint8Array(await resp.arrayBuffer()); onBytes?.(bytes.length, bytes.length); return { bytes, cached };}
export async function isCached(url) { const cache = await openCache(); return Boolean(cache && await cache.match(url));}
// Token embedding rows, bf16 [262144 x 640] in one file, read with HTTP Range requests:// a prompt needs a few KB instead of the whole 335 MB table.const ROW = 640, ROW_BYTES = ROW * 2, EMB_SCALE = fr(Math.sqrt(640));async function embedRow(url, id, mem) { if (mem.has(id)) return mem.get(id); const key = `${url}?row=${id}`; const cache = await openCache(); let buf = cache && await cache.match(key).then((r) => r && r.arrayBuffer()); if (!buf) { const r = await fetch(url, { headers: { Range: `bytes=${id * ROW_BYTES}-${id * ROW_BYTES + ROW_BYTES - 1}` } }); if (r.status !== 206 && r.status !== 200) throw new Error(`embedding row ${id}: HTTP ${r.status}`); buf = await r.arrayBuffer(); if (r.status === 200) buf = buf.slice(id * ROW_BYTES, (id + 1) * ROW_BYTES); // server ignored Range if (buf.byteLength !== ROW_BYTES) throw new Error(`embedding row ${id}: ${buf.byteLength} bytes`); if (cache) cache.put(key, new Response(buf.slice(0))).catch(() => {}); } const u16 = new Uint16Array(buf), u32 = new Uint32Array(ROW); for (let k = 0; k < ROW; k++) u32[k] = u16[k] << 16; // bf16 -> f32, exact const f = new Float32Array(u32.buffer); for (let k = 0; k < ROW; k++) f[k] = fr(f[k] * EMB_SCALE); mem.set(id, f); return f;}
// ---------- live preview ----------// dflow's fitted latent -> RGB readout (dflow/preview.py): replicate-padded 3x3 conv// 96 -> 12, pixel-shuffled x2, so a 1/8-resolution image of the clean estimate.export function previewImage(x0, gh, gw, P) { const W = P.w, B = P.b, img = new ImageData(gw * 2, gh * 2), n = gh * gw; const cells = new Float32Array(12); for (let i = 0; i < gh; i++) for (let j = 0; j < gw; j++) { cells.set(B); for (let c = 0; c < 96; c++) for (let di = -1; di <= 1; di++) { const ii = Math.min(gh - 1, Math.max(0, i + di)); for (let dj = -1; dj <= 1; dj++) { const jj = Math.min(gw - 1, Math.max(0, j + dj)), v = x0[c * n + ii * gw + jj]; const k = (di + 1) * 3 + (dj + 1); for (let o = 0; o < 12; o++) cells[o] += W[(o * 96 + c) * 9 + k] * v; } } for (let o = 0; o < 12; o++) { const ch = Math.floor(o / 4), sub = o % 4, y = i * 2 + (sub >> 1), xx = j * 2 + (sub & 1); img.data[(y * gw * 2 + xx) * 4 + ch] = Math.round((Math.max(-1, Math.min(1, cells[o])) + 1) * 127.5); } for (let sub = 0; sub < 4; sub++) img.data[((i * 2 + (sub >> 1)) * gw * 2 + j * 2 + (sub & 1)) * 4 + 3] = 255; } return img;}
// ---------- engine ----------export class DFlowWeb { constructor({ ort, base, files, log = () => {}, progress = () => {} }) { this.ort = ort; this.base = base.replace(/\/$/, ''); this.files = files; this.log = log; this.progress = progress; this.sessions = {}; this.rows = new Map(); this.textCache = new Map(); }
url(name) { return `${this.base}/${name}`; }
async _session(part, ep, extra = {}) { const onnx = await fetchBytes(this.url(`${part}/${part}.onnx`)); const data = await fetchBytes(this.url(`${part}/${part}.onnx.data`), (got, total) => this.progress(part, got, total || this.files?.[part] || 0)); this.log(`${part}: ${(data.bytes.length / 1e6).toFixed(0)} MB ${data.cached ? '(cached)' : '(downloaded)'}, starting ${ep}`); const t0 = performance.now(); const s = await this.ort.InferenceSession.create(onnx.bytes, { executionProviders: [ep], graphOptimizationLevel: 'all', logSeverityLevel: 3, externalData: [{ path: `${part}.onnx.data`, data: data.bytes }], ...extra, }); this.log(`${part}: ready in ${((performance.now() - t0) / 1000).toFixed(1)} s`); return s; }
async load({ tokenizer }) { this.tokenizer = tokenizer; this.preview = await (await fetch(new URL('./preview.json', import.meta.url))).json(); this.sessions.text = await this._session('text', 'wasm'); for (const p of DIT_PARTS) { const loc = p === 'dit_d' ? 'cpu' : 'gpu-buffer'; this.sessions[p] = await this._session(p, 'webgpu', { preferredOutputLocation: loc }); } this.sessions.vae_dec = await this._session('vae_dec', 'webgpu'); }
async encode(prompt) { if (this.textCache.has(prompt)) return this.textCache.get(prompt); const ids = tokenizePrompt(this.tokenizer, prompt); if (ids.length > 256) throw new Error(`prompt is ${ids.length} tokens; this demo takes up to 256`); const rows = await Promise.all(ids.map((id) => embedRow(this.url('embed_bf16.bin'), id, this.rows))); const L = ids.length, emb = new Float32Array(L * ROW); rows.forEach((r, i) => emb.set(r, i * ROW)); const T = this.ort.Tensor, g = gemmaTables(L), r = dflowRows(textPositions(L + 3), L + 3); const out = await this.sessions.text.run({ emb: new T('float32', emb, [1, L, ROW]), g_cos_s: new T('float32', g.g_cos_s, [L, 1, 256]), g_sin_s: new T('float32', g.g_sin_s, [L, 1, 256]), g_cos_f: new T('float32', g.g_cos_f, [L, 1, 256]), g_sin_f: new T('float32', g.g_sin_f, [L, 1, 256]), r_sin: new T('float32', r.sin, [1, L + 3, 128]), r_cos: new T('float32', r.cos, [1, L + 3, 128]), }); const res = { ids, text: out.text.data, lt: L + 3 }; this.textCache.clear(); this.textCache.set(prompt, res); return res; }
async velocity(x, t, ctx) { const T = this.ort.Tensor, { n, feeds } = ctx; const lat = new Float32Array(n * 96); // [96, n] -> [n, 96] for (let c = 0; c < 96; c++) for (let i = 0; i < n; i++) lat[i * 96 + c] = x[c * n + i]; const a = await this.sessions.dit_a.run({ lat: new T('float32', lat, [1, n, 96]), t: new T('float32', new Float32Array([t]), [1]), text: ctx.text, ...feeds }); const b = await this.sessions.dit_b.run({ x: a.x, tact: a.tact, ...feeds }); const c = await this.sessions.dit_c.run({ x: b.y, tact: a.tact, ...feeds }); b.y.dispose(); const d = await this.sessions.dit_d.run({ prefix: a.x, middle: c.y, tact: a.tact, ...feeds }); a.x.dispose(); a.tact.dispose(); c.y.dispose(); const vel = d.vel.data, v = new Float32Array(96 * n); // [n(+text), 96] -> [96, n] for (let i = 0; i < n; i++) for (let ch = 0; ch < 96; ch++) v[ch * n + i] = vel[i * 96 + ch]; return v; }
async generate({ prompt, width, height, seed, steps = 4, noise, onStep = () => {} }) { const T = this.ort.Tensor, gh = height / 16, gw = width / 16, n = gh * gw; const t0 = performance.now(); const enc = await this.encode(prompt); const tText = performance.now(); const rope = dflowRows(jointPositions(enc.lt, gh, gw), n + enc.lt); const S = n + enc.lt; const gain = selfAttentionGain(width, height); const ctx = { n, text: new T('float32', enc.text, [1, enc.lt, 2304]), feeds: { rope_sin: new T('float32', rope.sin, [1, S, 128]), rope_cos: new T('float32', rope.cos, [1, S, 128]), qscale: new T('float32', new Float32Array([fr(Math.exp(gain))]), []) }, }; const ts = timesteps(width, height, steps); let x = noise ? Float32Array.from(noise) : gaussianNoise(96 * n, seed); const vels = []; for (let i = 0; i < steps; i++) { const s0 = performance.now(); const v = await this.velocity(x, ts[i], ctx); vels.push(v); const dt = fr(ts[i + 1] - ts[i]), x0 = new Float32Array(x.length); for (let k = 0; k < x.length; k++) { x0[k] = x[k] - ts[i] * v[k]; x[k] = fr(x[k] + dt * v[k]); } onStep(i + 1, steps, (performance.now() - s0) / 1000, x0); } const tDen = performance.now(); const vt = vaeTables(gh, gw); const out = await this.sessions.vae_dec.run({ z: new T('float32', x, [1, 96, gh, gw]), v_sin: new T('float32', vt.sin, [n, 64]), v_cos: new T('float32', vt.cos, [n, 64]) }); const rgb = out.rgb.data; const img = new ImageData(width, height), hw = width * height; for (let i = 0; i < hw; i++) { img.data[i * 4] = Math.round(rgb[i] * 255); img.data[i * 4 + 1] = Math.round(rgb[hw + i] * 255); img.data[i * 4 + 2] = Math.round(rgb[2 * hw + i] * 255); img.data[i * 4 + 3] = 255; } const tEnd = performance.now(); return { image: img, ids: enc.ids, text: enc.text, latent: x, vels, rgb, times: ts, timing: { text: (tText - t0) / 1000, denoise: (tDen - tText) / 1000, decode: (tEnd - tDen) / 1000 } }; }}53 unmodified lines54555657585953 unmodified linesThis project uses dflow_2b by Data Archetype. Non-commercial use only (MG-BY-NC-2.0); Gemma is provided under and subject to the Gemma Terms of Use found at gemma.ai/resources/terms.</p></details></main><script type="module" src="main.js"></script></body></html>53 unmodified lines54555657585953 unmodified linesThis project uses dflow_2b by Data Archetype. Non-commercial use only (MG-BY-NC-2.0); Gemma is provided under and subject to the Gemma Terms of Use found at gemma.ai/resources/terms.</p></details></main><script type="module" src="app.js"></script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190import { CACHE, DFlowWeb, DIT_PARTS, fetchBytes, isCached, previewImage } from './dflow.js';
const q = new URLSearchParams(location.search);const REPO = 'WeReCooking2/DFlow2-4step-ONNX-WebGPU';// Test hooks: only same-origin paths (or the Hub, for weights) are accepted, so a crafted// link cannot make this page import someone else's script.const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null);const hub = (v) => (v && /^https:\/\/huggingface\.co\/[\w.-]+\/[\w.-]+\/resolve\/[\w.-]+$/.test(v) ? v : null);const BASE = local(q.get('base')) || hub(q.get('base')) || `https://huggingface.co/${REPO}/resolve/main`;const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';const TOK_URL = local(q.get('tok')) || 'https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/dist/tokenizers.min.mjs';const PARTS = ['text', ...DIT_PARTS, 'vae_dec'];const SIZES = [[512, 512], [384, 640], [640, 384], [512, 768], [768, 512], [640, 640], [768, 768], [832, 1216], [1216, 832], [1024, 1024]];
if (/^\d{2,4}x\d{2,4}$/.test(q.get('size') || '')) { // test hook, multiples of 16 only const sz = q.get('size').split('x').map(Number); if (sz.every((v) => v % 16 === 0)) SIZES.unshift(sz);}const $ = (id) => document.getElementById(id);const ui = { go: $('go'), msg: $('msg'), bar: $('bar').firstElementChild, size: $('size'), seed: $('seed'), random: $('random'), canvas: $('canvas'), save: $('save'), prompt: $('prompt'), backend: $('backend'), speed: $('speed'), store: $('store'), wipe: $('wipe'), limits: $('limits'), more: $('more') };const ctx2d = ui.canvas.getContext('2d');ui.repo = $('repo'); ui.repo.href = `https://huggingface.co/${REPO}`; ui.repo.textContent = REPO;
let ort, engine, manifest, maxTokens = Infinity, perToken = null, busy = false, saveUrl = null;const gb = (b) => (b / 1e9).toFixed(2) + ' GB', mb = (b) => (b / 1e6).toFixed(0) + ' MB';
function status(text, frac = null, bad = false) { ui.msg.textContent = text; ui.msg.classList.toggle('bad', bad); if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;}
const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical promptfunction estimate([w, h]) { // seconds for a whole image, from the last run if (!perToken) return ''; const s = tokensOf([w, h]); const sec = 4 * perToken.step * Math.pow(s / perToken.tokens, 1.15) + perToken.decode * (w * h) / perToken.pixels; return ` · ~${sec < 90 ? Math.round(sec) + ' s' : (sec / 60).toFixed(1) + ' min'}`;}
function fillSizes() { const keep = ui.size.value; ui.size.innerHTML = ''; for (const sz of SIZES) { if (tokensOf(sz) > maxTokens) continue; const o = document.createElement('option'); o.value = sz.join('x'); const tag = sz[0] === sz[1] ? '' : sz[0] < sz[1] ? ' portrait' : ' landscape'; const trained = (sz[0] === 832 && sz[1] === 1216) || (sz[0] === 1216 && sz[1] === 832) ? ', trained size' : ''; o.textContent = `${sz[0]}×${sz[1]}${tag}${trained}${estimate(sz)}`; ui.size.append(o); } ui.size.value = keep && [...ui.size.options].some((o) => o.value === keep) ? keep : (q.get('size') || '512x512');}
async function storageLine() { try { const est = await navigator.storage?.estimate?.(); const cached = manifest ? (await Promise.all(PARTS.map((p) => isCached(`${BASE}/${p}/${p}.onnx.data`)))).filter(Boolean).length : 0; ui.store.textContent = `${cached} of ${PARTS.length} model files stored in this browser` + (est ? ` (site storage in use ${gb(est.usage || 0)}, quota ${gb(est.quota || 0)}).` : '.'); return cached === PARTS.length; } catch { return false; }}
async function buttonLabel() { if (engine?.ready) { ui.go.textContent = 'Generate'; return; } const all = await storageLine(); ui.go.textContent = all ? 'Load model and generate' : `Download model (${manifest ? gb(manifest.total) : '1.6 GB'}) and generate`;}
async function init() { ui.random.addEventListener('change', () => { ui.seed.disabled = ui.random.checked; }); ui.seed.disabled = ui.random.checked; ui.save.addEventListener('click', (e) => { if (ui.save.classList.contains('disabled')) e.preventDefault(); }); ui.wipe.addEventListener('click', async () => { if (busy) return; await caches.delete(CACHE); status('Deleted the stored model. Reloading…'); location.reload(); }); fillSizes(); if (!navigator.gpu) return fail('This browser has no WebGPU. Use Chrome or Edge 121+ (Android 12+), or Safari 26.'); const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); if (!adapter) return fail('WebGPU is present but no GPU adapter was found (blocklisted driver or disabled flag).'); const lim = Math.min(adapter.limits.maxStorageBufferBindingSize, adapter.limits.maxBufferSize); maxTokens = Math.floor(Math.sqrt(lim / (18 * 4))); // one fp32 attention map [18, S, S] must fit a buffer const info = adapter.info || {}; const gpu = [info.vendor, info.architecture].filter(Boolean).join(' ') || 'GPU'; ui.backend.textContent = `WebGPU on ${gpu} · 4-bit weights`; ui.limits.textContent = `This GPU allows buffers up to ${mb(lim)}, so images up to about ${maxTokens - 48} latent tokens ` + `(${Math.round(Math.sqrt((maxTokens - 48) * 256))}² pixels). Larger sizes are hidden.`; fillSizes(); try { manifest = JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/manifest.json`)).bytes)); } catch (e) { return fail(`Could not reach the model repo (${e.message}).`); } ui.go.disabled = false; ui.go.addEventListener('click', run); await buttonLabel(); status('Ready.', 0);}
function fail(text) { ui.backend.textContent = 'no WebGPU'; ui.go.disabled = true; ui.go.textContent = 'Needs WebGPU'; status(text, 0, true);}
async function load() { status('Loading the runtime…', 0); ort = await import(ORT_URL); ort.env.logLevel = 'error'; ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1; ort.env.webgpu.powerPreference = 'high-performance'; const { Tokenizer } = await import(TOK_URL); navigator.storage?.persist?.().catch(() => {}); const total = manifest.total; let done = 0; status('Tokenizer…', 0); const [tj, tc] = await Promise.all(['tokenizer.json', 'tokenizer_config.json'].map(async (f) => JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/${f}`)).bytes)))); engine = new DFlowWeb({ ort, base: BASE, files: manifest.parts, log: (m) => status(m, done / total), progress: (part, got, size) => status(`Downloading ${part}: ${mb(got)} of ${mb(size)} · ${gb(done + got)} of ${gb(total)}`, (done + got) / total), }); const orig = engine._session.bind(engine); engine._session = async (part, ep, extra) => { const s = await orig(part, ep, extra); done += manifest.parts[part] || 0; return s; }; await engine.load({ tokenizer: new Tokenizer(tj, tc) }); engine.ready = true; Promise.resolve(ort.env.webgpu.device).then((d) => d?.lost?.then((i) => { if (i.reason !== 'destroyed') status(`The GPU was lost (${i.message || 'out of memory?'}). Reload the page and pick a smaller size.`, 0, true); })).catch(() => {}); await storageLine();}
async function run() { if (busy) return; const prompt = ui.prompt.value.trim(); if (!prompt) { status('Write a prompt first.', null, true); return; } busy = true; ui.go.disabled = true; try { if (!engine?.ready) await load(); const [w, h] = ui.size.value.split('x').map(Number); const seed = ui.random.checked ? (crypto.getRandomValues(new Uint32Array(1))[0] >>> 1) : (Number(ui.seed.value) >>> 0); ui.seed.value = seed; ui.canvas.width = w; ui.canvas.height = h; ctx2d.clearRect(0, 0, w, h); ui.save.classList.add('disabled'); status('Reading the prompt…', 0); const t0 = performance.now(); const pre = document.createElement('canvas'); const res = await engine.generate({ prompt, width: w, height: h, seed, onStep: (i, n, sec, x0) => { const img = previewImage(x0, h / 16, w / 16, engine.preview); pre.width = img.width; pre.height = img.height; pre.getContext('2d').putImageData(img, 0, 0); ctx2d.imageSmoothingEnabled = true; ctx2d.drawImage(pre, 0, 0, w, h); status(i < n ? `Step ${i} of ${n} · ${sec.toFixed(1)} s per step` : 'Decoding the image…', i / (n + 0.5)); } }); ctx2d.putImageData(res.image, 0, 0); const total = (performance.now() - t0) / 1000; perToken = { step: res.timing.denoise / 4, tokens: (w * h) / 256 + res.ids.length + 3, decode: res.timing.decode, pixels: w * h }; ui.speed.textContent = `~${Math.round(total)} s per ${w}×${h} image here`; fillSizes(); ui.canvas.toBlob((blob) => { if (saveUrl) URL.revokeObjectURL(saveUrl); saveUrl = URL.createObjectURL(blob); ui.save.href = saveUrl; ui.save.download = `dflow2_${w}x${h}_seed${seed}.png`; ui.save.classList.remove('disabled'); }, 'image/png'); status(`Done in ${total.toFixed(1)} s (prompt ${res.timing.text.toFixed(1)} s, 4 steps ` + `${res.timing.denoise.toFixed(1)} s, decode ${res.timing.decode.toFixed(1)} s). Seed ${seed}.`, 1); } catch (e) { console.error(e); status(`Failed: ${e?.message || e}`, null, true); } finally { busy = false; ui.go.disabled = false; await buttonLabel(); }}
init().catch((e) => status(`Failed to start: ${e.message}`, 0, true));12345678910111213141516171819// dflow_2b prompt tokenization (port of dflow/tokenization.py, plain prompts).// <bos> frame, then the prompt; text inside straight or curly double quotes on// one line is tokenized one character at a time, quote marks included.const QUOTED = /"[^"\n]*"|“[^”\n]*”/gu;
export function tokenizePrompt(tokenizer, text, frame = { prefix: [2], suffix: [] }) { const pieces = []; let cursor = 0; for (const m of text.matchAll(QUOTED)) { if (m.index > cursor) pieces.push(text.slice(cursor, m.index)); for (const ch of m[0]) pieces.push(ch); // per code point, as Python iterates cursor = m.index + m[0].length; } if (cursor < text.length) pieces.push(text.slice(cursor)); const ids = [...frame.prefix]; for (const piece of pieces) ids.push(...tokenizer.encode(piece, { add_special_tokens: false }).ids); ids.push(...frame.suffix); return ids;}app.jsAdded
dflow.jsDeleted-329
index.html+1-1
main.jsDeleted-190
preview.jsonDeleted
prompt.jsDeleted-19