File size: 16,960 Bytes
0718f73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Jeveration text-to-image in JS on ONNX Runtime: one backbone pass -> 128 codes -> TA-TiTok decoder -> 512x512 image.
// `ort` is injected (onnxruntime-node for tests, onnxruntime-web/webgpu in the browser); `files` resolves graph paths.
import { Tokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/+esm";

const N_CODES = 128, CODE_DIM = 64, K = 8192, HIDDEN = 2560, CLIP_LEN = 77;

/** Small seeded RNG (xoshiro128**) with uniform and normal draws. Not torch's stream: same seed != same image as PyTorch. */
export class Rng {
  constructor(seed = 0) {
    let s = (seed >>> 0) || 1;
    const sm = () => { s = (s + 0x9e3779b9) >>> 0; let z = s; z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) >>> 0; z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) >>> 0; return (z ^ (z >>> 16)) >>> 0; };
    this.a = sm(); this.b = sm(); this.c = sm(); this.d = sm();
  }
  u32() {
    const r = Math.imul(((Math.imul(this.b, 5) << 7) | (Math.imul(this.b, 5) >>> 25)), 9) >>> 0, t = this.b << 9;
    this.c ^= this.a; this.d ^= this.b; this.b ^= this.c; this.a ^= this.d; this.c ^= t; this.d = (this.d << 11) | (this.d >>> 21);
    return r;
  }
  uniform() { return (this.u32() + 0.5) / 4294967296; }                 // (0, 1)
  normal() { return Math.sqrt(-2 * Math.log(this.uniform())) * Math.cos(2 * Math.PI * this.uniform()); }
}

