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

Ship one app.js: a private static Space returns 401 for module imports

Browse files
Files changed (6) hide show
  1. app.js +0 -0
  2. dflow.js +0 -329
  3. index.html +1 -1
  4. main.js +0 -190
  5. preview.json +0 -0
  6. prompt.js +0 -19
app.js ADDED
The diff for this file is too large to render. See raw diff
 
dflow.js DELETED
@@ -1,329 +0,0 @@
1
- // dflow_2b + 4-step eDMD/LADD LoRA, in the browser with ONNX Runtime Web.
2
- // Text graph on WASM (Gemma activations stay fp32), denoiser and decoder on WebGPU.
3
- // Port of dflow/{rope3d,schedules,solvers}.py and dinac3 RoPE; every table mirrors
4
- // work/ropes.py, which the ONNX export was verified against.
5
- import { tokenizePrompt } from './prompt.js';
6
-
7
- const fr = Math.fround;
8
- export const DIT_PARTS = ['dit_a', 'dit_b', 'dit_c', 'dit_d'];
9
- export const CACHE = 'dflow2-web-v1';
10
- // Beta(1.25, 1.25) quantiles of linspace(0, 1, steps + 1), float32 (scipy.stats.beta.ppf).
11
- const BETA_GRID = {
12
- 1: [0, 1],
13
- 2: [0, 0.5, 1],
14
- 3: [0, 0.35325562953948975, 0.6467443108558655, 1],
15
- 4: [0, 0.2776529788970947, 0.5, 0.7223470211029053, 1],
16
- 5: [0, 0.23080690205097198, 0.4123722314834595, 0.5876277685165405, 0.7691931128501892, 1],
17
- 6: [0, 0.19865159690380096, 0.35325562953948975, 0.5, 0.6467443108558655, 0.8013483881950378, 1],
18
- 8: [0, 0.15698565542697906, 0.2776529788970947, 0.39030271768569946, 0.5, 0.6096972823143005,
19
- 0.7223470211029053, 0.8430143594741821, 1],
20
- };
21
-
22
- // ---------- schedule ----------
23
- export function timesteps(width, height, steps = 4) {
24
- const base = BETA_GRID[steps];
25
- if (!base) throw new Error(`steps must be one of ${Object.keys(BETA_GRID)}`);
26
- const shift = Math.min(0, -0.25 - Math.log((width * height) / 65536));
27
- const eps = 1.1920928955078125e-07, tiny = 1.1754943508222875e-38;
28
- const out = base.map((t) => {
29
- if (t === 0 || t === 1 || Math.abs(shift) <= 1e-9) return t;
30
- const c = Math.min(Math.max(t, tiny), 1 - eps);
31
- const lg = Math.log(c / (1 - c)) - 0.5 * shift;
32
- return fr(1 / (1 + Math.exp(-lg)));
33
- });
34
- return out.reverse();
35
- }
36
-
37
- export function selfAttentionGain(width, height) {
38
- const area = width * height;
39
- if (area <= 1.05e6) return -0.03;
40
- const frac = Math.log(area / 1.05e6) / Math.log(2.5e6 / 1.05e6);
41
- return -0.03 * Math.max(0, 1 - frac);
42
- }
43
-
44
- // ---------- RoPE tables ----------
45
- const AXES = [[32, 0], [48, 32], [48, 80]]; // [dim, channel offset] per axis, head width 128
46
-
47
- function dflowRows(positions, n) { // positions: Float64Array [n*3]
48
- const sin = new Float32Array(n * 128), cos = new Float32Array(n * 128);
49
- for (const [axis, [dim, off]] of AXES.entries()) {
50
- for (let k = 0; k < dim / 2; k++) {
51
- const f = 1 / Math.pow(10000, (2 * k) / dim);
52
- for (let i = 0; i < n; i++) {
53
- const a = fr(positions[i * 3 + axis] * f);
54
- const s = fr(Math.sin(a)), c = fr(Math.cos(a)), o = i * 128 + off + 2 * k;
55
- sin[o] = s; sin[o + 1] = s; cos[o] = c; cos[o + 1] = c;
56
- }
57
- }
58
- }
59
- return { sin, cos };
60
- }
61
-
62
- function textPositions(L) {
63
- const p = new Float64Array(L * 3);
64
- for (let i = 0; i < L; i++) p[i * 3] = i + 1;
65
- return p;
66
- }
67
-
68
- function jointPositions(L, gh, gw) {
69
- const n = gh * gw, p = new Float64Array((n + L) * 3);
70
- for (let i = 0; i < n; i++) {
71
- const r = Math.floor(i / gw), c = i % gw;
72
- p[i * 3] = L + 1; p[i * 3 + 1] = r - (gh - 1) / 2; p[i * 3 + 2] = c - (gw - 1) / 2;
73
- }
74
- p.set(textPositions(L), n * 3);
75
- return p;
76
- }
77
-
78
- function gemmaTables(L) {
79
- const out = {};
80
- for (const [name, theta, factor] of [['s', 10000, 1], ['f', 1000000, 8]]) {
81
- const inv = new Float32Array(128);
82
- for (let k = 0; k < 128; k++) inv[k] = fr(fr(1 / fr(Math.pow(theta, fr((2 * k) / 256)))) / factor);
83
- const c = new Float32Array(L * 256), s = new Float32Array(L * 256);
84
- for (let i = 0; i < L; i++) for (let k = 0; k < 128; k++) {
85
- const a = fr(i * inv[k]), cv = fr(Math.cos(a)), sv = fr(Math.sin(a));
86
- c[i * 256 + k] = cv; c[i * 256 + 128 + k] = cv; s[i * 256 + k] = sv; s[i * 256 + 128 + k] = sv;
87
- }
88
- out[`g_cos_${name}`] = c; out[`g_sin_${name}`] = s;
89
- }
90
- return out;
91
- }
92
-
93
- function vaeTables(gh, gw) {
94
- const per = new Float32Array(16);
95
- for (let i = 0; i < 16; i++) per[i] = fr(Math.pow(10000, fr((2 * i) / 32)));
96
- const n = gh * gw, sin = new Float32Array(n * 64), cos = new Float32Array(n * 64);
97
- for (let t = 0; t < n; t++) {
98
- const coord = [Math.floor(t / gw), t % gw];
99
- for (let ax = 0; ax < 2; ax++) for (let i = 0; i < 16; i++) {
100
- const a = fr(coord[ax] / per[i]), s = fr(Math.sin(a)), c = fr(Math.cos(a));
101
- const o = t * 64 + ax * 32 + 2 * i;
102
- sin[o] = s; sin[o + 1] = s; cos[o] = c; cos[o + 1] = c;
103
- }
104
- }
105
- return { sin, cos };
106
- }
107
-
108
- // ---------- noise ----------
109
- export function gaussianNoise(count, seed) {
110
- let s = (seed >>> 0) || 1;
111
- const next = () => { // mulberry32
112
- s = (s + 0x6d2b79f5) >>> 0;
113
- let t = s;
114
- t = Math.imul(t ^ (t >>> 15), t | 1);
115
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
116
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
117
- };
118
- const out = new Float32Array(count);
119
- for (let i = 0; i < count; i += 2) {
120
- const u = Math.max(next(), 1e-12), v = next(), r = Math.sqrt(-2 * Math.log(u));
121
- out[i] = r * Math.cos(2 * Math.PI * v);
122
- if (i + 1 < count) out[i + 1] = r * Math.sin(2 * Math.PI * v);
123
- }
124
- return out;
125
- }
126
-
127
- // ---------- downloads ----------
128
- async function openCache() {
129
- try { return await caches.open(CACHE); } catch { return null; }
130
- }
131
-
132
- export async function fetchBytes(url, onBytes) {
133
- const cache = await openCache();
134
- let resp = cache && await cache.match(url);
135
- const cached = Boolean(resp);
136
- if (!resp) {
137
- resp = await fetch(url);
138
- if (!resp.ok) throw new Error(`${resp.status} ${url}`);
139
- const total = Number(resp.headers.get('content-length')) || 0;
140
- const reader = resp.body.getReader();
141
- // Fill one buffer as the stream arrives: no Blob (large Blobs spill to disk and can
142
- // become unreadable when storage is short) and no second copy.
143
- let bytes = new Uint8Array(total || 1 << 20), got = 0;
144
- for (;;) {
145
- const { done, value } = await reader.read();
146
- if (done) break;
147
- if (got + value.length > bytes.length) {
148
- const grown = new Uint8Array(Math.max(bytes.length * 2, got + value.length));
149
- grown.set(bytes.subarray(0, got)); bytes = grown;
150
- }
151
- bytes.set(value, got); got += value.length;
152
- onBytes?.(got, total);
153
- }
154
- if (got !== bytes.length) bytes = bytes.slice(0, got);
155
- if (cache) {
156
- try { await cache.put(url, new Response(bytes)); } catch (e) { console.warn(`not cached (${e.name}): ${url}`); }
157
- }
158
- return { bytes, cached };
159
- }
160
- const bytes = new Uint8Array(await resp.arrayBuffer());
161
- onBytes?.(bytes.length, bytes.length);
162
- return { bytes, cached };
163
- }
164
-
165
- export async function isCached(url) {
166
- const cache = await openCache();
167
- return Boolean(cache && await cache.match(url));
168
- }
169
-
170
- // Token embedding rows, bf16 [262144 x 640] in one file, read with HTTP Range requests:
171
- // a prompt needs a few KB instead of the whole 335 MB table.
172
- const ROW = 640, ROW_BYTES = ROW * 2, EMB_SCALE = fr(Math.sqrt(640));
173
- async function embedRow(url, id, mem) {
174
- if (mem.has(id)) return mem.get(id);
175
- const key = `${url}?row=${id}`;
176
- const cache = await openCache();
177
- let buf = cache && await cache.match(key).then((r) => r && r.arrayBuffer());
178
- if (!buf) {
179
- const r = await fetch(url, { headers: { Range: `bytes=${id * ROW_BYTES}-${id * ROW_BYTES + ROW_BYTES - 1}` } });
180
- if (r.status !== 206 && r.status !== 200) throw new Error(`embedding row ${id}: HTTP ${r.status}`);
181
- buf = await r.arrayBuffer();
182
- if (r.status === 200) buf = buf.slice(id * ROW_BYTES, (id + 1) * ROW_BYTES); // server ignored Range
183
- if (buf.byteLength !== ROW_BYTES) throw new Error(`embedding row ${id}: ${buf.byteLength} bytes`);
184
- if (cache) cache.put(key, new Response(buf.slice(0))).catch(() => {});
185
- }
186
- const u16 = new Uint16Array(buf), u32 = new Uint32Array(ROW);
187
- for (let k = 0; k < ROW; k++) u32[k] = u16[k] << 16; // bf16 -> f32, exact
188
- const f = new Float32Array(u32.buffer);
189
- for (let k = 0; k < ROW; k++) f[k] = fr(f[k] * EMB_SCALE);
190
- mem.set(id, f);
191
- return f;
192
- }
193
-
194
- // ---------- live preview ----------
195
- // dflow's fitted latent -> RGB readout (dflow/preview.py): replicate-padded 3x3 conv
196
- // 96 -> 12, pixel-shuffled x2, so a 1/8-resolution image of the clean estimate.
197
- export function previewImage(x0, gh, gw, P) {
198
- const W = P.w, B = P.b, img = new ImageData(gw * 2, gh * 2), n = gh * gw;
199
- const cells = new Float32Array(12);
200
- for (let i = 0; i < gh; i++) for (let j = 0; j < gw; j++) {
201
- cells.set(B);
202
- for (let c = 0; c < 96; c++) for (let di = -1; di <= 1; di++) {
203
- const ii = Math.min(gh - 1, Math.max(0, i + di));
204
- for (let dj = -1; dj <= 1; dj++) {
205
- const jj = Math.min(gw - 1, Math.max(0, j + dj)), v = x0[c * n + ii * gw + jj];
206
- const k = (di + 1) * 3 + (dj + 1);
207
- for (let o = 0; o < 12; o++) cells[o] += W[(o * 96 + c) * 9 + k] * v;
208
- }
209
- }
210
- for (let o = 0; o < 12; o++) {
211
- const ch = Math.floor(o / 4), sub = o % 4, y = i * 2 + (sub >> 1), xx = j * 2 + (sub & 1);
212
- img.data[(y * gw * 2 + xx) * 4 + ch] = Math.round((Math.max(-1, Math.min(1, cells[o])) + 1) * 127.5);
213
- }
214
- for (let sub = 0; sub < 4; sub++) img.data[((i * 2 + (sub >> 1)) * gw * 2 + j * 2 + (sub & 1)) * 4 + 3] = 255;
215
- }
216
- return img;
217
- }
218
-
219
- // ---------- engine ----------
220
- export class DFlowWeb {
221
- constructor({ ort, base, files, log = () => {}, progress = () => {} }) {
222
- this.ort = ort; this.base = base.replace(/\/$/, ''); this.files = files;
223
- this.log = log; this.progress = progress;
224
- this.sessions = {}; this.rows = new Map(); this.textCache = new Map();
225
- }
226
-
227
- url(name) { return `${this.base}/${name}`; }
228
-
229
- async _session(part, ep, extra = {}) {
230
- const onnx = await fetchBytes(this.url(`${part}/${part}.onnx`));
231
- const data = await fetchBytes(this.url(`${part}/${part}.onnx.data`),
232
- (got, total) => this.progress(part, got, total || this.files?.[part] || 0));
233
- this.log(`${part}: ${(data.bytes.length / 1e6).toFixed(0)} MB ${data.cached ? '(cached)' : '(downloaded)'}, starting ${ep}`);
234
- const t0 = performance.now();
235
- const s = await this.ort.InferenceSession.create(onnx.bytes, {
236
- executionProviders: [ep], graphOptimizationLevel: 'all', logSeverityLevel: 3,
237
- externalData: [{ path: `${part}.onnx.data`, data: data.bytes }], ...extra,
238
- });
239
- this.log(`${part}: ready in ${((performance.now() - t0) / 1000).toFixed(1)} s`);
240
- return s;
241
- }
242
-
243
- async load({ tokenizer }) {
244
- this.tokenizer = tokenizer;
245
- this.preview = await (await fetch(new URL('./preview.json', import.meta.url))).json();
246
- this.sessions.text = await this._session('text', 'wasm');
247
- for (const p of DIT_PARTS) {
248
- const loc = p === 'dit_d' ? 'cpu' : 'gpu-buffer';
249
- this.sessions[p] = await this._session(p, 'webgpu', { preferredOutputLocation: loc });
250
- }
251
- this.sessions.vae_dec = await this._session('vae_dec', 'webgpu');
252
- }
253
-
254
- async encode(prompt) {
255
- if (this.textCache.has(prompt)) return this.textCache.get(prompt);
256
- const ids = tokenizePrompt(this.tokenizer, prompt);
257
- if (ids.length > 256) throw new Error(`prompt is ${ids.length} tokens; this demo takes up to 256`);
258
- const rows = await Promise.all(ids.map((id) => embedRow(this.url('embed_bf16.bin'), id, this.rows)));
259
- const L = ids.length, emb = new Float32Array(L * ROW);
260
- rows.forEach((r, i) => emb.set(r, i * ROW));
261
- const T = this.ort.Tensor, g = gemmaTables(L), r = dflowRows(textPositions(L + 3), L + 3);
262
- const out = await this.sessions.text.run({
263
- emb: new T('float32', emb, [1, L, ROW]),
264
- 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]),
265
- 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]),
266
- r_sin: new T('float32', r.sin, [1, L + 3, 128]), r_cos: new T('float32', r.cos, [1, L + 3, 128]),
267
- });
268
- const res = { ids, text: out.text.data, lt: L + 3 };
269
- this.textCache.clear(); this.textCache.set(prompt, res);
270
- return res;
271
- }
272
-
273
- async velocity(x, t, ctx) {
274
- const T = this.ort.Tensor, { n, feeds } = ctx;
275
- const lat = new Float32Array(n * 96); // [96, n] -> [n, 96]
276
- for (let c = 0; c < 96; c++) for (let i = 0; i < n; i++) lat[i * 96 + c] = x[c * n + i];
277
- const a = await this.sessions.dit_a.run({ lat: new T('float32', lat, [1, n, 96]),
278
- t: new T('float32', new Float32Array([t]), [1]), text: ctx.text, ...feeds });
279
- const b = await this.sessions.dit_b.run({ x: a.x, tact: a.tact, ...feeds });
280
- const c = await this.sessions.dit_c.run({ x: b.y, tact: a.tact, ...feeds });
281
- b.y.dispose();
282
- const d = await this.sessions.dit_d.run({ prefix: a.x, middle: c.y, tact: a.tact, ...feeds });
283
- a.x.dispose(); a.tact.dispose(); c.y.dispose();
284
- const vel = d.vel.data, v = new Float32Array(96 * n); // [n(+text), 96] -> [96, n]
285
- for (let i = 0; i < n; i++) for (let ch = 0; ch < 96; ch++) v[ch * n + i] = vel[i * 96 + ch];
286
- return v;
287
- }
288
-
289
- async generate({ prompt, width, height, seed, steps = 4, noise, onStep = () => {} }) {
290
- const T = this.ort.Tensor, gh = height / 16, gw = width / 16, n = gh * gw;
291
- const t0 = performance.now();
292
- const enc = await this.encode(prompt);
293
- const tText = performance.now();
294
- const rope = dflowRows(jointPositions(enc.lt, gh, gw), n + enc.lt);
295
- const S = n + enc.lt;
296
- const gain = selfAttentionGain(width, height);
297
- const ctx = {
298
- n, text: new T('float32', enc.text, [1, enc.lt, 2304]),
299
- feeds: { rope_sin: new T('float32', rope.sin, [1, S, 128]), rope_cos: new T('float32', rope.cos, [1, S, 128]),
300
- qscale: new T('float32', new Float32Array([fr(Math.exp(gain))]), []) },
301
- };
302
- const ts = timesteps(width, height, steps);
303
- let x = noise ? Float32Array.from(noise) : gaussianNoise(96 * n, seed);
304
- const vels = [];
305
- for (let i = 0; i < steps; i++) {
306
- const s0 = performance.now();
307
- const v = await this.velocity(x, ts[i], ctx);
308
- vels.push(v);
309
- const dt = fr(ts[i + 1] - ts[i]), x0 = new Float32Array(x.length);
310
- for (let k = 0; k < x.length; k++) { x0[k] = x[k] - ts[i] * v[k]; x[k] = fr(x[k] + dt * v[k]); }
311
- onStep(i + 1, steps, (performance.now() - s0) / 1000, x0);
312
- }
313
- const tDen = performance.now();
314
- const vt = vaeTables(gh, gw);
315
- const out = await this.sessions.vae_dec.run({ z: new T('float32', x, [1, 96, gh, gw]),
316
- v_sin: new T('float32', vt.sin, [n, 64]), v_cos: new T('float32', vt.cos, [n, 64]) });
317
- const rgb = out.rgb.data;
318
- const img = new ImageData(width, height), hw = width * height;
319
- for (let i = 0; i < hw; i++) {
320
- img.data[i * 4] = Math.round(rgb[i] * 255);
321
- img.data[i * 4 + 1] = Math.round(rgb[hw + i] * 255);
322
- img.data[i * 4 + 2] = Math.round(rgb[2 * hw + i] * 255);
323
- img.data[i * 4 + 3] = 255;
324
- }
325
- const tEnd = performance.now();
326
- return { image: img, ids: enc.ids, text: enc.text, latent: x, vels, rgb, times: ts,
327
- timing: { text: (tText - t0) / 1000, denoise: (tDen - tText) / 1000, decode: (tEnd - tDen) / 1000 } };
328
- }
329
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html CHANGED
@@ -54,6 +54,6 @@
54
  This 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>
