linoyts's picture
linoyts HF Staff
Point at linoyts/Qwen-Image-2.1-int4-ONNX; cache weights by SHA-256 (adopts existing cached copies)
f916d7c verified
Raw History Blame Contribute Delete
13.4 kB
// P-JiT 21K text-to-image (Linum-AI/pjit-21k), mirroring the official sampler (pjit_21k/sampler.py): pixel space,
// x-prediction, 50 Euler steps over uniform timesteps, adaptive projected guidance against an empty negative prompt.
// Graph layout and I/O are documented in the model repo's transformer/config.json and text_encoder/config.json.
import { Tokenizer } from "@huggingface/tokenizers";
import { FlowMatchEulerDiscreteScheduler } from "../schedulers/flow_match_euler_discrete.js";
import { AdaptiveProjectedGuidance } from "../guiders/adaptive_projected_guidance.js";
import { Callable } from "../callable.js";
import { createSession, f16, f32, halfBits, persistent, readFloat, release } from "../runtime.js";
import { bf16Round, linspaceF32, randn } from "../utils.js";
const pad2 = (i) => String(i).padStart(2, "0");
export class PJiTPipeline extends Callable {
/**
* @param {import("../hub.js").HubFiles|import("../hub.js").LocalFiles} files where the model repo lives
* @param {{ort:any, device?:"webgpu"|"cpu", progress_callback?:(e:object)=>void, components?:("text_encoder"|"transformer")[]}} opts
*/
static async from_pretrained(files, { ort, device = "webgpu", progress_callback, components } = {}) {
const p = new PJiTPipeline();
p.ort = ort; p.device = device; p.files = files;
p.index = await files.json("model_index.json");
p.defaults = p.index.diffusers_js.defaults;
p.scheduler = FlowMatchEulerDiscreteScheduler.from_config(await files.json("scheduler/scheduler_config.json"));
p.guider = AdaptiveProjectedGuidance.from_config(await files.json("guider/guider_config.json"));
p.te_config = await files.json("text_encoder/config.json");
p.dit_config = await files.json("transformer/config.json");
p.tokenizer = new Tokenizer(await files.json("tokenizer/tokenizer.json"), await files.json("tokenizer/tokenizer_config.json"));
await p.load(components ?? ["text_encoder", "transformer"], progress_callback);
return p;
}
/** Create the sessions of the given components (already loaded ones are skipped). */
async load(components, progress_callback) {
const { ort, files, device } = this;
const S = (component, file, opt) => createSession(ort, files, `${component}/onnx/${file}`, { device, progress_callback, ...opt });
const gpu = { keepOutputsOnGpu: true, externalData: true };
const tg = this.te_config.diffusers_js.graphs, dg = this.dit_config.diffusers_js.graphs;
for (const c of components) {
if (c === "text_encoder" && !this.te) {
this.te = { embed: await S("text_encoder", tg.embed_tokens.file, { externalData: true }),
model: await S("text_encoder", tg.model.file, { externalData: tg.model.external_data_chunks }) };
} else if (c === "transformer" && !this.dit) {
const d = { patch_embed: await S("transformer", dg.patch_embed.file), time_embed: await S("transformer", dg.time_embed.file),
text_proj: await S("transformer", dg.text_proj.file, { externalData: true }), head: await S("transformer", dg.head.file),
image_refiner: [], text_refiner: [], blocks: [] };
const block = (pattern, i) => S("transformer", pattern.replace("{index:02d}", pad2(i)), gpu);
for (let i = 0; i < dg.image_refiner.count; i++) d.image_refiner.push(await block(dg.image_refiner.file, i));
for (let i = 0; i < dg.text_refiner.count; i++) d.text_refiner.push(await block(dg.text_refiner.file, i));
for (let i = 0; i < dg.block.count; i++) d.blocks.push(await block(dg.block.file, i));
this.dit = d;
}
}
}
/**
* Caption -> features [1, L, 7680] (fp16 bits): Qwen3.5-4B hidden states of layers 7, 15 and 27, concatenated, exactly
* what the official QwenTextEncoder returns (chat template, no padding).
*/
async encode_prompt(prompt) {
const { ort } = this; const cfg = this.te_config.diffusers_js;
let ids = this.tokenizer.encode(cfg.prompt_template.replace("{}", prompt)).ids;
if (ids.length > cfg.max_length) ids = ids.slice(0, cfg.max_length);
const L = ids.length, D = cfg.hidden_size, layers = cfg.output_names;
const emb = (await this.te.embed.run({ input_ids: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, L]) })).inputs_embeds;
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);
const feeds = { inputs_embeds: emb, attention_mask: new ort.Tensor("int64", new BigInt64Array(L).fill(1n), [1, L]),
position_ids: new ort.Tensor("int64", pos, [3, 1, L]) };
for (const [name, dims] of Object.entries(cfg.empty_state_inputs)) { // prefill: empty recurrent/conv state, no KV
const shape = dims.map((d) => (d === "batch" ? 1 : d)), n = shape.reduce((a, b) => a * b, 1);
feeds[name] = f16(ort, new Uint16Array(n), shape);
}
const out = await this.te.model.run(feeds);
const parts = layers.map((n) => halfBits(out[n])), data = new Uint16Array(L * D * layers.length);
for (let t = 0; t < L; t++) parts.forEach((p, k) => data.set(p.subarray(t * D, (t + 1) * D), (t * layers.length + k) * D));
return { data, dims: [1, L, D * layers.length] };
}
/**
* @param {{prompt?:string, negative_prompt?:string, prompt_embeds?:{data:Uint16Array,dims:number[]},
* negative_prompt_embeds?:{data:Uint16Array,dims:number[]}, width?:number, height?:number,
* num_inference_steps?:number, guidance_scale?:number, seed?:number, latents?:Float32Array,
* callback_on_step_end?:(i:number, n:number)=>void}} opts
* `latents` is the initial noise already scaled (the official sampler draws N(0,1) * noise_scale).
* @returns {Promise<{images:{data:Uint8ClampedArray,width:number,height:number}[], latents:Float32Array}>}
*/
async _call({ prompt, negative_prompt, prompt_embeds, negative_prompt_embeds, width, height, num_inference_steps,
guidance_scale, seed = 0, latents, callback_on_step_end, output_type = "rgba" } = {}) {
const { ort } = this; const d = this.defaults;
width ??= d.width; height ??= d.height; num_inference_steps ??= d.num_inference_steps;
const P = this.dit_config.diffusers_js.patch_size;
if (width % P || height % P) throw new Error(`width and height must be multiples of ${P}`);
prompt_embeds ??= await this.encode_prompt(prompt);
negative_prompt_embeds ??= await this.encode_prompt(negative_prompt ?? d.negative_prompt);
const guider = AdaptiveProjectedGuidance.from_config({ ...this.guider.config, ...(guidance_scale != null && { guidance_scale }) });
// timesteps exactly as the official sampler computes them (float32 linspace; integer timestep = trunc(t * 1000))
const ts = linspaceF32(1, 0, num_inference_steps + 1);
this.scheduler.set_timesteps({ sigmas: Array.from(ts.subarray(0, num_inference_steps)) });
const N = 3 * height * width;
const x = latents ? Float32Array.from(latents) : scaleInPlace(randn(N, seed), d.noise_scale);
const hp = height / P, wp = width / P, Li = hp * wp;
const keep = (t) => persistent(ort, this.device, t);
const text = [prompt_embeds, negative_prompt_embeds].map((e) => this.dit.text_proj.run({ text: f16(ort, e.data, e.dims) }));
const textTokens = await Promise.all(text.map(async (r) => (await r).text_tokens));
const rope = this.dit_config.diffusers_js.rope;
const imgRope = ropeTables(hp, wp, 0, rope);
const imgCos = await keep(f32(ort, imgRope.cos, [Li, 64])), imgSin = await keep(f32(ort, imgRope.sin, [Li, 64]));
const branches = [];
for (const tt of textTokens) {
const Lt = tt.dims[1], r = ropeTables(hp, wp, Lt, rope);
branches.push({ tokens: tt, Lt, txtCos: await keep(f32(ort, new Float32Array(Lt * 64).fill(1), [Lt, 64])),
txtSin: await keep(f32(ort, new Float32Array(Lt * 64), [Lt, 64])),
cos: await keep(f32(ort, r.cos, [Li + Lt, 64])), sin: await keep(f32(ort, r.sin, [Li + Lt, 64])) });
}
guider.reset();
const xIn = new Float32Array(N);
for (let i = 0; i < num_inference_steps; i++) {
const t = ts[i];
bf16Round(x, xIn); // the model sees the state rounded to bf16 (official sampler)
const { e, c_image, c_text } = await this.dit.time_embed.run({ sinusoid: f32(ort, sinusoid(Math.trunc(Math.fround(t * 1000)), 256), [1, 256]) });
const ci = f16(ort, readFloat(c_image), [1, 256]), ct = f16(ort, readFloat(c_text), [1, 256]), e16 = f16(ort, readFloat(e), [1, e.dims[1]]);
// image path: identical for both branches, so it runs once per step
let img = (await this.dit.patch_embed.run({ pixels: f16(ort, xIn, [1, 3, height, width]) })).img_tokens;
for (const b of this.dit.image_refiner) {
const o = (await b.run({ hidden_states: img, c: ci, rope_cos: imgCos, rope_sin: imgSin })).out_hidden_states; release(img); img = o;
}
const imgBits = halfBits(await toCpu(img)); release(img);
const preds = [];
for (const br of branches) {
let txt = br.tokens;
for (const b of this.dit.text_refiner) {
const o = (await b.run({ hidden_states: txt, c: ct, rope_cos: br.txtCos, rope_sin: br.txtSin })).out_hidden_states;
if (txt !== br.tokens) release(txt); txt = o;
}
const txtBits = halfBits(await toCpu(txt)); if (txt !== br.tokens) release(txt);
const seq = new Uint16Array((Li + br.Lt) * imgBits.length / Li);
seq.set(imgBits); seq.set(txtBits, imgBits.length);
let h = f16(ort, seq, [1, Li + br.Lt, imgBits.length / Li]);
for (const b of this.dit.blocks) {
const o = (await b.run({ hidden_states: h, c: ci, rope_cos: br.cos, rope_sin: br.sin })).out_hidden_states; release(h); h = o;
}
const hb = halfBits(await toCpu(h)); release(h);
const patches = readFloat((await this.dit.head.run({ hidden_states: f16(ort, hb.subarray(0, imgBits.length), [1, Li, imgBits.length / Li]), e: e16 })).patches);
preds.push(unpatchify(patches, hp, wp, P));
}
// velocities of the bf16 state the model saw; APG; Euler on the fp32 state (pjit_21k/sampler.py)
const vc = new Float32Array(N), vu = new Float32Array(N);
for (let k = 0; k < N; k++) { vc[k] = (xIn[k] - preds[0][k]) / t; vu[k] = (xIn[k] - preds[1][k]) / t; }
const vg = guider.guide(vc, vu, (a) => bf16Round(a));
const v = new Float32Array(N);
for (let k = 0; k < N; k++) { const xp = xIn[k] - t * vg[k]; v[k] = (x[k] - xp) / t; }
this.scheduler.step(v, i, x);
callback_on_step_end?.(i, num_inference_steps);
}
for (const br of branches) for (const k of ["txtCos", "txtSin", "cos", "sin"]) release(br[k]);
release(imgCos); release(imgSin);
if (output_type === "latent") return { images: [], latents: x };
const px = new Uint8ClampedArray(width * height * 4), S = width * height;
for (let k = 0; k < S; k++) {
for (let c = 0; c < 3; c++) px[k * 4 + c] = Math.round((Math.min(1, Math.max(-1, x[c * S + k])) + 1) / 2 * 255);
px[k * 4 + 3] = 255;
}
return { images: [{ data: px, width, height }], latents: x };
}
}
async function toCpu(t) { // GPU-resident tensor -> CPU tensor (CPU tensors pass through)
if (t.location !== "gpu-buffer") return t;
const data = await t.getData();
return { data, dims: t.dims, type: t.type };
}
function scaleInPlace(a, s) { for (let i = 0; i < a.length; i++) a[i] *= s; return a; }
/** Official sinusoidal_embedding_1d (fp64): [cos | sin] of t * 10000^(-k/half). */
function sinusoid(t, dim) {
const half = dim / 2, out = new Float32Array(dim);
for (let k = 0; k < half; k++) { const a = t * 10000 ** (-k / half); out[k] = Math.cos(a); out[half + k] = Math.sin(a); }
return out;
}
/**
* RoPE cos/sin [L, 64] for [image hp*wp | text Lt]: 64 rotation pairs per token split (t: 22, h: 21, w: 21); image tokens
* rotate by (frame 0, row * spatial_scale, col * spatial_scale); text tokens sit at position 0 (identity).
*/
function ropeTables(hp, wp, Lt, { head_dim, theta, spatial_scale }) {
const half = head_dim / 2, sp = Math.floor(half / 3), tp = half - 2 * sp;
const inv = (pairs) => Array.from({ length: pairs }, (_, j) => 1 / theta ** ((2 * j) / (2 * pairs)));
const it = inv(tp), is = inv(sp), L = hp * wp + Lt;
const cos = new Float32Array(L * half).fill(1), sin = new Float32Array(L * half);
for (let r = 0; r < hp; r++) for (let c = 0; c < wp; c++) {
const n = r * wp + c, o = n * half;
for (let j = 0; j < sp; j++) {
const a = r * spatial_scale * is[j], b = c * spatial_scale * is[j];
cos[o + tp + j] = Math.cos(a); sin[o + tp + j] = Math.sin(a);
cos[o + tp + sp + j] = Math.cos(b); sin[o + tp + sp + j] = Math.sin(b);
}
}
return { cos, sin };
}
/** Head patches [hp*wp, P*P*3] -> planar image [3, hp*P, wp*P] (official unpatchify). */
function unpatchify(patches, hp, wp, P) {
const W = wp * P, S = hp * P * W, out = new Float32Array(3 * S);
for (let h = 0; h < hp; h++) for (let w = 0; w < wp; w++) {
const base = (h * wp + w) * P * P * 3;
for (let q = 0; q < P; q++) for (let r = 0; r < P; r++) for (let c = 0; c < 3; c++)
out[c * S + (h * P + q) * W + w * P + r] = patches[base + (q * P + r) * 3 + c];
}
return out;
}