export class JeverationPipeline {
  /** files: {bytes(path), json(path), path?(path)}; graphs/assets as written by export_rest.py and build_mixed.py */
  static async load(files, { ort, device = "cpu", head = "head_fp16.onnx", backbone = "backbone_int8/manifest.json", i2i = false,
                             progress } = {}) {
    const p = new JeverationPipeline();
    p.ort = ort; p.device = device;
    const S = async (path, { gpuOut = false } = {}) => {
      const opts = { executionProviders: [device === "webgpu" ? "webgpu" : "cpu"], graphOptimizationLevel: "all" };
      if (device === "webgpu" && gpuOut) opts.preferredOutputLocation = "gpu-buffer";   // stays on the GPU for the next graph
      progress?.({ status: "loading", file: path });
      if (files.path && device !== "webgpu") return ort.InferenceSession.create(files.path(path), opts);
      const onP = (e) => progress?.({ status: "progress", ...e });
      opts.externalData = [{ path: path.split("/").pop() + "_data", data: await files.bytes(path + "_data", onP) }];
      return ort.InferenceSession.create(await files.bytes(path, onP), opts);
    };
    p.tpl = await files.json("assets/prompt_template.json");
    p.sampling = await files.json("assets/sampling.json");
    const f32file = async (f) => { const b = await files.bytes(f); return new Float32Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)); };
    p.codebookStd = await f32file("assets/codebook_std.bin");
    p.maskEmb = await f32file("assets/mask_emb.bin");
    p.qwenTok = new Tokenizer(await files.json("tokenizer/qwen/tokenizer.json"), await files.json("tokenizer/qwen/tokenizer_config.json"));
    p.clipTok = new Tokenizer(await files.json("tokenizer/clip/tokenizer.json"), await files.json("tokenizer/clip/tokenizer_config.json"));
    const manifest = await files.json(backbone);                          // the backbone, split into consecutive-layer chunks
    p.s = {
      embed: await S("embed_tokens_q4f16.onnx"),
      decisionEmbed: await S("decision_embed_fp16.onnx"),
      chunks: [],
      head: await S(head),
      clip: await S("clip_text_fp16.onnx"),
      decoder: await S("decoder_fp16.onnx"),
    };
    for (const [i, f] of manifest.files.entries()) p.s.chunks.push(await S(f, { gpuOut: i < manifest.files.length - 1 }));
    p.maxLen = manifest.max_len ?? 320;
    if (i2i) {                                       // image-to-image: the vision tower, the source decoder, the texts
      p.i2iTpl = await files.json("assets/i2i_template.json");
      p.s.vision = await S("vision_encoder_fp16.onnx");
      p.s.sourceDecoder = await S("source_decoder_fp16.onnx");
    }
    return p;
  }

  /** prompt -> backbone token ids: chat head + prompt (<= 128 tokens) + chat tail */
  promptIds(prompt) {
    const ids = this.qwenTok.encode(prompt, { add_special_tokens: false }).ids.slice(0, this.tpl.max_prompt_tokens);
    return [...this.tpl.head_ids, ...ids, ...this.tpl.tail_ids];
  }

  /** prompt -> 77 CLIP ids, padded with 0 after the end token (open_clip's convention, which the decoder was trained with) */
  clipIds(prompt) {
    const ids = this.clipTok.encode(prompt.toLowerCase().trim().replace(/\s+/g, " ")).ids;   // [BOS, ..., EOS]
    const out = new BigInt64Array(CLIP_LEN);
    const body = ids.slice(0, CLIP_LEN);
    if (body.length === CLIP_LEN) body[CLIP_LEN - 1] = ids[ids.length - 1];          // truncated: keep the end token last
    body.forEach((v, i) => { out[i] = BigInt(v); });
    return out;
  }

  /** the shared random state: each position masked (mask_emb) with prob MASK_PROB or a random standardised code, + noise */
  randomState(rng) {
    const { mask_prob: rho, state_noise: sigma } = this.sampling;
    const state = new Float32Array(N_CODES * CODE_DIM);
    let masked = 0;
    const isMasked = [], code = [];
    for (let i = 0; i < N_CODES; i++) isMasked.push(rng.uniform() < rho);
    for (let i = 0; i < N_CODES; i++) code.push(rng.u32() % K);
    const a = Math.sqrt(1 - sigma * sigma);
    for (let i = 0; i < N_CODES; i++) {
      if (isMasked[i]) masked++;
      for (let j = 0; j < CODE_DIM; j++) {
        const v = isMasked[i] ? this.maskEmb[j] : this.codebookStd[code[i] * CODE_DIM + j];
        state[i * CODE_DIM + j] = a * v + sigma * rng.normal();
      }
    }
    return { state, t: new Float32Array([masked / N_CODES]) };
  }

  /** Gumbel noise [128*8192] for sampling all codes: one categorical draw per position is argmax(logits + noise) */
  static gumbel(rng) {
    const g = new Float32Array(N_CODES * K);
    for (let i = 0; i < g.length; i++) g[i] = -Math.log(-Math.log(rng.uniform()));
    return g;
  }

  /** logits [128, 8192] + Gumbel noise -> codes. With the noise held fixed, a small change of the logits keeps most codes. */
  static sampleCodes(logits, noise) {
    const codes = new BigInt64Array(N_CODES);
    for (let i = 0; i < N_CODES; i++) {
      let best = -Infinity, arg = 0;
      for (let k = 0, o = i * K; k < K; k++) {
        const v = logits[o + k] + noise[o + k];
        if (v > best) { best = v; arg = k; }
      }
      codes[i] = BigInt(arg);
    }
    return codes;
  }

  /** Everything a seed decides, computed once and reused while only the prompt changes: the random state, the
   *  decision tokens' input embeddings and the sampling noise. */
  async seedCache(seed) {
    if (this._seed?.seed === seed) return this._seed;
    const rng = new Rng(seed), { state, t } = this.randomState(rng), noise = JeverationPipeline.gumbel(rng);
    const tail = await this.decisionTail(state, t);
    return (this._seed = { seed, state, t, noise, tail });
  }

  /** the backbone pass and the image head: (ids, state, t) -> logits Float32Array [128*8192] */
  async logits(ids, state, t, timings = {}, tailCached = null) {
    const { ort, s } = this, T = (n, d, dims) => new ort.Tensor(n, d, dims);
    const t0 = performance.now();
    const emb = toF32((await s.embed.run({ input_ids: T("int64", BigInt64Array.from(ids.map(BigInt)), [1, ids.length]) })).inputs_embeds.data);
    const tail = tailCached ?? await this.decisionTail(state, t);
    const L = ids.length + N_CODES, x = new Float32Array(L * HIDDEN);
    x.set(emb, 0); x.set(tail, ids.length * HIDDEN);
    const pos = new BigInt64Array(3 * L);
    for (let a = 0; a < 3; a++) for (let i = 0; i < L; i++) pos[a * L + i] = BigInt(i);
    timings.inputs = performance.now() - t0;
    return this.backboneAndHead(x, pos, L, state, t, timings);
  }

  async decisionTail(state, t) {
    const T = (n, d, dims) => new this.ort.Tensor(n, d, dims);
    return toF32((await this.s.decisionEmbed.run({ state: T("float32", state, [1, N_CODES, CODE_DIM]), t: T("float32", t, [1]) })).tail.data);
  }

  /** x [L*2560] (the decision tokens last), rotary positions [3*L] -> logits Float32Array [128*8192] */
  async backboneAndHead(x, pos, L, state, t, timings = {}) {
    const { ort, s } = this, T = (n, d, dims) => new ort.Tensor(n, d, dims);
    if (L > this.maxLen) throw new Error(`request of ${L} tokens; this backbone takes at most ${this.maxLen}`);
    let t0 = performance.now();
    const position_ids = T("int64", pos, [3, 1, L]);
    let h = T("float32", x, [1, L, HIDDEN]);
    for (const c of s.chunks) {
      const o = await c.run({ hidden_in: h, position_ids });
      if (h.location === "gpu-buffer") h.dispose();
      h = o.hidden_out ?? o.hidden;
    }
    const hidden = h;
    timings.backbone = performance.now() - t0; t0 = performance.now();
    const lg = (await s.head.run({ hidden, state: T("float32", state, [1, N_CODES, CODE_DIM]), t: T("float32", t, [1]) })).logits;
    if (hidden.location === "gpu-buffer") hidden.dispose();
    timings.head = performance.now() - t0;
    return toF32(lg.location === "gpu-buffer" ? await lg.getData() : lg.data);
  }

  /** codes + prompt -> RGB uint8 [512*512*3] */
  async decode(codes, prompt, timings = {}, source = null) {
    const { ort, s } = this;
    let t0 = performance.now();
    const tg = (await s.clip.run({ clip_ids: new ort.Tensor("int64", this.clipIds(prompt), [1, CLIP_LEN]) })).text_guidance;
    const feeds = { codes: new ort.Tensor("int64", codes, [1, N_CODES]), text_guidance: tg };
    if (source) {                                    // image-to-image: the source picture (planar, [0, 1]) and its task id
      const hw = 512 * 512, src = new Float32Array(3 * hw);
      for (let c = 0; c < 3; c++) for (let i = 0; i < hw; i++) src[c * hw + i] = source.rgb[i * 3 + c] / 255;
      feeds.source = new ort.Tensor("float32", src, [1, 3, 512, 512]);
      feeds.task = new ort.Tensor("int64", BigInt64Array.from([BigInt(source.task)]), [1]);
    }
    const img = (await (source ? s.sourceDecoder : s.decoder).run(feeds)).image.data;
    timings.decode = performance.now() - t0;
    const hw = 512 * 512, rgb = new Uint8Array(hw * 3);
    for (let c = 0; c < 3; c++) for (let i = 0; i < hw; i++) rgb[i * 3 + c] = Math.round(Math.min(1, Math.max(0, img[c * hw + i])) * 255);
    return rgb;
  }

  /** prompt -> {rgb, codes, timings}; one backbone pass. Same seed = same random state and sampling noise, so editing
   *  the prompt changes the image smoothly instead of re-rolling it. */
  async generate(prompt, { seed = 0 } = {}) {
    const timings = {};
    const t0 = performance.now();
    const c = await this.seedCache(seed);
    timings.seed = performance.now() - t0;
    const logits = await this.logits(this.promptIds(prompt), c.state, c.t, timings, c.tail);
    let t1 = performance.now();
    const codes = JeverationPipeline.sampleCodes(logits, c.noise);
    timings.sample = performance.now() - t1;
    const rgb = await this.decode(codes, prompt, timings);
    timings.total = performance.now() - t0;
    return { rgb, codes, timings };
  }

  // ---- image-to-image ------------------------------------------------------------------------------------------------------
  /** RGB uint8 [512*512*3] -> grey (BT.601 luma in all three channels), the colorize task's input */
  static toGray(rgb) {
    const out = new Uint8Array(rgb.length);
    for (let i = 0; i < rgb.length; i += 3) {
      const y = Math.min(255, Math.max(0, Math.round(0.299 * rgb[i] + 0.587 * rgb[i + 1] + 0.114 * rgb[i + 2])));
      out[i] = out[i + 1] = out[i + 2] = y;
    }
    return out;
  }

  /** RGB uint8 [512*512*3] -> the vision tower's patches [1024, 1536] (Qwen-VL order: 2x2 merge blocks, channel, 2 frames, 16x16) */
  static patchify(rgb, size = 512) {
    const p = 16, m = 2, tp = 2, g = size / p, row = 3 * tp * p * p, out = new Float32Array(g * g * row);
    let r = 0;
    for (let bh = 0; bh < g / m; bh++) for (let bw = 0; bw < g / m; bw++) for (let mh = 0; mh < m; mh++) for (let mw = 0; mw < m; mw++, r++) {
      const y0 = (bh * m + mh) * p, x0 = (bw * m + mw) * p;
      for (let c = 0; c < 3; c++) for (let f = 0; f < tp; f++) for (let py = 0; py < p; py++) for (let px = 0; px < p; px++)
        out[r * row + ((c * tp + f) * p + py) * p + px] = rgb[((y0 + py) * size + x0 + px) * 3 + c] / 127.5 - 1;
    }
    return out;
  }

  /** RGB uint8 [512*512*3] -> visual tokens Float32Array [256*2560]; the last picture's tokens are kept for reuse */
  async visionTokens(rgb, timings = {}) {
    if (this._vis?.rgb === rgb) { timings.vision = 0; return this._vis.vis; }
    const t0 = performance.now(), g = 512 / 16;
    const o = await this.s.vision.run({ pixel_values: new this.ort.Tensor("float32", JeverationPipeline.patchify(rgb), [g * g, 1536]),
                                        image_grid_thw: new this.ort.Tensor("int64", BigInt64Array.from([1n, BigInt(g), BigInt(g)]), [1, 3]) });
    const vis = toF32(o.image_features.data);
    timings.vision = performance.now() - t0;
    this._vis = { rgb, vis };
    return vis;
  }

  /** a task (a style, or "colorize") -> [instruction the backbone reads, text the decoder reads, decoder task id] */
  i2iTexts(task) {
    const tp = this.i2iTpl;
    if (task in tp.style) return [tp.style_prefix + tp.style[task], tp.style[task], tp.decoder_task_id[task]];
    if (task === "colorize") return [tp.colorize, tp.colorize, tp.decoder_task_id.colorize];
    throw new Error("unknown image-to-image task " + task);
  }

  /** photo RGB uint8 [512*512*3] (already 512 x 512) + task -> {rgb, codes, timings}. One backbone pass after the picture's
   *  visual tokens: [chat head] [image] [end of vision] instruction [chat tail] [128 decision tokens]. */
  async imageToImage(photo, task, { seed = 0, debug = null } = {}) {
    const timings = {}, t0 = performance.now();
    const src = task === "colorize" ? (this._gray?.photo === photo ? this._gray.gray : (this._gray = { photo, gray: JeverationPipeline.toGray(photo) }).gray) : photo;
    const c = await this.seedCache(seed);
    timings.seed = performance.now() - t0;
    const vis = await this.visionTokens(src, timings);
    let t1 = performance.now();
    const [instr, decText, taskId] = this.i2iTexts(task), tp = this.i2iTpl;
    const ins = this.qwenTok.encode(instr, { add_special_tokens: false }).ids.slice(0, this.tpl.max_prompt_tokens);
    const textIds = [...tp.head_ids, ...tp.mid_ids, ...ins, ...tp.tail_ids];
    const T = (n, d, dims) => new this.ort.Tensor(n, d, dims);
    const emb = toF32((await this.s.embed.run({ input_ids: T("int64", BigInt64Array.from(textIds.map(BigInt)), [1, textIds.length]) })).inputs_embeds.data);
    const nh = tp.head_ids.length, nv = vis.length / HIDDEN, na = textIds.length - nh, g = Math.sqrt(nv);
    const L = nh + nv + na + N_CODES, x = new Float32Array(L * HIDDEN), pos = new BigInt64Array(3 * L);
    x.set(emb.subarray(0, nh * HIDDEN), 0);
    x.set(vis, nh * HIDDEN);
    x.set(emb.subarray(nh * HIDDEN), (nh + nv) * HIDDEN);
    x.set(c.tail, (nh + nv + na) * HIDDEN);
    const P = (a, i, v) => { pos[a * L + i] = BigInt(v); };
    for (let i = 0; i < nh; i++) for (let a = 0; a < 3; a++) P(a, i, i);                     // text before the image
    for (let k = 0; k < nv; k++) { P(0, nh + k, nh); P(1, nh + k, nh + Math.floor(k / g)); P(2, nh + k, nh + (k % g)); }
    const after = nh + g;                                                                  // text after the image
    for (let i = 0; i < na; i++) for (let a = 0; a < 3; a++) P(a, nh + nv + i, after + i);
    for (let i = 0; i < N_CODES; i++) for (let a = 0; a < 3; a++) P(a, nh + nv + na + i, after + na + i);   // decision tokens
    timings.inputs = performance.now() - t1;
    let { state, t } = c;
    if (debug?.state) {                              // tests: the reference's random state instead of the seed's
      ({ state, t } = debug); x.set(await this.decisionTail(state, t), (nh + nv + na) * HIDDEN);
    }
    const logits = await this.backboneAndHead(x, pos, L, state, t, timings);
    if (debug) Object.assign(debug, { x, pos, L, logits });
    t1 = performance.now();
    const codes = JeverationPipeline.sampleCodes(logits, c.noise);
    timings.sample = performance.now() - t1;
    const rgb = await this.decode(codes, decText, timings, { rgb: src, task: taskId });
    timings.total = performance.now() - t0;
    return { rgb, codes, timings, length: L };
  }
}

function toF32(d) {
  if (d instanceof Float32Array) return d;
  if (d instanceof Uint16Array) { const o = new Float32Array(d.length); for (let i = 0; i < d.length; i++) o[i] = half(d[i]); return o; }
  return Float32Array.from(d);
}
function half(h) {
  const s = h & 0x8000 ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff;
  if (e === 0) return s * 2 ** -14 * (f / 1024);
  if (e === 31) return f ? NaN : s * Infinity;
  return s * 2 ** (e - 15) * (1 + f / 1024);
}