// Rectified-flow sampling from t = 1 (noise) to t = 0, following ThalisAI/solstice-80m generate.py and the // Nyx-2 space: Euler or Heun (the last Heun step is Euler), classifier-free guidance on t <= 0.75 for teachers // (cond and uncond in one 2N batch), guidance as input `w` for distilled students, and for a self-conditioning // model the previous evaluation's x0 estimate (x - t * v).clamp(-1, 1) from the guided velocity. // // Environment-agnostic: pass the ort namespace (onnxruntime-web or onnxruntime-node) as `ort`. const PIX = 4 * 32 * 32; // mulberry32 + Box-Muller: the same seed gives the same noise for every row of a sweep export function noise(seed, n = PIX) { let a = seed >>> 0; const rand = () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const out = new Float32Array(n); for (let i = 0; i < n; i += 2) { let u1 = 0; while (u1 <= 1e-12) u1 = rand(); const u2 = rand(); const r = Math.sqrt(-2 * Math.log(u1)); out[i] = r * Math.cos(2 * Math.PI * u2); if (i + 1 < n) out[i + 1] = r * Math.sin(2 * Math.PI * u2); } return out; } export class Runner { // model: a models.js entry; session: ort.InferenceSession; backend: 'webgpu' | 'wasm' | 'cpu' constructor(ort, session, model, backend, { constTensor = null, L, D } = {}) { this.ort = ort; this.session = session; this.model = model; this.backend = backend; this.L = L; this.D = D; this.constTensor = constTensor || (async (_b, data, dims, type = 'float32') => new ort.Tensor(type, data, dims)); this.inputs = new Set(session.inputNames); this.guided = this.inputs.has('w'); this.selfCond = this.inputs.has('sc'); this.names = model.io === 'nyx' ? { pool: 'text_pool', tokens: 'text_tokens', mask: 'text_mask', out: 'v_pred' } : { pool: 'pool', tokens: 'tokens', mask: 'mask', out: 'v' }; this.extraFeeds = {}; // LoRA inputs this.hasLora = [...this.inputs].some((n) => n.startsWith('lora_')); } setExtraFeeds(feeds) { for (const t of Object.values(this.extraFeeds)) if (t.dispose && t.location === 'gpu-buffer') t.dispose(); this.extraFeeds = feeds; } // Pack conditionings into constant text tensors (on the GPU under WebGPU). async pack(conds) { const { L, D } = this; const N = conds.length; const tokens = new Float32Array(N * L * D); const pool = new Float32Array(N * D); const mask = new Uint8Array(N * L); conds.forEach((c, i) => { const t = c.tokens; tokens.set(t.data.subarray(t.offset, t.offset + L * D), i * L * D); pool.set(c.pool.data.subarray(c.pool.offset, c.pool.offset + D), i * D); mask.fill(1, i * L, i * L + Math.min(L, c.len)); }); return { N, tokens: await this.constTensor(this.backend, tokens, [N, L, D]), pool: await this.constTensor(this.backend, pool, [N, D]), mask: new this.ort.Tensor('bool', mask, [N, L]), }; } dispose(packed) { for (const k of ['tokens', 'pool']) if (packed[k].location === 'gpu-buffer') packed[k].dispose(); } async forward(x, t, packed, w, sc) { const { ort } = this; const N = packed.N; const feeds = { x: new ort.Tensor('float32', x, [N, 4, 32, 32]), t: new ort.Tensor('float32', new Float32Array(N).fill(t), [N]), [this.names.pool]: packed.pool, [this.names.tokens]: packed.tokens, [this.names.mask]: packed.mask, ...this.extraFeeds, }; if (this.guided) feeds.w = new ort.Tensor('float32', new Float32Array(N).fill(w), [N]); if (this.selfCond) feeds.sc = new ort.Tensor('float32', sc || new Float32Array(N * PIX), [N, 4, 32, 32]); const out = await this.session.run(feeds, [this.names.out]); return new Float32Array(out[this.names.out].data); } } function concat(a, b) { const out = new Float32Array(a.length + b.length); out.set(a); out.set(b, a.length); return out; } // Sample one batch: conds[i] with noise from seeds[i]. onStep(step, steps, x0Estimate) after every step. export async function sampleBatch(runner, { conds, uncond, seeds, steps, sampler = 'euler', guidance = 4, onStep, signal }) { const N = conds.length; const x = new Float32Array(N * PIX); seeds.forEach((s, i) => x.set(noise(s), i * PIX)); const packed = await runner.pack(conds); const needCfg = !runner.guided && guidance !== 1; const packedCU = needCfg ? await runner.pack([...conds, ...new Array(N).fill(uncond)]) : null; let sc = null; let x0 = null; async function velocity(xs, t) { if (signal?.aborted) throw new DOMException('Cancelled', 'AbortError'); let v; if (runner.guided) { v = await runner.forward(xs, t, packed, guidance, null); } else if (!needCfg || t > 0.75 + 1e-5) { v = await runner.forward(xs, t, packed, guidance, sc); } else { const both = await runner.forward(concat(xs, xs), t, packedCU, guidance, sc ? concat(sc, sc) : null); v = new Float32Array(N * PIX); const off = N * PIX; for (let i = 0; i < v.length; i++) v[i] = both[off + i] + guidance * (both[i] - both[off + i]); } x0 = new Float32Array(xs.length); for (let i = 0; i < xs.length; i++) x0[i] = Math.min(1, Math.max(-1, xs[i] - t * v[i])); if (runner.selfCond) sc = x0; return v; } try { for (let i = 0; i < steps; i++) { const t0 = 1 - i / steps; const t1 = 1 - (i + 1) / steps; const dt = t1 - t0; let v = await velocity(x, t0); if (sampler === 'heun' && i < steps - 1) { const xe = new Float32Array(x.length); for (let k = 0; k < x.length; k++) xe[k] = x[k] + dt * v[k]; const v2 = await velocity(xe, t1); for (let k = 0; k < v.length; k++) v[k] = 0.5 * (v[k] + v2[k]); } for (let k = 0; k < x.length; k++) x[k] += dt * v[k]; if (onStep) await onStep(i + 1, steps, i === steps - 1 ? x : x0); } } finally { runner.dispose(packed); if (packedCU) runner.dispose(packedCU); } return x; } // Sample any number of items in chunks of maxBatch. items: [{ cond, seed }]. Returns Float32Array per item. export async function sampleMany(runner, items, opts) { const maxBatch = opts.maxBatch || 8; const out = []; for (let s = 0; s < items.length; s += maxBatch) { const chunk = items.slice(s, s + maxBatch); const x = await sampleBatch(runner, { ...opts, conds: chunk.map((it) => it.cond), seeds: chunk.map((it) => it.seed), onStep: opts.onStep ? (i, n, xs) => opts.onStep(s, chunk.length, i, n, xs) : null, }); for (let i = 0; i < chunk.length; i++) out.push(x.subarray(i * PIX, (i + 1) * PIX)); } return out; } // [4, 32, 32] in [-1, 1] -> RGBA bytes, binary alpha (opaque where a > 0, RGB zeroed elsewhere). export function toRGBA(x, final = true) { const plane = 32 * 32; const out = new Uint8ClampedArray(plane * 4); for (let p = 0; p < plane; p++) { const c = (k) => Math.min(1, Math.max(-1, x[k * plane + p])); const a = c(3); const opaque = a > 0; if (final && !opaque) continue; out[p * 4] = Math.round((c(0) + 1) * 127.5); out[p * 4 + 1] = Math.round((c(1) + 1) * 127.5); out[p * 4 + 2] = Math.round((c(2) + 1) * 127.5); out[p * 4 + 3] = final ? 255 : Math.round((a + 1) * 127.5); } return out; } export const PIXELS = PIX;