RD-Flow-64-WebGPU / rdflow.js
linoyts's picture
linoyts HF Staff
RD Flow 64 WebGPU demo
4173f94 verified
Raw History Blame Contribute Delete
23.2 kB
// RD Flow 64 (Retro Diffusion) in JS on ONNX Runtime: caption -> prompt reader (Qwen3-VL-4B, first 27 layers)
// -> 16 flow-matching Euler steps on the 64 x 64 pixel grid -> every pixel an exact palette colour or transparent.
// A line-by-line port of rdflow/flow.py's `sample` (palette extraction, shading ramps, pointer head, commit).
// `ort` is injected (onnxruntime-node for tests, onnxruntime-web/webgpu in the browser); `files` resolves repo paths.
import { Tokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/+esm";
const N = 64, NPIX = N * N, C = 4, D = 2560, AB_SCALE = 3, SLOTS = 256, BUCKETS = [32, 64, 128, 256];
const pad2 = (i) => String(i).padStart(2, "0");
// ---------------------------------------------------------------------------------------------------------------
// Noise: torch.randn((64, 64, 4), generator=torch.Generator().manual_seed(seed)) on the CPU (mt19937 + the 16-wide
// Box-Muller of ATen's normal_fill), so a seed draws the same picture as the Python pipeline (up to float rounding).
export function torchRandn(seed, n = NPIX * C) {
const mt = new Uint32Array(624); let idx = 624;
mt[0] = Number(BigInt.asUintN(32, BigInt(seed)));
for (let i = 1; i < 624; i++) { const p = mt[i - 1] ^ (mt[i - 1] >>> 30); mt[i] = (Math.imul(1812433253, p) + i) >>> 0; }
const next = () => {
if (idx >= 624) {
for (let i = 0; i < 624; i++) {
const y = (mt[i] & 0x80000000) | (mt[(i + 1) % 624] & 0x7fffffff);
mt[i] = mt[(i + 397) % 624] ^ (y >>> 1) ^ (y & 1 ? 0x9908b0df : 0);
}
idx = 0;
}
let y = mt[idx++];
y ^= y >>> 11; y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= y >>> 18;
return y >>> 0;
};
const d = new Float32Array(n);
for (let i = 0; i < n; i++) d[i] = (next() & 0xffffff) * 2 ** -24;
for (let i = 0; i + 16 <= n; i += 16) {
for (let j = 0; j < 8; j++) {
const u1 = 1 - d[i + j], u2 = d[i + j + 8], r = Math.sqrt(-2 * Math.log(u1)), th = 2 * Math.PI * u2;
d[i + j] = r * Math.cos(th); d[i + j + 8] = r * Math.sin(th);
}
}
return d;
}
// ---------------------------------------------------------------------------------------------------------------
// Colour: sRGB <-> OKLab, the model's value space, shading ramps (ports of flow.py, palette.py, ramps.py).
const f = Math.fround;
function oklabF32(r, g, b) { // ColourEmbed.oklab: float32 math, as torch does it
const lin = (c) => { c = f(c / 255); return c <= 0.04045 ? f(c / 12.92) : f(f((c + 0.055) / 1.055) ** 2.4); };
const R = lin(r), G = lin(g), B = lin(b);
const cb = (x) => f(Math.max(0, f(x)) ** (1 / 3));
const l = cb(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
const m = cb(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
const s = cb(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
return [f(0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s), f(1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s),
f(0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)];
}
function oklab64(r, g, b) { // palette.srgb_to_oklab: float64, then float32 out
const lin = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
const R = lin(r), G = lin(g), B = lin(b);
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
return [f(0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s), f(1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s),
f(0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)];
}
function srgbFromOklabF32(L, a, b) { // flow.oklab_to_srgb: float32 math
L = f(L); a = f(a); b = f(b);
const l = f(f(L + 0.3963377774 * a + 0.2158037573 * b) ** 3), m = f(f(L - 0.1055613458 * a - 0.0638541728 * b) ** 3);
const s = f(f(L - 0.0894841775 * a - 1.2914855480 * b) ** 3);
const lin = [f(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), f(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
f(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s)];
return lin.map((c) => {
c = Math.min(1, Math.max(0, c));
c = c <= 0.0031308 ? f(c * 12.92) : f(f(1.055 * f(Math.max(c, 1e-12) ** (1 / 2.4))) - 0.055);
return roundHalfEven(f(c * 255));
});
}
function roundHalfEven(x) { const r = Math.round(x); return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r; }
/** rdflow.ramps.ramps: palette OKLab -> (ramp id, level in 0..1). */
function ramps(lab) {
const n = lab.length, ramp = new Int32Array(n), level = new Float32Array(n).fill(0.5);
if (!n) return { ramp, level };
const TAU = 2 * Math.PI, HUE_GAP = (28 * Math.PI) / 180, HUE_SPAN = (75 * Math.PI) / 180;
const chroma = lab.map(([, a, b]) => Math.hypot(a, b)), hue = lab.map(([, a, b]) => { const h = Math.atan2(b, a) % TAU; return h < 0 ? h + TAU : h; });
const unwrap = (ids) => { const out = [hue[ids[0]]]; for (let i = 1; i < ids.length; i++) { let d = hue[ids[i]] - hue[ids[i - 1]]; const dd = ((d + Math.PI) % TAU + TAU) % TAU - Math.PI; out.push(out[i - 1] + (dd === -Math.PI && d > 0 ? Math.PI : dd)); } return out; };
const chromatic = [...Array(n).keys()].filter((i) => chroma[i] >= 0.035);
let groups = [];
if (chromatic.length) {
let order = chromatic.slice().sort((x, y) => hue[x] - hue[y]);
const h = order.map((i) => hue[i]);
let best = -1, start = 0;
for (let i = 0; i < h.length; i++) { const g = (i + 1 < h.length ? h[i + 1] : h[0] + TAU) - h[i]; if (g > best) { best = g; start = i + 1; } }
order = [...order.slice(start % order.length), ...order.slice(0, start % order.length)];
const hu = unwrap(order); let cur = [order[0]];
for (let i = 1; i < order.length; i++) { if (hu[i] - hu[i - 1] > HUE_GAP) { groups.push(cur); cur = []; } cur.push(order[i]); }
groups.push(cur);
const split = [];
for (let g of groups) {
while (g.length > 2) {
const hg = unwrap(g);
if (hg[hg.length - 1] - hg[0] <= HUE_SPAN) break;
let k = 0, bg = -Infinity; for (let i = 0; i + 1 < hg.length; i++) { const d = hg[i + 1] - hg[i]; if (d > bg) { bg = d; k = i + 1; } }
split.push(g.slice(0, k)); g = g.slice(k);
}
split.push(g);
}
groups = split;
}
const neutral = [...Array(n).keys()].filter((i) => chroma[i] < 0.035);
const all = [[0, neutral], ...groups.map((g, i) => [Math.min(i + 1, 15), g])];
for (const [rid, g] of all) {
if (!g.length) continue;
for (const i of g) ramp[i] = rid;
if (g.length > 1) {
const ord = g.slice().sort((x, y) => lab[x][0] - lab[y][0] || x - y);
ord.forEach((i, r) => { level[i] = f(r / (g.length - 1)); });
}
}
return { ramp, level };
}
/** flow.extract_palette: one image's model-space guess [4096*4] -> sorted unique sRGB colours [[r,g,b], ...]. */
export function extractPalette(x, { maxColours = 64, merge = 0.05, bin = 0.015, iters = 4 } = {}) {
const pts = [];
for (let p = 0; p < NPIX; p++) {
if (!(x[p * 4 + 3] > 0)) continue;
pts.push([(f(x[p * 4]) + 1) / 2, f(x[p * 4 + 1]) / AB_SCALE, f(x[p * 4 + 2]) / AB_SCALE].map((v) => f(v)));
}
if (!pts.length) return [];
const bins = new Map();
for (const q of pts) {
const k = q.map((v) => roundHalfEven(v / bin)), key = k.join(",");
let e = bins.get(key); if (!e) { e = { k, n: 0, s: [0, 0, 0] }; bins.set(key, e); }
e.n++; for (let j = 0; j < 3; j++) e.s[j] += q[j];
}
const keys = [...bins.values()].sort((a, b) => a.k[0] - b.k[0] || a.k[1] - b.k[1] || a.k[2] - b.k[2]); // np.unique order
const order = keys.map((e, i) => i).sort((i, j) => keys[j].n - keys[i].n || i - j); // stable argsort(-counts)
let cen = [];
for (const i of order) {
const c = keys[i].s.map((v) => v / keys[i].n);
if (!cen.length || Math.min(...cen.map((o) => Math.hypot(o[0] - c[0], o[1] - c[1], o[2] - c[2]))) > merge) {
cen.push(c); if (cen.length >= maxColours) break;
}
}
for (let it = 0; it < iters; it++) {
const sum = cen.map(() => [0, 0, 0]), cnt = new Array(cen.length).fill(0);
for (const q of pts) {
let bi = 0, bd = Infinity;
for (let k = 0; k < cen.length; k++) { const d = (q[0] - cen[k][0]) ** 2 + (q[1] - cen[k][1]) ** 2 + (q[2] - cen[k][2]) ** 2; if (d < bd) { bd = d; bi = k; } }
cnt[bi]++; for (let j = 0; j < 3; j++) sum[bi][j] += q[j];
}
cen = cen.map((_, k) => (cnt[k] ? sum[k].map((v) => v / cnt[k]) : null)).filter(Boolean);
}
const rgb = cen.map((c) => srgbFromOklabF32(...c));
const uniq = [...new Map(rgb.map((c) => [c.join(","), c])).values()];
return uniq.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
}
/** flow.palette_dict + palette_model_space for B images (lists of [r,g,b]), padded to `P` slots. */
function paletteTensors(lists, P) {
const B = lists.length, rgb = new BigInt64Array(B * P * 3), ramp = new BigInt64Array(B * P), level = new Float32Array(B * P).fill(0.5);
const valid = new Uint8Array(B * P), X = new Float32Array(B * (1 + P) * 4);
lists.forEach((cols, b) => {
cols = cols.slice(0, SLOTS);
const rl = ramps(cols.map((c) => oklab64(...c)));
X.set([0, 0, 0, -1], b * (1 + P) * 4);
cols.forEach((c, s) => {
const o = b * P + s;
for (let j = 0; j < 3; j++) rgb[o * 3 + j] = BigInt(c[j]);
valid[o] = 1; ramp[o] = BigInt(rl.ramp[s]); level[o] = rl.level[s];
const [L, a, bb] = oklabF32(...c);
X.set([f(2 * L - 1), f(a * AB_SCALE), f(bb * AB_SCALE), 1], (b * (1 + P) + 1 + s) * 4);
});
});
return { rgb, ramp, level, valid, X, P, lists };
}
/** RGBA bytes [64*64*4] from a palette and pointer tokens (0 transparent, 1 + s slot s). */
export function decode(colours, tokens) {
const out = new Uint8ClampedArray(NPIX * 4);
for (let p = 0; p < NPIX; p++) {
const t = tokens[p]; if (!t) continue;
const c = colours[t - 1]; out[p * 4] = c[0]; out[p * 4 + 1] = c[1]; out[p * 4 + 2] = c[2]; out[p * 4 + 3] = 255;
}
return out;
}
function bf16Round(src) {
const out = new Float32Array(src.length), fl = new Float32Array(1), u = new Uint32Array(fl.buffer);
for (let i = 0; i < src.length; i++) { fl[0] = src[i]; const x = u[0]; u[0] = (x + 0x7fff + ((x >>> 16) & 1)) & 0xffff0000; out[i] = fl[0]; }
return out;
}
function toHalf(src) {
const out = new Uint16Array(src.length), fl = new Float32Array(1), u = new Uint32Array(fl.buffer);
for (let i = 0; i < src.length; i++) {
fl[0] = src[i]; const x = u[0], sign = (x >>> 16) & 0x8000; let e = ((x >>> 23) & 0xff) - 112, m = x & 0x7fffff;
if (e <= 0) { if (e < -10) { out[i] = sign; continue; } m |= 0x800000; const sh = 14 - e; let h = m >> sh; const r = m & ((1 << sh) - 1), hf = 1 << (sh - 1); if (r > hf || (r === hf && (h & 1))) h++; out[i] = sign | h; continue; }
if (e >= 31) { out[i] = sign | 0x7c00 | (((x >>> 23) & 0xff) === 0xff && m ? 0x200 : 0); continue; }
let h = sign | (e << 10) | (m >> 13); const r = m & 0x1fff; if (r > 0x1000 || (r === 0x1000 && (h & 1))) h++; out[i] = h;
}
return out;
}
function readF32(t) {
const d = t.data;
if (d instanceof Float32Array) return d;
if (d instanceof Uint16Array) { const o = new Float32Array(d.length); for (let i = 0; i < d.length; i++) { const h = d[i], s = h & 0x8000 ? -1 : 1, e = (h >> 10) & 31, m = h & 1023; o[i] = e === 0 ? s * m * 2 ** -24 : e === 31 ? (m ? NaN : s * Infinity) : s * (1 + m / 1024) * 2 ** (e - 15); } return o; }
return Float32Array.from(d);
}
// ---------------------------------------------------------------------------------------------------------------
export class RDFlowPipeline {
/**
* @param files {json(path), bytes(path, onProgress), path?(path)}
* @param opts {ort, device: "webgpu"|"cpu", progress?(e), components?: ("text"|"flow")[]}
*/
static async load(files, { ort, device = "webgpu", progress, components = ["text", "flow"] } = {}) {
const p = new RDFlowPipeline();
p.ort = ort; p.device = device; p.files = files; p.progress = progress;
p.config = await files.json("onnx/config.json");
p.tok = new Tokenizer(await files.json("text_encoder/tokenizer.json"), await files.json("text_encoder/tokenizer_config.json"));
await p.loadComponents(components);
return p;
}
async session(path, { gpuOut = false, external = true } = {}) {
const { ort, files, device, progress } = this;
const opts = { executionProviders: [device === "webgpu" ? "webgpu" : "cpu"], graphOptimizationLevel: "all" };
if (device === "webgpu" && gpuOut) opts.preferredOutputLocation = "gpu-buffer";
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 });
if (external) opts.externalData = [{ path: path.split("/").pop() + "_data", data: await files.bytes(path + "_data", onP) }];
return ort.InferenceSession.create(await files.bytes(path, onP), opts);
}
async loadComponents(components) {
const c = this.config;
if (components.includes("text") && !this.te) {
const t = c.text_encoder, te = { embed: await this.session(`onnx/${t.embed}`), layers: [] };
for (let i = 0; i < t.layers; i++) te.layers.push(await this.session(`onnx/${t.layer.replace("{i}", pad2(i))}`, { gpuOut: true }));
te.norm = await this.session(`onnx/${t.norm}`, { external: false });
this.te = te;
}
if (components.includes("flow") && !this.flow) this.flow = await this.session(`onnx/${c.flow.file}`, { external: c.flow.external_data !== false });
}
/** Release the prompt reader's sessions (GPU memory); `encode` reloads them from the browser cache. */
async unloadText() { if (!this.te) return; for (const s of [this.te.embed, ...this.te.layers, this.te.norm]) await s.release?.(); this.te = null; }
/** caption -> token ids exactly as the reference: raw text, no chat template, no special tokens, at most 512. */
ids(caption) { return this.tok.encode(caption, { add_special_tokens: false }).ids.slice(0, this.config.text_encoder.max_len); }
/** caption -> {data: Float32Array [L*2560] (bf16-rounded, what the drawing model sees), L} */
async encode(caption) {
if (!this.te) await this.loadComponents(["text"]);
const { ort } = this, ids = this.ids(caption), L = Math.max(1, ids.length), t = this.config.text_encoder;
if (!ids.length) ids.push(this.tok.encode(" ", { add_special_tokens: false }).ids[0] ?? 220);
const half = 64, cos = new Float32Array(L * half), sin = new Float32Array(L * half);
for (let j = 0; j < half; j++) {
const inv = 1 / t.rope_theta ** ((2 * j) / 128);
for (let p = 0; p < L; p++) { const a = f(p * inv); cos[p * half + j] = Math.cos(a); sin[p * half + j] = Math.sin(a); }
}
const bias = new Float32Array(L * L); for (let i = 0; i < L; i++) for (let j = i + 1; j < L; j++) bias[i * L + j] = -Infinity;
const feeds = { rope_cos: new ort.Tensor("float32", cos, [L, half]), rope_sin: new ort.Tensor("float32", sin, [L, half]),
attention_bias: new ort.Tensor("float16", toHalf(bias), [L, L]) };
let x = (await this.te.embed.run({ input_ids: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, L]) })).inputs_embeds;
for (const layer of this.te.layers) {
const out = (await layer.run({ hidden_states: x, ...feeds })).out_hidden_states;
if (x.location === "gpu-buffer") x.dispose();
x = out;
}
const y = (await this.te.norm.run({ hidden_states: x })).features;
if (x.location === "gpu-buffer") x.dispose();
return { data: bf16Round(readF32(y)), L };
}
/** One drawing-model call: B rows (cond and/or uncond). Returns {xh: Float32Array [B*4096*4], lg: Float32Array [B*4096*(1+P)]} */
async model(rows, t, pal, sc) {
const { ort } = this, B = rows.length, L = rows[0].L, P = pal ? pal.P : 1;
const x = new Float32Array(B * NPIX * C), text = new Float32Array(B * L * D), mask = new Uint8Array(B * L), bg = new BigInt64Array(B);
const scA = new Float32Array(B * NPIX * C), tt = new Float32Array(B).fill(t);
rows.forEach((r, b) => {
x.set(r.x, b * NPIX * C); bg[b] = BigInt(r.bg);
if (r.text) { text.set(r.text, b * L * D); mask.fill(1, b * L, (b + 1) * L); }
if (sc) scA.set(r.sc, b * NPIX * C);
});
const rep = (arr, per) => { const o = new arr.constructor(B * per); rows.forEach((r, b) => o.set(arr.subarray(r.img * per, (r.img + 1) * per), b * per)); return o; };
const feeds = {
x_t: new ort.Tensor("float32", x, [B, N, N, C]), t: new ort.Tensor("float32", tt, [B]),
text: new ort.Tensor("float32", text, [B, L, D]), text_mask: new ort.Tensor("bool", mask, [B, L]),
pal_rgb: new ort.Tensor("int64", pal ? rep(pal.rgb, P * 3) : new BigInt64Array(B * 3), [B, P, 3]),
pal_ramp: new ort.Tensor("int64", pal ? rep(pal.ramp, P) : new BigInt64Array(B), [B, P]),
pal_level: new ort.Tensor("float32", pal ? rep(pal.level, P) : new Float32Array(B).fill(0.5), [B, P]),
pal_valid: new ort.Tensor("bool", pal ? rep(pal.valid, P) : new Uint8Array(B), [B, P]),
sc: new ort.Tensor("float32", scA, [B, N, N, C]), bg: new ort.Tensor("int64", bg, [B]),
};
const out = await this.flow.run(feeds);
return { xh: readF32(out.x_hat), lg: readF32(out.logits), P };
}
/**
* flow.sample for n images of one caption.
* @param {{feats:{data,L}, seeds:number[], transparent?:boolean, steps?:number, guidance?:number, noise?:Float32Array[],
* lockPalette?: number[][], onStep?:(i,n,preview)=>void, shouldStop?:()=>boolean}} o
* @returns {{images: Uint8ClampedArray[], palettes: number[][][], tokens: Uint8Array[]}|null} null when stopped early
*/
async sample({ feats, seeds, transparent = true, steps = 16, guidance = 4.0, noise, lockPalette, onStep, shouldStop,
interval = [0, 0.9], shift = 3, paletteAt = 0.6, maxColours = 64, merge = 0.05, pointerFrom = 0.35,
commitFrom = 0.55, commitThresh = 0.9 }) {
const n = seeds.length, S = NPIX * C;
const xs = (noise ?? seeds.map((s) => torchRandn(s))).map((a) => Float32Array.from(a));
const lin = new Float32Array(steps + 1);
{ const step = f(1 / steps), half = Math.floor((steps + 1) / 2); for (let i = 0; i <= steps; i++) lin[i] = i < half ? f(step * i) : f(1 - f(step * (steps - i))); }
const ts = lin.map((t) => f(t / f(t + f(shift * f(1 - t)))));
const bg = transparent ? 2 : 1;
let pal = lockPalette?.length ? this.bucket(paletteTensors(seeds.map(() => lockPalette), SLOTS)) : null;
let xhat = null, sc = null, probs = null;
for (let i = 0; i < steps; i++) {
const t = ts[i], t2 = ts[i + 1];
if (!pal && t >= paletteAt && xhat) pal = this.bucket(paletteTensors(xhat.map((x) => extractPalette(x, { maxColours, merge })), SLOTS));
const guide = guidance !== 1 && interval[0] <= t && t <= interval[1];
const rows = [];
for (let b = 0; b < n; b++) rows.push({ img: b, x: xs[b], text: feats.data, L: feats.L, bg, sc: sc?.[b] });
if (guide) for (let b = 0; b < n; b++) rows.push({ img: b, x: xs[b], text: null, L: feats.L, bg, sc: sc?.[b] });
const { xh, lg, P } = await this.model(rows, t, pal, sc);
xhat = [];
for (let b = 0; b < n; b++) {
const c = xh.subarray(b * S, (b + 1) * S), o = new Float32Array(S);
if (guide) { const u = xh.subarray((n + b) * S, (n + b + 1) * S); for (let k = 0; k < S; k++) o[k] = f(u[k] + f(guidance * f(c[k] - u[k]))); }
else o.set(c);
xhat.push(o);
}
if (pal && t >= pointerFrom) {
probs = [];
for (let b = 0; b < n; b++) {
const ex = (row) => this.expected(lg, row, P, pal, b);
const { p, xp } = ex(b);
if (guide) { const { xp: xpu } = ex(n + b); for (let k = 0; k < S; k++) xp[k] = f(xpu[k] + f(guidance * f(xp[k] - xpu[k]))); }
if (t >= commitFrom) {
const K = 1 + P, X = pal.X.subarray(b * K * 4, (b + 1) * K * 4);
for (let q = 0; q < NPIX; q++) {
let bi = 0, bv = -1; for (let k = 0; k < K; k++) if (p[q * K + k] > bv) { bv = p[q * K + k]; bi = k; }
if (bv >= commitThresh) for (let j = 0; j < 4; j++) xp[q * 4 + j] = X[bi * 4 + j];
}
}
probs.push(p); xhat[b] = xp;
}
}
sc = xhat;
const dt = f(t2 - t), den = Math.max(f(1 - t), 1e-4);
for (let b = 0; b < n; b++) { const x = xs[b], h = xhat[b]; for (let k = 0; k < S; k++) x[k] = f(x[k] + f(f(dt * f(h[k] - x[k])) / den)); }
onStep?.(i + 1, steps, xhat);
if (i + 1 < steps && shouldStop?.()) return null; // a newer request is waiting: drop this one
}
if (!pal) pal = this.bucket(paletteTensors(xhat.map((x) => extractPalette(x, { maxColours, merge })), SLOTS));
const K = 1 + pal.P, tokens = probs.map((p) => {
const tk = new Uint8Array(NPIX);
for (let q = 0; q < NPIX; q++) { let bi = 0, bv = -1; for (let k = 0; k < K; k++) if (p[q * K + k] > bv) { bv = p[q * K + k]; bi = k; } tk[q] = bi; }
return tk;
});
return { images: tokens.map((tk, b) => decode(pal.lists[b], tk)), palettes: pal.lists, tokens };
}
/** bucket_palette: cut the 256 slots to the smallest bucket holding every image's colours (X keeps 1+P rows). */
bucket(full) {
const B = full.lists.length, need = Math.max(...full.lists.map((l) => Math.min(l.length, SLOTS)));
if (!need) return null;
const P = BUCKETS.find((b) => b >= need) ?? SLOTS, cut = (arr, per, newPer) => {
const o = new arr.constructor(B * newPer); for (let b = 0; b < B; b++) o.set(arr.subarray(b * per, b * per + newPer), b * newPer); return o;
};
return { rgb: cut(full.rgb, SLOTS * 3, P * 3), ramp: cut(full.ramp, SLOTS, P), level: cut(full.level, SLOTS, P), valid: cut(full.valid, SLOTS, P),
X: cut(full.X, (1 + SLOTS) * 4, (1 + P) * 4), P, lists: full.lists };
}
/** softmax over (transparent, valid slots) of one logits row-block, and the expected model-space value p @ Xpal. */
expected(lg, row, P, pal, b) {
const K = 1 + P, p = new Float32Array(NPIX * K), xp = new Float32Array(NPIX * 4), base = row * NPIX * K;
const X = pal.X.subarray(b * K * 4, (b + 1) * K * 4), valid = pal.valid.subarray(b * P, (b + 1) * P), any = valid.some((v) => v);
for (let q = 0; q < NPIX; q++) {
let mx = lg[base + q * K];
for (let k = 1; k < K; k++) if (any && valid[k - 1] && lg[base + q * K + k] > mx) mx = lg[base + q * K + k];
let s = 0;
for (let k = 0; k < K; k++) { const ok = k === 0 || (any && valid[k - 1]); const e = ok ? Math.exp(lg[base + q * K + k] - mx) : 0; p[q * K + k] = e; s += e; }
for (let k = 0; k < K; k++) {
const v = f(p[q * K + k] / s); p[q * K + k] = v;
if (v) for (let j = 0; j < 4; j++) xp[q * 4 + j] += v * X[k * 4 + j];
}
}
return { p, xp };
}
}