55
  </details>
56
  </main>
57
- <script type="module" src="main.js"></script>
58
  </body>
59
  </html>
 
54
  This 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>
55
  </details>
56
  </main>
57
+ <script type="module" src="app.js"></script>
58
  </body>
59
  </html>
main.js DELETED
@@ -1,190 +0,0 @@
1
- import { CACHE, DFlowWeb, DIT_PARTS, fetchBytes, isCached, previewImage } from './dflow.js';
2
-
3
- const q = new URLSearchParams(location.search);
4
- const REPO = 'WeReCooking2/DFlow2-4step-ONNX-WebGPU';
5
- // Test hooks: only same-origin paths (or the Hub, for weights) are accepted, so a crafted
6
- // link cannot make this page import someone else's script.
7
- const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null);
8
- const hub = (v) => (v && /^https:\/\/huggingface\.co\/[\w.-]+\/[\w.-]+\/resolve\/[\w.-]+$/.test(v) ? v : null);
9
- const BASE = local(q.get('base')) || hub(q.get('base')) || `https://huggingface.co/${REPO}/resolve/main`;
10
- const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
11
- const TOK_URL = local(q.get('tok')) || 'https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/dist/tokenizers.min.mjs';
12
- const PARTS = ['text', ...DIT_PARTS, 'vae_dec'];
13
- const SIZES = [[512, 512], [384, 640], [640, 384], [512, 768], [768, 512], [640, 640], [768, 768],
14
- [832, 1216], [1216, 832], [1024, 1024]];
15
-
16
- if (/^\d{2,4}x\d{2,4}$/.test(q.get('size') || '')) { // test hook, multiples of 16 only
17
- const sz = q.get('size').split('x').map(Number);
18
- if (sz.every((v) => v % 16 === 0)) SIZES.unshift(sz);
19
- }
20
- const $ = (id) => document.getElementById(id);
21
- const ui = { go: $('go'), msg: $('msg'), bar: $('bar').firstElementChild, size: $('size'), seed: $('seed'),
22
- random: $('random'), canvas: $('canvas'), save: $('save'), prompt: $('prompt'), backend: $('backend'),
23
- speed: $('speed'), store: $('store'), wipe: $('wipe'), limits: $('limits'), more: $('more') };
24
- const ctx2d = ui.canvas.getContext('2d');
25
- ui.repo = $('repo'); ui.repo.href = `https://huggingface.co/${REPO}`; ui.repo.textContent = REPO;
26
-
27
- let ort, engine, manifest, maxTokens = Infinity, perToken = null, busy = false, saveUrl = null;
28
- const gb = (b) => (b / 1e9).toFixed(2) + ' GB', mb = (b) => (b / 1e6).toFixed(0) + ' MB';
29
-
30
- function status(text, frac = null, bad = false) {
31
- ui.msg.textContent = text; ui.msg.classList.toggle('bad', bad);
32
- if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;
33
- }
34
-
35
- const tokensOf = ([w, h]) => (w * h) / 256 + 48; // image tokens + a typical prompt
36
- function estimate([w, h]) { // seconds for a whole image, from the last run
37
- if (!perToken) return '';
38
- const s = tokensOf([w, h]);
39
- const sec = 4 * perToken.step * Math.pow(s / perToken.tokens, 1.15) + perToken.decode * (w * h) / perToken.pixels;
40
- return ` · ~${sec < 90 ? Math.round(sec) + ' s' : (sec / 60).toFixed(1) + ' min'}`;
41
- }
42
-
43
- function fillSizes() {
44
- const keep = ui.size.value;
45
- ui.size.innerHTML = '';
46
- for (const sz of SIZES) {
47
- if (tokensOf(sz) > maxTokens) continue;
48
- const o = document.createElement('option');
49
- o.value = sz.join('x');
50
- const tag = sz[0] === sz[1] ? '' : sz[0] < sz[1] ? ' portrait' : ' landscape';
51
- const trained = (sz[0] === 832 && sz[1] === 1216) || (sz[0] === 1216 && sz[1] === 832) ? ', trained size' : '';
52
- o.textContent = `${sz[0]}×${sz[1]}${tag}${trained}${estimate(sz)}`;
53
- ui.size.append(o);
54
- }
55
- ui.size.value = keep && [...ui.size.options].some((o) => o.value === keep) ? keep : (q.get('size') || '512x512');
56
- }
57
-
58
- async function storageLine() {
59
- try {
60
- const est = await navigator.storage?.estimate?.();
61
- const cached = manifest ? (await Promise.all(PARTS.map((p) => isCached(`${BASE}/${p}/${p}.onnx.data`)))).filter(Boolean).length : 0;
62
- ui.store.textContent = `${cached} of ${PARTS.length} model files stored in this browser` +
63
- (est ? ` (site storage in use ${gb(est.usage || 0)}, quota ${gb(est.quota || 0)}).` : '.');
64
- return cached === PARTS.length;
65
- } catch { return false; }
66
- }
67
-
68
- async function buttonLabel() {
69
- if (engine?.ready) { ui.go.textContent = 'Generate'; return; }
70
- const all = await storageLine();
71
- ui.go.textContent = all ? 'Load model and generate' : `Download model (${manifest ? gb(manifest.total) : '1.6 GB'}) and generate`;
72
- }
73
-
74
- async function init() {
75
- ui.random.addEventListener('change', () => { ui.seed.disabled = ui.random.checked; });
76
- ui.seed.disabled = ui.random.checked;
77
- ui.save.addEventListener('click', (e) => { if (ui.save.classList.contains('disabled')) e.preventDefault(); });
78
- ui.wipe.addEventListener('click', async () => {
79
- if (busy) return;
80
- await caches.delete(CACHE);
81
- status('Deleted the stored model. Reloading…');
82
- location.reload();
83
- });
84
- fillSizes();
85
- if (!navigator.gpu) return fail('This browser has no WebGPU. Use Chrome or Edge 121+ (Android 12+), or Safari 26.');
86
- const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
87
- if (!adapter) return fail('WebGPU is present but no GPU adapter was found (blocklisted driver or disabled flag).');
88
- const lim = Math.min(adapter.limits.maxStorageBufferBindingSize, adapter.limits.maxBufferSize);
89
- maxTokens = Math.floor(Math.sqrt(lim / (18 * 4))); // one fp32 attention map [18, S, S] must fit a buffer
90
- const info = adapter.info || {};
91
- const gpu = [info.vendor, info.architecture].filter(Boolean).join(' ') || 'GPU';
92
- ui.backend.textContent = `WebGPU on ${gpu} · 4-bit weights`;
93
- ui.limits.textContent = `This GPU allows buffers up to ${mb(lim)}, so images up to about ${maxTokens - 48} latent tokens ` +
94
- `(${Math.round(Math.sqrt((maxTokens - 48) * 256))}² pixels). Larger sizes are hidden.`;
95
- fillSizes();
96
- try {
97
- manifest = JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/manifest.json`)).bytes));
98
- } catch (e) { return fail(`Could not reach the model repo (${e.message}).`); }
99
- ui.go.disabled = false;
100
- ui.go.addEventListener('click', run);
101
- await buttonLabel();
102
- status('Ready.', 0);
103
- }
104
-
105
- function fail(text) {
106
- ui.backend.textContent = 'no WebGPU';
107
- ui.go.disabled = true; ui.go.textContent = 'Needs WebGPU';
108
- status(text, 0, true);
109
- }
110
-
111
- async function load() {
112
- status('Loading the runtime…', 0);
113
- ort = await import(ORT_URL);
114
- ort.env.logLevel = 'error';
115
- ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
116
- ort.env.webgpu.powerPreference = 'high-performance';
117
- const { Tokenizer } = await import(TOK_URL);
118
- navigator.storage?.persist?.().catch(() => {});
119
- const total = manifest.total;
120
- let done = 0;
121
- status('Tokenizer…', 0);
122
- const [tj, tc] = await Promise.all(['tokenizer.json', 'tokenizer_config.json'].map(async (f) =>
123
- JSON.parse(new TextDecoder().decode((await fetchBytes(`${BASE}/${f}`)).bytes))));
124
- engine = new DFlowWeb({
125
- ort, base: BASE, files: manifest.parts,
126
- log: (m) => status(m, done / total),
127
- progress: (part, got, size) => status(`Downloading ${part}: ${mb(got)} of ${mb(size)} · ${gb(done + got)} of ${gb(total)}`,
128
- (done + got) / total),
129
- });
130
- const orig = engine._session.bind(engine);
131
- engine._session = async (part, ep, extra) => {
132
- const s = await orig(part, ep, extra);
133
- done += manifest.parts[part] || 0;
134
- return s;
135
- };
136
- await engine.load({ tokenizer: new Tokenizer(tj, tc) });
137
- engine.ready = true;
138
- Promise.resolve(ort.env.webgpu.device).then((d) => d?.lost?.then((i) => {
139
- if (i.reason !== 'destroyed') status(`The GPU was lost (${i.message || 'out of memory?'}). Reload the page and pick a smaller size.`, 0, true);
140
- })).catch(() => {});
141
- await storageLine();
142
- }
143
-
144
- async function run() {
145
- if (busy) return;
146
- const prompt = ui.prompt.value.trim();
147
- if (!prompt) { status('Write a prompt first.', null, true); return; }
148
- busy = true; ui.go.disabled = true;
149
- try {
150
- if (!engine?.ready) await load();
151
- const [w, h] = ui.size.value.split('x').map(Number);
152
- const seed = ui.random.checked ? (crypto.getRandomValues(new Uint32Array(1))[0] >>> 1) : (Number(ui.seed.value) >>> 0);
153
- ui.seed.value = seed;
154
- ui.canvas.width = w; ui.canvas.height = h;
155
- ctx2d.clearRect(0, 0, w, h);
156
- ui.save.classList.add('disabled');
157
- status('Reading the prompt…', 0);
158
- const t0 = performance.now();
159
- const pre = document.createElement('canvas');
160
- const res = await engine.generate({ prompt, width: w, height: h, seed,
161
- onStep: (i, n, sec, x0) => {
162
- const img = previewImage(x0, h / 16, w / 16, engine.preview);
163
- pre.width = img.width; pre.height = img.height; pre.getContext('2d').putImageData(img, 0, 0);
164
- ctx2d.imageSmoothingEnabled = true; ctx2d.drawImage(pre, 0, 0, w, h);
165
- status(i < n ? `Step ${i} of ${n} · ${sec.toFixed(1)} s per step` : 'Decoding the image…', i / (n + 0.5));
166
- } });
167
- ctx2d.putImageData(res.image, 0, 0);
168
- const total = (performance.now() - t0) / 1000;
169
- perToken = { step: res.timing.denoise / 4, tokens: (w * h) / 256 + res.ids.length + 3,
170
- decode: res.timing.decode, pixels: w * h };
171
- ui.speed.textContent = `~${Math.round(total)} s per ${w}×${h} image here`;
172
- fillSizes();
173
- ui.canvas.toBlob((blob) => {
174
- if (saveUrl) URL.revokeObjectURL(saveUrl);
175
- saveUrl = URL.createObjectURL(blob);
176
- ui.save.href = saveUrl; ui.save.download = `dflow2_${w}x${h}_seed${seed}.png`;
177
- ui.save.classList.remove('disabled');
178
- }, 'image/png');
179
- status(`Done in ${total.toFixed(1)} s (prompt ${res.timing.text.toFixed(1)} s, 4 steps ` +
180
- `${res.timing.denoise.toFixed(1)} s, decode ${res.timing.decode.toFixed(1)} s). Seed ${seed}.`, 1);
181
- } catch (e) {
182
- console.error(e);
183
- status(`Failed: ${e?.message || e}`, null, true);
184
- } finally {
185
- busy = false; ui.go.disabled = false;
186
- await buttonLabel();
187
- }
188
- }
189
-
190
- init().catch((e) => status(`Failed to start: ${e.message}`, 0, true));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preview.json DELETED
The diff for this file is too large to render. See raw diff
 
prompt.js DELETED
@@ -1,19 +0,0 @@
1
- // dflow_2b prompt tokenization (port of dflow/tokenization.py, plain prompts).
2
- // <bos> frame, then the prompt; text inside straight or curly double quotes on
3
- // one line is tokenized one character at a time, quote marks included.
4
- const QUOTED = /"[^"\n]*"|“[^”\n]*”/gu;
5
-
6
- export function tokenizePrompt(tokenizer, text, frame = { prefix: [2], suffix: [] }) {
7
- const pieces = [];
8
- let cursor = 0;
9
- for (const m of text.matchAll(QUOTED)) {
10
- if (m.index > cursor) pieces.push(text.slice(cursor, m.index));
11
- for (const ch of m[0]) pieces.push(ch); // per code point, as Python iterates
12
- cursor = m.index + m[0].length;
13
- }
14
- if (cursor < text.length) pieces.push(text.slice(cursor));
15
- const ids = [...frame.prefix];
16
- for (const piece of pieces) ids.push(...tokenizer.encode(piece, { add_special_tokens: false }).ids);
17
- ids.push(...frame.suffix);
18
- return ids;
19
- }