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
3.46 kB
// One worker per pipeline stage (text encoder | transformer + vae). Terminating a worker is the reliable way to give
// its GPU memory back (releasing an onnxruntime-web session does not always do it: onnxruntime#34237).
// Message protocol follows transformers.js-examples/janus-pro-webgpu: check -> load -> work, with status messages.
import * as ort from "onnxruntime-web/webgpu";
import { HubFiles, QwenImage21Pipeline, setPersistOnGpu } from "diffusers-js";
const MODEL_ID = "linoyts/Qwen-Image-2.1-int4-ONNX";
// The ORT wasm is bundled by Vite into dist/assets, so the Space never depends on a CDN or a different ORT version.
ort.env.webgpu.powerPreference = "high-performance";
let pipe = null;
async function check() {
try {
if (!navigator.gpu) throw new Error("WebGPU is not supported by this browser.");
const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
if (!adapter) throw new Error("WebGPU is not supported (no adapter found).");
if (!adapter.features.has("shader-f16")) throw new Error("This GPU does not support fp16 shaders (shader-f16), which this model needs.");
const info = adapter.info ?? {};
self.postMessage({ status: "success", data: { vendor: info.vendor, architecture: info.architecture,
maxBufferSize: adapter.limits.maxBufferSize } });
} catch (e) {
self.postMessage({ status: "error", data: String(e.message ?? e) });
}
}
async function load(components, persist = true) {
setPersistOnGpu(persist);
self.postMessage({ status: "loading", data: components.join(" + ") });
pipe = await QwenImage21Pipeline.from_pretrained(new HubFiles(MODEL_ID), {
ort, device: "webgpu", components, progress_callback: (e) => self.postMessage(e),
});
self.postMessage({ status: "ready" });
}
async function encode({ prompt, image }) {
if (image && !pipe.vision) { // the vision tower is only downloaded for the first edit
self.postMessage({ status: "loading", data: "vision" });
await pipe.load(["vision"], (e) => self.postMessage(e));
}
const t = performance.now();
const emb = await pipe.encode_prompt(prompt, { image });
self.postMessage({ status: "encoded", data: { ...emb, time: performance.now() - t } }, [emb.data.buffer]);
}
async function generate({ prompt_embeds, image, width, height, seed }) {
self.postMessage({ status: "start" });
const t0 = performance.now(); let tStep = t0;
const out = await pipe({
prompt_embeds, image, width, height, seed,
callback_on_step_end: (i, n) => {
const now = performance.now();
self.postMessage({ status: "step", data: { step: i + 1, total: n, time: now - tStep } }); tStep = now;
},
});
const im = out.images[0];
self.postMessage({ status: "complete", data: { ...im, time: performance.now() - t0 } }, [im.data.buffer]);
}
self.addEventListener("message", async ({ data: { type, data } }) => {
try {
if (type === "check") await check();
else if (type === "load") await load(data.components, data.persist);
else if (type === "encode") await encode(data);
else if (type === "generate") await generate(data);
} catch (e) {
console.error(e);
const where = String(e?.stack ?? "").split("\n").slice(1, 4).map((l) => l.trim()).join("\n");
self.postMessage({ status: "error", data: `${type}: ${String(e?.message ?? e)}${where ? "\n" + where : ""}` });
}
});