Nekochu commited on
Commit
bb452ca
·
verified ·
1 Parent(s): dad4d17

8-bit weights by default, trained ~1 MP size by default, tiled decoder, header links

Browse files
Files changed (4) hide show
  1. README.md +4 -2
  2. app.js +125 -48
  3. index.html +9 -7
  4. style.css +4 -1
README.md CHANGED
@@ -20,8 +20,10 @@ Text to image with [dflow_2b](https://huggingface.co/data-archetype/dflow_2b) an
20
  in your browser tab on your own GPU through WebGPU and ONNX Runtime Web. Nothing is sent to a server.
21
 
22
  - Needs WebGPU: Chrome or Edge 121+ (Android 12+ on phones), or Safari 26.
23
- - Downloads about 1.7 GB once, then works from the browser's storage.
24
- - Needs about 2 GB of free GPU memory. On a phone, close other tabs and start at 512×512.
 
 
25
 
26
  Weights and conversion details: [WeReCooking2/DFlow2-4step-ONNX-WebGPU](https://huggingface.co/WeReCooking2/DFlow2-4step-ONNX-WebGPU).
27
 
 
20
  in your browser tab on your own GPU through WebGPU and ONNX Runtime Web. Nothing is sent to a server.
21
 
22
  - Needs WebGPU: Chrome or Edge 121+ (Android 12+ on phones), or Safari 26.
23
+ - Downloads once, then works from the browser's storage: about 2.7 GB with the default 8-bit weights
24
+ (same output as the original model), 1.7 GB with the optional 4-bit ones (softer, for low-memory devices).
25
+ - Picks the trained size (about 1 MP) when your GPU allows it. 512×512 is a quick preview with far
26
+ less detail, since the model was trained at 1 MP and above.
27
 
28
  Weights and conversion details: [WeReCooking2/DFlow2-4step-ONNX-WebGPU](https://huggingface.co/WeReCooking2/DFlow2-4step-ONNX-WebGPU).
29
 
app.js CHANGED
@@ -27,7 +27,7 @@ function tokenizePrompt(tokenizer, text, frame = { prefix: [2], suffix: [] }) {
27
 
28
  const fr = Math.fround;
29
  const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];
30
- const CACHE = 'dflow2-web-v1';
31
  // Beta(1.25, 1.25) quantiles of linspace(0, 1, steps + 1), float32 (scipy.stats.beta.ppf).
32
  const BETA_GRID = {
33
  1: [0, 1],
@@ -239,18 +239,21 @@ function previewImage(x0, gh, gw, P) {
239
 
240
  // ---------- engine ----------
241
  class DFlowWeb {
242
- constructor({ ort, base, files, log = () => {}, progress = () => {} }) {
 
 
243
  this.ort = ort; this.base = base.replace(/\/$/, ''); this.files = files;
 
244
  this.log = log; this.progress = progress;
245
  this.sessions = {}; this.rows = new Map(); this.textCache = new Map();
246
  }
247
 
248
  url(name) { return `${this.base}/${name}`; }
249
 
250
- async _session(part, ep, extra = {}) {
251
- const onnx = await fetchBytes(this.url(`${part}/${part}.onnx`));
252
- const data = await fetchBytes(this.url(`${part}/${part}.onnx.data`),
253
- (got, total) => this.progress(part, got, total || this.files?.[part] || 0));
254
  this.log(`${part}: ${(data.bytes.length / 1e6).toFixed(0)} MB ${data.cached ? '(cached)' : '(downloaded)'}, starting ${ep}`);
255
  const t0 = performance.now();
256
  const s = await this.ort.InferenceSession.create(onnx.bytes, {
@@ -267,9 +270,15 @@ class DFlowWeb {
267
  this.sessions.text = await this._session('text', 'wasm');
268
  for (const p of DIT_PARTS) {
269
  const loc = p === 'dit_d' ? 'cpu' : 'gpu-buffer';
270
- this.sessions[p] = await this._session(p, 'webgpu', { preferredOutputLocation: loc });
271
  }
272
- this.sessions.vae_dec = await this._session('vae_dec', 'webgpu');
 
 
 
 
 
 
273
  }
274
 
275
  async encode(prompt) {
@@ -291,6 +300,46 @@ class DFlowWeb {
291
  return res;
292
  }
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  async velocity(x, t, ctx) {
295
  const T = this.ort.Tensor, { n, feeds } = ctx;
296
  const lat = new Float32Array(n * 96); // [96, n] -> [n, 96]
@@ -307,7 +356,7 @@ class DFlowWeb {
307
  return v;
308
  }
309
 
310
- async generate({ prompt, width, height, seed, steps = 4, noise, onStep = () => {} }) {
311
  const T = this.ort.Tensor, gh = height / 16, gw = width / 16, n = gh * gw;
312
  const t0 = performance.now();
313
  const enc = await this.encode(prompt);
@@ -332,17 +381,8 @@ class DFlowWeb {
332
  onStep(i + 1, steps, (performance.now() - s0) / 1000, x0);
333
  }
334
  const tDen = performance.now();
335
- const vt = vaeTables(gh, gw);
336
- const out = await this.sessions.vae_dec.run({ z: new T('float32', x, [1, 96, gh, gw]),
337
- v_sin: new T('float32', vt.sin, [n, 64]), v_cos: new T('float32', vt.cos, [n, 64]) });
338
- const rgb = out.rgb.data;
339
- const img = new ImageData(width, height), hw = width * height;
340
- for (let i = 0; i < hw; i++) {
341
- img.data[i * 4] = Math.round(rgb[i] * 255);
342
- img.data[i * 4 + 1] = Math.round(rgb[hw + i] * 255);
343
- img.data[i * 4 + 2] = Math.round(rgb[2 * hw + i] * 255);
344
- img.data[i * 4 + 3] = 255;
345
- }
346
  const tEnd = performance.now();
347
  return { image: img, ids: enc.ids, text: enc.text, latent: x, vels, rgb, times: ts,
348
  timing: { text: (tText - t0) / 1000, denoise: (tDen - tText) / 1000, decode: (tEnd - tDen) / 1000 } };
@@ -359,22 +399,34 @@ const hub = (v) => (v && /^https:\/\/huggingface\.co\/[\w.-]+\/[\w.-]+\/resolve\
359
  const BASE = local(q.get('base')) || hub(q.get('base')) || `https://huggingface.co/${REPO}/resolve/main`;
360
  const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
361
  const TOK_URL = local(q.get('tok')) || 'https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/dist/tokenizers.min.mjs';
362
- const PARTS = ['text', ...DIT_PARTS, 'vae_dec'];
363
- const SIZES = [[512, 512], [384, 640], [640, 384], [512, 768], [768, 512], [640, 640], [768, 768],
364
- [832, 1216], [1216, 832], [1024, 1024]];
 
 
 
 
 
 
 
 
 
 
 
365
 
366
  if (/^\d{2,4}x\d{2,4}$/.test(q.get('size') || '')) { // test hook, multiples of 16 only
367
  const sz = q.get('size').split('x').map(Number);
368
- if (sz.every((v) => v % 16 === 0)) SIZES.unshift(sz);
369
  }
370
  const $ = (id) => document.getElementById(id);
371
  const ui = { go: $('go'), msg: $('msg'), bar: $('bar').firstElementChild, size: $('size'), seed: $('seed'),
372
- random: $('random'), canvas: $('canvas'), save: $('save'), prompt: $('prompt'), backend: $('backend'),
373
  speed: $('speed'), store: $('store'), wipe: $('wipe'), limits: $('limits'), more: $('more') };
374
  const ctx2d = ui.canvas.getContext('2d');
375
  ui.repo = $('repo'); ui.repo.href = `https://huggingface.co/${REPO}`; ui.repo.textContent = REPO;
376
 
377
- let ort, engine, manifest, maxTokens = Infinity, perToken = null, busy = false, saveUrl = null;
 
378
  const gb = (b) => (b / 1e9).toFixed(2) + ' GB', mb = (b) => (b / 1e6).toFixed(0) + ' MB';
379
 
380
  function status(text, frac = null, bad = false) {
@@ -383,6 +435,9 @@ function status(text, frac = null, bad = false) {
383
  }
384
 
385
  const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical prompt
 
 
 
386
  function estimate([w, h]) { // seconds for a whole image, from the last run
387
  if (!perToken) return '';
388
  const s = tokensOf([w, h]);
@@ -393,38 +448,41 @@ function estimate([w, h]) { // seconds for a whole imag
393
  function fillSizes() {
394
  const keep = ui.size.value;
395
  ui.size.innerHTML = '';
396
- for (const sz of SIZES) {
397
- if (tokensOf(sz) > maxTokens) continue;
398
  const o = document.createElement('option');
399
- o.value = sz.join('x');
400
- const tag = sz[0] === sz[1] ? '' : sz[0] < sz[1] ? ' portrait' : ' landscape';
401
- const trained = (sz[0] === 832 && sz[1] === 1216) || (sz[0] === 1216 && sz[1] === 832) ? ', trained size' : '';
402
- o.textContent = `${sz[0]}×${sz[1]}${tag}${trained}${estimate(sz)}`;
403
  ui.size.append(o);
404
  }
405
- ui.size.value = keep && [...ui.size.options].some((o) => o.value === keep) ? keep : (q.get('size') || '512x512');
 
406
  }
407
 
408
  async function storageLine() {
409
  try {
410
  const est = await navigator.storage?.estimate?.();
411
- const cached = manifest ? (await Promise.all(PARTS.map((p) => isCached(`${BASE}/${p}/${p}.onnx.data`)))).filter(Boolean).length : 0;
412
- ui.store.textContent = `${cached} of ${PARTS.length} model files stored in this browser` +
 
413
  (est ? ` (site storage in use ${gb(est.usage || 0)}, quota ${gb(est.quota || 0)}).` : '.');
414
- return cached === PARTS.length;
415
  } catch { return false; }
416
  }
417
 
418
  async function buttonLabel() {
419
  if (engine?.ready) { ui.go.textContent = 'Generate'; return; }
420
  const all = await storageLine();
421
- ui.go.textContent = all ? 'Load model and generate' : `Download model (${manifest ? gb(manifest.total) : '1.6 GB'}) and generate`;
422
  }
423
 
424
  async function init() {
425
  ui.random.addEventListener('change', () => { ui.seed.disabled = ui.random.checked; });
426
  ui.seed.disabled = ui.random.checked;
427
  ui.save.addEventListener('click', (e) => { if (ui.save.classList.contains('disabled')) e.preventDefault(); });
 
 
 
428
  ui.wipe.addEventListener('click', async () => {
429
  if (busy) return;
430
  await caches.delete(CACHE);
@@ -436,16 +494,34 @@ async function init() {
436
  const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
437
  if (!adapter) return fail('WebGPU is present but no GPU adapter was found (blocklisted driver or disabled flag).');
438
  const lim = Math.min(adapter.limits.maxStorageBufferBindingSize, adapter.limits.maxBufferSize);
439
- maxTokens = Math.floor(Math.sqrt(lim / (18 * 4))); // one fp32 attention map [18, S, S] must fit a buffer
 
 
 
440
  const info = adapter.info || {};
441
- const gpu = [info.vendor, info.architecture].filter(Boolean).join(' ') || 'GPU';
442
- ui.backend.textContent = `WebGPU on ${gpu} · 4-bit weights`;
443
- ui.limits.textContent = `This GPU allows buffers up to ${mb(lim)}, so images up to about ${maxTokens - 48} latent tokens ` +
444
- `(${Math.round(Math.sqrt((maxTokens - 48) * 256))}² pixels). Larger sizes are hidden.`;
 
445
  fillSizes();
446
  try {
447
  manifest = JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/manifest.json`)).bytes));
448
  } catch (e) { return fail(`Could not reach the model repo (${e.message}).`); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  ui.go.disabled = false;
450
  ui.go.addEventListener('click', run);
451
  await buttonLabel();
@@ -466,21 +542,21 @@ async function load() {
466
  ort.env.webgpu.powerPreference = 'high-performance';
467
  const { Tokenizer } = await import(TOK_URL);
468
  navigator.storage?.persist?.().catch(() => {});
469
- const total = manifest.total;
470
  let done = 0;
471
  status('Tokenizer…', 0);
472
  const [tj, tc] = await Promise.all(['tokenizer.json', 'tokenizer_config.json'].map(async (f) =>
473
  JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/${f}`)).bytes))));
474
  engine = new DFlowWeb({
475
- ort, base: BASE, files: manifest.parts,
476
  log: (m) => status(m, done / total),
477
  progress: (part, got, size) => status(`Downloading ${part}: ${mb(got)} of ${mb(size)} · ${gb(done + got)} of ${gb(total)}`,
478
  (done + got) / total),
479
  });
480
  const orig = engine._session.bind(engine);
481
- engine._session = async (part, ep, extra) => {
482
- const s = await orig(part, ep, extra);
483
- done += manifest.parts[part] || 0;
484
  return s;
485
  };
486
  await engine.load({ tokenizer: new Tokenizer(tj, tc) });
@@ -513,7 +589,8 @@ async function run() {
513
  pre.width = img.width; pre.height = img.height; pre.getContext('2d').putImageData(img, 0, 0);
514
  ctx2d.imageSmoothingEnabled = true; ctx2d.drawImage(pre, 0, 0, w, h);
515
  status(i < n ? `Step ${i} of ${n} · ${sec.toFixed(1)} s per step` : 'Decoding the image…', i / (n + 0.5));
516
- } });
 
517
  ctx2d.putImageData(res.image, 0, 0);
518
  const total = (performance.now() - t0) / 1000;
519
  perToken = { step: res.timing.denoise / 4, tokens: (w * h) / 256 + res.ids.length + 3,
 
27
 
28
  const fr = Math.fround;
29
  const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];
30
+ const CACHE = 'dflow2-web-v2';
31
  // Beta(1.25, 1.25) quantiles of linspace(0, 1, steps + 1), float32 (scipy.stats.beta.ppf).
32
  const BETA_GRID = {
33
  1: [0, 1],
 
239
 
240
  // ---------- engine ----------
241
  class DFlowWeb {
242
+ // ditDir: folder prefix of the denoiser parts ('' for 4-bit, 'q8/' for 8-bit).
243
+ // tileCore: decoder tile side in latent cells (the GPU's largest buffer sets it).
244
+ constructor({ ort, base, files, ditDir = '', tileCore = Infinity, log = () => {}, progress = () => {} }) {
245
  this.ort = ort; this.base = base.replace(/\/$/, ''); this.files = files;
246
+ this.ditDir = ditDir; this.tileCore = tileCore;
247
  this.log = log; this.progress = progress;
248
  this.sessions = {}; this.rows = new Map(); this.textCache = new Map();
249
  }
250
 
251
  url(name) { return `${this.base}/${name}`; }
252
 
253
+ async _session(part, ep, extra = {}, dir = part) {
254
+ const onnx = await fetchBytes(this.url(`${dir}/${part}.onnx`));
255
+ const data = await fetchBytes(this.url(`${dir}/${part}.onnx.data`),
256
+ (got, total) => this.progress(part, got, total || this.files?.[dir] || 0));
257
  this.log(`${part}: ${(data.bytes.length / 1e6).toFixed(0)} MB ${data.cached ? '(cached)' : '(downloaded)'}, starting ${ep}`);
258
  const t0 = performance.now();
259
  const s = await this.ort.InferenceSession.create(onnx.bytes, {
 
270
  this.sessions.text = await this._session('text', 'wasm');
271
  for (const p of DIT_PARTS) {
272
  const loc = p === 'dit_d' ? 'cpu' : 'gpu-buffer';
273
+ this.sessions[p] = await this._session(p, 'webgpu', { preferredOutputLocation: loc }, this.ditDir + p);
274
  }
275
+ this.sessions.vae_trunk = await this._session('vae_trunk', 'webgpu');
276
+ this.sessions.vae_head = await this._session('vae_head', 'webgpu');
277
+ }
278
+
279
+ async release() {
280
+ for (const s of Object.values(this.sessions)) { try { await s.release(); } catch { /* already gone */ } }
281
+ this.sessions = {}; this.ready = false;
282
  }
283
 
284
  async encode(prompt) {
 
300
  return res;
301
  }
302
 
303
+ // Decoder: global trunk once, then the local conv head tile by tile. Tiles overlap by
304
+ // HALO latent cells, wider than the head's receptive field (~6.6 cells), so the result
305
+ // is identical to one full pass (checked: max difference 0.0).
306
+ async decode(x, gh, gw, onDecode = () => {}) {
307
+ const T = this.ort.Tensor, n = gh * gw, C = 1152, HALO = 8, W = gw * 16, H = gh * 16;
308
+ const vt = vaeTables(gh, gw);
309
+ const tr = await this.sessions.vae_trunk.run({ z: new T('float32', x, [1, 96, gh, gw]),
310
+ v_sin: new T('float32', vt.sin, [n, 64]), v_cos: new T('float32', vt.cos, [n, 64]) });
311
+ const F = tr.feats.data;
312
+ const core = Math.max(1, Math.min(this.tileCore, Math.max(gh, gw)));
313
+ const img = new ImageData(W, H), rgb = new Float32Array(3 * W * H);
314
+ const tiles = Math.ceil(gh / core) * Math.ceil(gw / core);
315
+ let done = 0;
316
+ for (let y0 = 0; y0 < gh; y0 += core) for (let x0 = 0; x0 < gw; x0 += core) {
317
+ const y1 = Math.min(gh, y0 + core), x1 = Math.min(gw, x0 + core);
318
+ const ya = Math.max(0, y0 - HALO), xa = Math.max(0, x0 - HALO);
319
+ const yb = Math.min(gh, y1 + HALO), xb = Math.min(gw, x1 + HALO), th = yb - ya, tw = xb - xa;
320
+ const tile = new Float32Array(C * th * tw);
321
+ for (let c = 0; c < C; c++) for (let r = 0; r < th; r++) {
322
+ const src = c * n + (ya + r) * gw + xa;
323
+ tile.set(F.subarray(src, src + tw), (c * th + r) * tw);
324
+ }
325
+ const o = (await this.sessions.vae_head.run({ feats: new T('float32', tile, [1, C, th, tw]) })).rgb.data;
326
+ const TW = tw * 16, TH = th * 16;
327
+ for (let py = (y0 - ya) * 16; py < (y1 - ya) * 16; py++) {
328
+ const Y = ya * 16 + py;
329
+ for (let px = (x0 - xa) * 16; px < (x1 - xa) * 16; px++) {
330
+ const X = xa * 16 + px, i = Y * W + X, k = py * TW + px;
331
+ for (let ch = 0; ch < 3; ch++) {
332
+ const v = o[ch * TH * TW + k];
333
+ rgb[ch * W * H + i] = v; img.data[i * 4 + ch] = Math.round(v * 255);
334
+ }
335
+ img.data[i * 4 + 3] = 255;
336
+ }
337
+ }
338
+ onDecode(++done, tiles);
339
+ }
340
+ return { img, rgb };
341
+ }
342
+
343
  async velocity(x, t, ctx) {
344
  const T = this.ort.Tensor, { n, feeds } = ctx;
345
  const lat = new Float32Array(n * 96); // [96, n] -> [n, 96]
 
356
  return v;
357
  }
358
 
359
+ async generate({ prompt, width, height, seed, steps = 4, noise, decode = true, onStep = () => {}, onDecode = () => {} }) {
360
  const T = this.ort.Tensor, gh = height / 16, gw = width / 16, n = gh * gw;
361
  const t0 = performance.now();
362
  const enc = await this.encode(prompt);
 
381
  onStep(i + 1, steps, (performance.now() - s0) / 1000, x0);
382
  }
383
  const tDen = performance.now();
384
+ if (!decode) return { ids: enc.ids, text: enc.text, latent: x, vels, times: ts };
385
+ const { img, rgb } = await this.decode(x, gh, gw, onDecode);
 
 
 
 
 
 
 
 
 
386
  const tEnd = performance.now();
387
  return { image: img, ids: enc.ids, text: enc.text, latent: x, vels, rgb, times: ts,
388
  timing: { text: (tText - t0) / 1000, denoise: (tDen - tText) / 1000, decode: (tEnd - tDen) / 1000 } };
 
399
  const BASE = local(q.get('base')) || hub(q.get('base')) || `https://huggingface.co/${REPO}/resolve/main`;
400
  const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
401
  const TOK_URL = local(q.get('tok')) || 'https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/dist/tokenizers.min.mjs';
402
+ // Weights: the 8-bit denoiser matches the original model (37 dB from fp32 at 1824x1024);
403
+ // 4-bit is visibly softer (23 dB) and only offered for devices short on memory.
404
+ const QUALITY = { q8: ['8-bit', 'full detail'], q4: ['4-bit', 'softer, low memory'] };
405
+ const filesFor = (v) => [['text', 'text'], ...DIT_PARTS.map((p) => [`${v}/${p}`, p]),
406
+ ['vae_trunk', 'vae_trunk'], ['vae_head', 'vae_head']];
407
+ const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
408
+ set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* private mode */ } } };
409
+ // [width, height, note]. The model and the LoRA were trained at about 1 MP and above; detail
410
+ // scales with the token count (one token per 16x16 pixels), so 512² is only a quick preview.
411
+ const SIZES = [[1216, 832, 'trained'], [832, 1216, 'trained'], [1824, 1024, 'trained, LoRA card size'],
412
+ [1024, 1824, 'trained'], [1024, 1024, ''], [768, 768, ''], [640, 640, ''], [512, 512, 'preview, least detail']];
413
+ const MOBILE = navigator.userAgentData?.mobile ?? /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);
414
+ const LOW_MEMORY = MOBILE && (navigator.deviceMemory ?? 4) < 8;
415
+ const DEFAULTS = MOBILE ? ['768x768', '640x640', '512x512'] : ['1216x832', '1024x1024', '768x768', '640x640', '512x512'];
416
 
417
  if (/^\d{2,4}x\d{2,4}$/.test(q.get('size') || '')) { // test hook, multiples of 16 only
418
  const sz = q.get('size').split('x').map(Number);
419
+ if (sz.every((v) => v % 16 === 0)) { SIZES.unshift([...sz, 'test']); DEFAULTS.unshift(sz.join('x')); }
420
  }
421
  const $ = (id) => document.getElementById(id);
422
  const ui = { go: $('go'), msg: $('msg'), bar: $('bar').firstElementChild, size: $('size'), seed: $('seed'),
423
+ random: $('random'), quality: $('quality'), canvas: $('canvas'), save: $('save'), prompt: $('prompt'), backend: $('backend'),
424
  speed: $('speed'), store: $('store'), wipe: $('wipe'), limits: $('limits'), more: $('more') };
425
  const ctx2d = ui.canvas.getContext('2d');
426
  ui.repo = $('repo'); ui.repo.href = `https://huggingface.co/${REPO}`; ui.repo.textContent = REPO;
427
 
428
+ let ort, engine, manifest, bufLimit = Infinity, tileCore = Infinity, gpuName = 'GPU', perToken = null, busy = false, saveUrl = null;
429
+ const variant = () => ui.quality.value || 'q8';
430
  const gb = (b) => (b / 1e9).toFixed(2) + ' GB', mb = (b) => (b / 1e6).toFixed(0) + ' MB';
431
 
432
  function status(text, frac = null, bad = false) {
 
435
  }
436
 
437
  const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical prompt
438
+ // Largest single GPU buffer a size needs (fp32): one head's attention map (the graphs run
439
+ // attention head by head) and the MLP hidden layer. The decoder runs in tiles sized to fit.
440
+ const bufferNeed = ([w, h]) => { const s = tokensOf([w, h]) + 16; return Math.max(s * s * 4, s * 9216 * 4); };
441
  function estimate([w, h]) { // seconds for a whole image, from the last run
442
  if (!perToken) return '';
443
  const s = tokensOf([w, h]);
 
448
  function fillSizes() {
449
  const keep = ui.size.value;
450
  ui.size.innerHTML = '';
451
+ for (const [w, h, note] of SIZES) {
452
+ if (bufferNeed([w, h]) > bufLimit) continue;
453
  const o = document.createElement('option');
454
+ o.value = `${w}x${h}`;
455
+ o.textContent = `${w}×${h}${note ? ', ' + note : ''}${estimate([w, h])}`;
 
 
456
  ui.size.append(o);
457
  }
458
+ const have = (v) => [...ui.size.options].some((o) => o.value === v);
459
+ ui.size.value = keep && have(keep) ? keep : (DEFAULTS.find(have) || ui.size.options[0]?.value);
460
  }
461
 
462
  async function storageLine() {
463
  try {
464
  const est = await navigator.storage?.estimate?.();
465
+ const files = filesFor(variant());
466
+ const cached = manifest ? (await Promise.all(files.map(([d, n]) => isCached(`${BASE}/${d}/${n}.onnx.data`)))).filter(Boolean).length : 0;
467
+ ui.store.textContent = `${cached} of ${files.length} files for the ${QUALITY[variant()][0]} model stored in this browser` +
468
  (est ? ` (site storage in use ${gb(est.usage || 0)}, quota ${gb(est.quota || 0)}).` : '.');
469
+ return cached === files.length;
470
  } catch { return false; }
471
  }
472
 
473
  async function buttonLabel() {
474
  if (engine?.ready) { ui.go.textContent = 'Generate'; return; }
475
  const all = await storageLine();
476
+ ui.go.textContent = all ? 'Load model and generate' : `Download ${manifest ? (manifest.total[variant()] / 1e9).toFixed(1) : '2.7'} GB and generate`;
477
  }
478
 
479
  async function init() {
480
  ui.random.addEventListener('change', () => { ui.seed.disabled = ui.random.checked; });
481
  ui.seed.disabled = ui.random.checked;
482
  ui.save.addEventListener('click', (e) => { if (ui.save.classList.contains('disabled')) e.preventDefault(); });
483
+ try { // drop files of older page versions
484
+ for (const k of await caches.keys()) if (k.startsWith('dflow2-web-') && k !== CACHE) await caches.delete(k);
485
+ } catch { /* no Cache API */ }
486
  ui.wipe.addEventListener('click', async () => {
487
  if (busy) return;
488
  await caches.delete(CACHE);
 
494
  const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
495
  if (!adapter) return fail('WebGPU is present but no GPU adapter was found (blocklisted driver or disabled flag).');
496
  const lim = Math.min(adapter.limits.maxStorageBufferBindingSize, adapter.limits.maxBufferSize);
497
+ bufLimit = lim;
498
+ // decoder tile side in latent cells: its largest layer is 128 ch x (16 (core + 2 x 8))^2 fp32
499
+ tileCore = Math.max(4, Math.min(512, Math.floor(Math.sqrt(lim / 512) / 16) - 16));
500
+ if (/^\d{1,3}$/.test(q.get('tile') || '')) tileCore = Math.max(1, Number(q.get('tile'))); // test hook
501
  const info = adapter.info || {};
502
+ gpuName = [info.vendor, info.architecture].filter(Boolean).join(' ') || 'GPU';
503
+ ui.backend.textContent = `WebGPU on ${gpuName}`;
504
+ const hidden = SIZES.filter((s) => bufferNeed(s) > lim).map(([w, h]) => `${w}×${h}`);
505
+ ui.limits.textContent = `This GPU allows single buffers up to ${mb(lim)}.` +
506
+ (hidden.length ? ` Sizes that need more are hidden: ${hidden.join(', ')}.` : ' Every size fits.');
507
  fillSizes();
508
  try {
509
  manifest = JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/manifest.json`)).bytes));
510
  } catch (e) { return fail(`Could not reach the model repo (${e.message}).`); }
511
+ for (const [v, [bits, note]] of Object.entries(QUALITY)) {
512
+ const o = document.createElement('option');
513
+ o.value = v; o.textContent = `${bits}, ${note} · ${(manifest.total[v] / 1e9).toFixed(1)} GB`;
514
+ ui.quality.append(o);
515
+ }
516
+ ui.quality.value = QUALITY[store.get('dflow2-quality')] ? store.get('dflow2-quality') : (LOW_MEMORY ? 'q4' : 'q8');
517
+ ui.backend.textContent = `WebGPU on ${gpuName} · ${QUALITY[variant()][0]} weights`;
518
+ ui.quality.addEventListener('change', async () => {
519
+ store.set('dflow2-quality', variant());
520
+ ui.backend.textContent = `WebGPU on ${gpuName} · ${QUALITY[variant()][0]} weights`;
521
+ if (engine && !busy) { await engine.release(); engine = null; }
522
+ perToken = null; fillSizes(); ui.speed.textContent = 'speed shown after the first image';
523
+ await buttonLabel();
524
+ });
525
  ui.go.disabled = false;
526
  ui.go.addEventListener('click', run);
527
  await buttonLabel();
 
542
  ort.env.webgpu.powerPreference = 'high-performance';
543
  const { Tokenizer } = await import(TOK_URL);
544
  navigator.storage?.persist?.().catch(() => {});
545
+ const v = variant(), total = manifest.total[v];
546
  let done = 0;
547
  status('Tokenizer…', 0);
548
  const [tj, tc] = await Promise.all(['tokenizer.json', 'tokenizer_config.json'].map(async (f) =>
549
  JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/${f}`)).bytes))));
550
  engine = new DFlowWeb({
551
+ ort, base: BASE, files: manifest.parts, ditDir: `${v}/`, tileCore,
552
  log: (m) => status(m, done / total),
553
  progress: (part, got, size) => status(`Downloading ${part}: ${mb(got)} of ${mb(size)} · ${gb(done + got)} of ${gb(total)}`,
554
  (done + got) / total),
555
  });
556
  const orig = engine._session.bind(engine);
557
+ engine._session = async (part, ep, extra, dir = part) => {
558
+ const s = await orig(part, ep, extra, dir);
559
+ done += manifest.parts[dir] || 0;
560
  return s;
561
  };
562
  await engine.load({ tokenizer: new Tokenizer(tj, tc) });
 
589
  pre.width = img.width; pre.height = img.height; pre.getContext('2d').putImageData(img, 0, 0);
590
  ctx2d.imageSmoothingEnabled = true; ctx2d.drawImage(pre, 0, 0, w, h);
591
  status(i < n ? `Step ${i} of ${n} · ${sec.toFixed(1)} s per step` : 'Decoding the image…', i / (n + 0.5));
592
+ },
593
+ onDecode: (i, n) => { if (n > 1) status(`Decoding the image, tile ${i} of ${n}…`, (4 + i / n) / 4.5); } });
594
  ctx2d.putImageData(res.image, 0, 0);
595
  const total = (performance.now() - t0) / 1000;
596
  perToken = { step: res.timing.denoise / 4, tokens: (w * h) / 256 + res.ids.length + 3,
index.html CHANGED
@@ -10,20 +10,22 @@
10
  </head>
11
  <body>
12
  <main>
13
- <p id="line"><b>DFlow2 2B · 4 steps</b>, text to image on your own GPU, nothing leaves this tab
14
  <span class="sep">|</span> <span id="backend">checking WebGPU…</span>
15
  <span class="sep">|</span> <span id="speed">speed shown after the first image</span></p>
16
 
17
  <section id="input">
18
  <label for="prompt" class="sr">Prompt</label>
19
  <textarea id="prompt" rows="7" spellcheck="false">A snow leopard walking along a rocky ridge in falling snow, telephoto wildlife photograph, natural light</textarea>
20
- <p class="hint">Describe a photo or a painting: subject, setting, light, medium. Text in "double quotes" is spelled letter by letter.</p>
21
  </section>
22
 
23
  <section id="settings">
24
- <label>Size <select id="size"></select></label>
25
- <label>Seed <input id="seed" type="number" min="0" max="4294967295" value="0"></label>
26
- <label class="check"><input id="random" type="checkbox" checked> new seed each run</label>
 
 
27
  </section>
28
 
29
  <section id="run">
@@ -43,8 +45,8 @@
43
  <summary>Storage, limits and credits</summary>
44
  <p id="store">Nothing downloaded yet.</p>
45
  <button id="wipe" type="button">Delete downloaded model</button>
46
- <p>The model downloads once (about 1.6 GB) into this browser's storage, then works offline.
47
- It needs WebGPU (Chrome or Edge 121+, Android 12+, Safari 26) and roughly 2 GB of free GPU memory.
48
  On a phone, close other tabs first. If the tab reloads by itself, the GPU ran out of memory: pick a smaller size.</p>
49
  <p id="limits"></p>
50
  <p>Model: <a href="https://huggingface.co/data-archetype/dflow_2b" target="_blank" rel="noopener">dflow_2b</a> by Data Archetype,
 
10
  </head>
11
  <body>
12
  <main>
13
+ <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
14
  <span class="sep">|</span> <span id="backend">checking WebGPU…</span>
15
  <span class="sep">|</span> <span id="speed">speed shown after the first image</span></p>
16
 
17
  <section id="input">
18
  <label for="prompt" class="sr">Prompt</label>
19
  <textarea id="prompt" rows="7" spellcheck="false">A snow leopard walking along a rocky ridge in falling snow, telephoto wildlife photograph, natural light</textarea>
20
+ <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>
21
  </section>
22
 
23
  <section id="settings">
24
+ <label for="size">Size</label><select id="size"></select>
25
+ <label for="quality">Weights</label><select id="quality"></select>
26
+ <label for="seed">Seed</label>
27
+ <span class="seedrow"><input id="seed" type="number" min="0" max="4294967295" value="0">
28
+ <label class="check"><input id="random" type="checkbox" checked> random</label></span>
29
  </section>
30
 
31
  <section id="run">
 
45
  <summary>Storage, limits and credits</summary>
46
  <p id="store">Nothing downloaded yet.</p>
47
  <button id="wipe" type="button">Delete downloaded model</button>
48
+ <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.
49
+ 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.
50
  On a phone, close other tabs first. If the tab reloads by itself, the GPU ran out of memory: pick a smaller size.</p>
51
  <p id="limits"></p>
52
  <p>Model: <a href="https://huggingface.co/data-archetype/dflow_2b" target="_blank" rel="noopener">dflow_2b</a> by Data Archetype,
style.css CHANGED
@@ -24,7 +24,10 @@ main {
24
  #line b { color: var(--ink); font-weight: 600; }
25
  .sep { opacity: .5; padding: 0 2px; }
26
  #input { grid-area: input; }
27
- #settings { grid-area: settings; display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; }
 
 
 
28
  #run { grid-area: run; display: grid; gap: 6px; }
29
  #output { grid-area: output; display: grid; gap: 6px; justify-items: start; }
30
  #more { grid-area: more; color: var(--muted); font-size: 13px; }
 
24
  #line b { color: var(--ink); font-weight: 600; }
25
  .sep { opacity: .5; padding: 0 2px; }
26
  #input { grid-area: input; }
27
+ #settings { grid-area: settings; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 4px 8px; align-items: center; }
28
+ #settings select { width: 100%; min-width: 0; }
29
+ .seedrow { display: flex; gap: 10px; align-items: center; }
30
+ .seedrow input[type=number] { width: 7.5em; }
31
  #run { grid-area: run; display: grid; gap: 6px; }
32
  #output { grid-area: output; display: grid; gap: 6px; justify-items: start; }
33
  #more { grid-area: more; color: var(--muted); font-size: 13px; }