Spaces:
Running
Running
8-bit weights by default, trained ~1 MP size by default, tiled decoder, header links
Browse filesFiles changed (4)
- README.md+4-2
- app.js+125-48
- index.html+9-7
- style.css+4-1
19 unmodified lines202122232425262719 unmodified linesin your browser tab on your own GPU through WebGPU and ONNX Runtime Web. Nothing is sent to a server.- Needs WebGPU: Chrome or Edge 121+ (Android 12+ on phones), or Safari 26.- Downloads about 1.7 GB once, then works from the browser's storage.- Needs about 2 GB of free GPU memory. On a phone, close other tabs and start at 512×512.Weights and conversion details: [WeReCooking2/DFlow2-4step-ONNX-WebGPU](https://huggingface.co/WeReCooking2/DFlow2-4step-ONNX-WebGPU).19 unmodified lines2021222324252627282919 unmodified linesin your browser tab on your own GPU through WebGPU and ONNX Runtime Web. Nothing is sent to a server.- Needs WebGPU: Chrome or Edge 121+ (Android 12+ on phones), or Safari 26.- Downloads once, then works from the browser's storage: about 2.7 GB with the default 8-bit weights(same output as the original model), 1.7 GB with the optional 4-bit ones (softer, for low-memory devices).- Picks the trained size (about 1 MP) when your GPU allows it. 512×512 is a quick preview with farless detail, since the model was trained at 1 MP and above.Weights and conversion details: [WeReCooking2/DFlow2-4step-ONNX-WebGPU](https://huggingface.co/WeReCooking2/DFlow2-4step-ONNX-WebGPU).
26 unmodified lines27282930313233205 unmodified lines23924024124224324424524624724824925025125225325425525610 unmodified lines26726826927027127227327427515 unmodified lines29129229329429529610 unmodified lines30730830931031131231318 unmodified lines33233333433533633733833934034134234334434534634734810 unmodified lines3593603613623633643653663673683693703713723733743753763773783793802 unmodified lines3833843853863873884 unmodified lines3933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294305 unmodified lines43643743843944044144244344444544644744844945045114 unmodified lines46646746846947047147247347447547647747847948048148248348448548626 unmodified lines51351451551651751851926 unmodified linesconst fr = Math.fround;const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];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],205 unmodified lines// ---------- engine ----------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, {10 unmodified linesthis.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) {15 unmodified linesreturn res;}async velocity(x, t, ctx) {const T = this.ort.Tensor, { n, feeds } = ctx;const lat = new Float32Array(n * 96); // [96, n] -> [n, 96]10 unmodified linesreturn 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);18 unmodified linesonStep(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 } };10 unmodified linesconst 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 onlyconst 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) {2 unmodified lines}const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical promptfunction estimate([w, h]) { // seconds for a whole image, from the last runif (!perToken) return '';const s = tokensOf([w, h]);4 unmodified linesfunction 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);5 unmodified linesconst 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 bufferconst 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();14 unmodified linesort.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) });26 unmodified linespre.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,26 unmodified lines27282930313233205 unmodified lines23924024124224324424524624724824925025125225325425525625725825910 unmodified lines27027127227327427527627727827928028128228328415 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434510 unmodified lines35635735835936036136218 unmodified lines38138238338438538638738810 unmodified lines3994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314322 unmodified lines4354364374384394404414424434 unmodified lines4484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874885 unmodified lines49449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652714 unmodified lines54254354454554654754854955055155255355455555655755855956056156226 unmodified lines58959059159259359459559626 unmodified linesconst fr = Math.fround;const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];const CACHE = 'dflow2-web-v2';// Beta(1.25, 1.25) quantiles of linspace(0, 1, steps + 1), float32 (scipy.stats.beta.ppf).const BETA_GRID = {1: [0, 1],205 unmodified lines// ---------- engine ----------class DFlowWeb {// ditDir: folder prefix of the denoiser parts ('' for 4-bit, 'q8/' for 8-bit).// tileCore: decoder tile side in latent cells (the GPU's largest buffer sets it).constructor({ ort, base, files, ditDir = '', tileCore = Infinity, log = () => {}, progress = () => {} }) {this.ort = ort; this.base = base.replace(/\/$/, ''); this.files = files;this.ditDir = ditDir; this.tileCore = tileCore;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 = {}, dir = part) {const onnx = await fetchBytes(this.url(`${dir}/${part}.onnx`));const data = await fetchBytes(this.url(`${dir}/${part}.onnx.data`),(got, total) => this.progress(part, got, total || this.files?.[dir] || 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, {10 unmodified linesthis.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.ditDir + p);}this.sessions.vae_trunk = await this._session('vae_trunk', 'webgpu');this.sessions.vae_head = await this._session('vae_head', 'webgpu');}async release() {for (const s of Object.values(this.sessions)) { try { await s.release(); } catch { /* already gone */ } }this.sessions = {}; this.ready = false;}async encode(prompt) {15 unmodified linesreturn res;}// Decoder: global trunk once, then the local conv head tile by tile. Tiles overlap by// HALO latent cells, wider than the head's receptive field (~6.6 cells), so the result// is identical to one full pass (checked: max difference 0.0).async decode(x, gh, gw, onDecode = () => {}) {const T = this.ort.Tensor, n = gh * gw, C = 1152, HALO = 8, W = gw * 16, H = gh * 16;const vt = vaeTables(gh, gw);const tr = await this.sessions.vae_trunk.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 F = tr.feats.data;const core = Math.max(1, Math.min(this.tileCore, Math.max(gh, gw)));const img = new ImageData(W, H), rgb = new Float32Array(3 * W * H);const tiles = Math.ceil(gh / core) * Math.ceil(gw / core);let done = 0;for (let y0 = 0; y0 < gh; y0 += core) for (let x0 = 0; x0 < gw; x0 += core) {const y1 = Math.min(gh, y0 + core), x1 = Math.min(gw, x0 + core);const ya = Math.max(0, y0 - HALO), xa = Math.max(0, x0 - HALO);const yb = Math.min(gh, y1 + HALO), xb = Math.min(gw, x1 + HALO), th = yb - ya, tw = xb - xa;const tile = new Float32Array(C * th * tw);for (let c = 0; c < C; c++) for (let r = 0; r < th; r++) {const src = c * n + (ya + r) * gw + xa;tile.set(F.subarray(src, src + tw), (c * th + r) * tw);}const o = (await this.sessions.vae_head.run({ feats: new T('float32', tile, [1, C, th, tw]) })).rgb.data;const TW = tw * 16, TH = th * 16;for (let py = (y0 - ya) * 16; py < (y1 - ya) * 16; py++) {const Y = ya * 16 + py;for (let px = (x0 - xa) * 16; px < (x1 - xa) * 16; px++) {const X = xa * 16 + px, i = Y * W + X, k = py * TW + px;for (let ch = 0; ch < 3; ch++) {const v = o[ch * TH * TW + k];rgb[ch * W * H + i] = v; img.data[i * 4 + ch] = Math.round(v * 255);}img.data[i * 4 + 3] = 255;}}onDecode(++done, tiles);}return { img, rgb };}async velocity(x, t, ctx) {const T = this.ort.Tensor, { n, feeds } = ctx;const lat = new Float32Array(n * 96); // [96, n] -> [n, 96]10 unmodified linesreturn v;}async generate({ prompt, width, height, seed, steps = 4, noise, decode = true, onStep = () => {}, onDecode = () => {} }) {const T = this.ort.Tensor, gh = height / 16, gw = width / 16, n = gh * gw;const t0 = performance.now();const enc = await this.encode(prompt);18 unmodified linesonStep(i + 1, steps, (performance.now() - s0) / 1000, x0);}const tDen = performance.now();if (!decode) return { ids: enc.ids, text: enc.text, latent: x, vels, times: ts };const { img, rgb } = await this.decode(x, gh, gw, onDecode);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 } };10 unmodified linesconst 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';// Weights: the 8-bit denoiser matches the original model (37 dB from fp32 at 1824x1024);// 4-bit is visibly softer (23 dB) and only offered for devices short on memory.const QUALITY = { q8: ['8-bit', 'full detail'], q4: ['4-bit', 'softer, low memory'] };const filesFor = (v) => [['text', 'text'], ...DIT_PARTS.map((p) => [`${v}/${p}`, p]),['vae_trunk', 'vae_trunk'], ['vae_head', 'vae_head']];const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* private mode */ } } };// [width, height, note]. The model and the LoRA were trained at about 1 MP and above; detail// scales with the token count (one token per 16x16 pixels), so 512² is only a quick preview.const SIZES = [[1216, 832, 'trained'], [832, 1216, 'trained'], [1824, 1024, 'trained, LoRA card size'],[1024, 1824, 'trained'], [1024, 1024, ''], [768, 768, ''], [640, 640, ''], [512, 512, 'preview, least detail']];const MOBILE = navigator.userAgentData?.mobile ?? /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);const LOW_MEMORY = MOBILE && (navigator.deviceMemory ?? 4) < 8;const DEFAULTS = MOBILE ? ['768x768', '640x640', '512x512'] : ['1216x832', '1024x1024', '768x768', '640x640', '512x512'];if (/^\d{2,4}x\d{2,4}$/.test(q.get('size') || '')) { // test hook, multiples of 16 onlyconst sz = q.get('size').split('x').map(Number);if (sz.every((v) => v % 16 === 0)) { SIZES.unshift([...sz, 'test']); DEFAULTS.unshift(sz.join('x')); }}const $ = (id) => document.getElementById(id);const ui = { go: $('go'), msg: $('msg'), bar: $('bar').firstElementChild, size: $('size'), seed: $('seed'),random: $('random'), quality: $('quality'), 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, bufLimit = Infinity, tileCore = Infinity, gpuName = 'GPU', perToken = null, busy = false, saveUrl = null;const variant = () => ui.quality.value || 'q8';const gb = (b) => (b / 1e9).toFixed(2) + ' GB', mb = (b) => (b / 1e6).toFixed(0) + ' MB';function status(text, frac = null, bad = false) {2 unmodified lines}const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical prompt// Largest single GPU buffer a size needs (fp32): one head's attention map (the graphs run// attention head by head) and the MLP hidden layer. The decoder runs in tiles sized to fit.const bufferNeed = ([w, h]) => { const s = tokensOf([w, h]) + 16; return Math.max(s * s * 4, s * 9216 * 4); };function estimate([w, h]) { // seconds for a whole image, from the last runif (!perToken) return '';const s = tokensOf([w, h]);4 unmodified linesfunction fillSizes() {const keep = ui.size.value;ui.size.innerHTML = '';for (const [w, h, note] of SIZES) {if (bufferNeed([w, h]) > bufLimit) continue;const o = document.createElement('option');o.value = `${w}x${h}`;o.textContent = `${w}×${h}${note ? ', ' + note : ''}${estimate([w, h])}`;ui.size.append(o);}const have = (v) => [...ui.size.options].some((o) => o.value === v);ui.size.value = keep && have(keep) ? keep : (DEFAULTS.find(have) || ui.size.options[0]?.value);}async function storageLine() {try {const est = await navigator.storage?.estimate?.();const files = filesFor(variant());const cached = manifest ? (await Promise.all(files.map(([d, n]) => isCached(`${BASE}/${d}/${n}.onnx.data`)))).filter(Boolean).length : 0;ui.store.textContent = `${cached} of ${files.length} files for the ${QUALITY[variant()][0]} model stored in this browser` +(est ? ` (site storage in use ${gb(est.usage || 0)}, quota ${gb(est.quota || 0)}).` : '.');return cached === files.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 ${manifest ? (manifest.total[variant()] / 1e9).toFixed(1) : '2.7'} 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(); });try { // drop files of older page versionsfor (const k of await caches.keys()) if (k.startsWith('dflow2-web-') && k !== CACHE) await caches.delete(k);} catch { /* no Cache API */ }ui.wipe.addEventListener('click', async () => {if (busy) return;await caches.delete(CACHE);5 unmodified linesconst 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);bufLimit = lim;// decoder tile side in latent cells: its largest layer is 128 ch x (16 (core + 2 x 8))^2 fp32tileCore = Math.max(4, Math.min(512, Math.floor(Math.sqrt(lim / 512) / 16) - 16));if (/^\d{1,3}$/.test(q.get('tile') || '')) tileCore = Math.max(1, Number(q.get('tile'))); // test hookconst info = adapter.info || {};gpuName = [info.vendor, info.architecture].filter(Boolean).join(' ') || 'GPU';ui.backend.textContent = `WebGPU on ${gpuName}`;const hidden = SIZES.filter((s) => bufferNeed(s) > lim).map(([w, h]) => `${w}×${h}`);ui.limits.textContent = `This GPU allows single buffers up to ${mb(lim)}.` +(hidden.length ? ` Sizes that need more are hidden: ${hidden.join(', ')}.` : ' Every size fits.');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}).`); }for (const [v, [bits, note]] of Object.entries(QUALITY)) {const o = document.createElement('option');o.value = v; o.textContent = `${bits}, ${note} · ${(manifest.total[v] / 1e9).toFixed(1)} GB`;ui.quality.append(o);}ui.quality.value = QUALITY[store.get('dflow2-quality')] ? store.get('dflow2-quality') : (LOW_MEMORY ? 'q4' : 'q8');ui.backend.textContent = `WebGPU on ${gpuName} · ${QUALITY[variant()][0]} weights`;ui.quality.addEventListener('change', async () => {store.set('dflow2-quality', variant());ui.backend.textContent = `WebGPU on ${gpuName} · ${QUALITY[variant()][0]} weights`;if (engine && !busy) { await engine.release(); engine = null; }perToken = null; fillSizes(); ui.speed.textContent = 'speed shown after the first image';await buttonLabel();});ui.go.disabled = false;ui.go.addEventListener('click', run);await buttonLabel();14 unmodified linesort.env.webgpu.powerPreference = 'high-performance';const { Tokenizer } = await import(TOK_URL);navigator.storage?.persist?.().catch(() => {});const v = variant(), total = manifest.total[v];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, ditDir: `${v}/`, tileCore,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, dir = part) => {const s = await orig(part, ep, extra, dir);done += manifest.parts[dir] || 0;return s;};await engine.load({ tokenizer: new Tokenizer(tj, tc) });26 unmodified linespre.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));},onDecode: (i, n) => { if (n > 1) status(`Decoding the image, tile ${i} of ${n}…`, (4 + i / n) / 4.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,
9 unmodified lines101112131415161718192021222324252627282913 unmodified lines43444546474849509 unmodified lines</head><body><main><p id="line"><b>DFlow2 2B · 4 steps</b>, text to image on your own GPU, nothing leaves this tab<span class="sep">|</span> <span id="backend">checking WebGPU…</span><span class="sep">|</span> <span id="speed">speed shown after the first image</span></p><section id="input"><label for="prompt" class="sr">Prompt</label><textarea id="prompt" rows="7" spellcheck="false">A snow leopard walking along a rocky ridge in falling snow, telephoto wildlife photograph, natural light</textarea><p class="hint">Describe a photo or a painting: subject, setting, light, medium. Text in "double quotes" is spelled letter by letter.</p></section><section id="settings"><label>Size <select id="size"></select></label><label>Seed <input id="seed" type="number" min="0" max="4294967295" value="0"></label><label class="check"><input id="random" type="checkbox" checked> new seed each run</label></section><section id="run">13 unmodified lines<summary>Storage, limits and credits</summary><p id="store">Nothing downloaded yet.</p><button id="wipe" type="button">Delete downloaded model</button><p>The model downloads once (about 1.6 GB) into this browser's storage, then works offline.It needs WebGPU (Chrome or Edge 121+, Android 12+, Safari 26) and roughly 2 GB of free GPU memory.On a phone, close other tabs first. If the tab reloads by itself, the GPU ran out of memory: pick a smaller size.</p><p id="limits"></p><p>Model: <a href="https://huggingface.co/data-archetype/dflow_2b" target="_blank" rel="noopener">dflow_2b</a> by Data Archetype,9 unmodified lines1011121314151617181920212223242526272829303113 unmodified lines45464748495051529 unmodified lines</head><body><main><p id="line"><b><a href="https://huggingface.co/data-archetype/dflow_2b" target="_blank" rel="noopener">DFlow2 2B</a> · <a href="https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA" target="_blank" rel="noopener">4 steps</a></b>, text to image on your own GPU, nothing leaves this tab<span class="sep">|</span> <span id="backend">checking WebGPU…</span><span class="sep">|</span> <span id="speed">speed shown after the first image</span></p><section id="input"><label for="prompt" class="sr">Prompt</label><textarea id="prompt" rows="7" spellcheck="false">A snow leopard walking along a rocky ridge in falling snow, telephoto wildlife photograph, natural light</textarea><p class="hint">Describe a photo or a painting: subject, setting, light, medium. Text in "double quotes" is spelled letter by letter. Detail grows with size: the model was trained at about 1 MP, 512² is a quick preview.</p></section><section id="settings"><label for="size">Size</label><select id="size"></select><label for="quality">Weights</label><select id="quality"></select><label for="seed">Seed</label><span class="seedrow"><input id="seed" type="number" min="0" max="4294967295" value="0"><label class="check"><input id="random" type="checkbox" checked> random</label></span></section><section id="run">13 unmodified lines<summary>Storage, limits and credits</summary><p id="store">Nothing downloaded yet.</p><button id="wipe" type="button">Delete downloaded model</button><p>The model downloads once (about 2.7 GB with 8-bit weights, 1.7 GB with 4-bit) into this browser's storage, then works offline.It needs WebGPU (Chrome or Edge 121+, Android 12+, Safari 26) and roughly 3 GB of free GPU memory for 8-bit, 2 GB for 4-bit.On a phone, close other tabs first. If the tab reloads by itself, the GPU ran out of memory: pick a smaller size.</p><p id="limits"></p><p>Model: <a href="https://huggingface.co/data-archetype/dflow_2b" target="_blank" rel="noopener">dflow_2b</a> by Data Archetype,
23 unmodified lines2425262728293023 unmodified lines#line b { color: var(--ink); font-weight: 600; }.sep { opacity: .5; padding: 0 2px; }#input { grid-area: input; }#settings { grid-area: settings; display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; }#run { grid-area: run; display: grid; gap: 6px; }#output { grid-area: output; display: grid; gap: 6px; justify-items: start; }#more { grid-area: more; color: var(--muted); font-size: 13px; }23 unmodified lines2425262728293031323323 unmodified lines#line b { color: var(--ink); font-weight: 600; }.sep { opacity: .5; padding: 0 2px; }#input { grid-area: input; }#settings { grid-area: settings; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 4px 8px; align-items: center; }#settings select { width: 100%; min-width: 0; }.seedrow { display: flex; gap: 10px; align-items: center; }.seedrow input[type=number] { width: 7.5em; }#run { grid-area: run; display: grid; gap: 6px; }#output { grid-area: output; display: grid; gap: 6px; justify-items: start; }#more { grid-area: more; color: var(--muted); font-size: 13px; }
README.md+4-2
app.js+125-48
index.html+9-7
style.css+4-1