RD-Flow-64-WebGPU / worker.js
linoyts's picture
linoyts HF Staff
RD Flow 64 WebGPU demo
4173f94 verified
Raw History Blame Contribute Delete
3.72 kB
// Runs the whole pipeline off the main thread. Protocol: check -> load -> draw, with status/progress messages.
// Draw requests are "latest wins": while one runs, newer requests replace each other, and the running one stops at
// its next step, so live typing never builds a backlog. The prompt reader's features are cached per caption, so a new
// seed or a sprite/scene switch skips it.
import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.bundle.min.mjs";
import { HubFiles } from "./hub.js";
import { RDFlowPipeline } from "./rdflow.js";
const params = new URL(self.location.href).searchParams;
const MODEL_ID = params.get("model") || "linoyts/RD-Flow-64-ONNX", REVISION = params.get("revision") || "main";
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
ort.env.webgpu.powerPreference = "high-performance";
let pipe = null, lowMemory = false, busy = false, pending = null;
const cache = new Map(), CACHE_MAX = 16;
const post = (m, transfer) => self.postMessage(m, transfer ?? []);
async function check() {
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 the prompt reader needs.");
const info = adapter.info ?? {};
return { vendor: info.vendor, architecture: info.architecture };
}
async function features(req) {
let feats = cache.get(req.caption);
if (feats) { cache.delete(req.caption); cache.set(req.caption, feats); return { feats, read: null }; }
post({ status: "reading", data: { id: req.id, reload: !pipe.te } });
const t0 = performance.now();
feats = await pipe.encode(req.caption);
cache.set(req.caption, feats); if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);
if (lowMemory) await pipe.unloadText();
return { feats, read: (performance.now() - t0) / 1000 };
}
async function drain() {
if (busy) return;
busy = true;
while (pending) {
const req = pending; pending = null;
try {
const { feats, read } = await features(req);
if (pending) continue; // superseded while reading: start the newer one
const t1 = performance.now();
const out = await pipe.sample({ feats, seeds: [req.seed], transparent: req.transparent, shouldStop: () => !!pending,
onStep: (i, n) => post({ status: "step", data: { id: req.id, step: i, total: n } }) });
if (!out) continue;
const img = out.images[0];
post({ status: "image", data: { id: req.id, image: img, palette: out.palettes[0],
timings: { read, draw: (performance.now() - t1) / 1000, tokens: feats.L } } }, [img.buffer]);
} catch (e) {
post({ status: "error", data: String(e?.message ?? e) });
}
}
busy = false;
}
self.onmessage = async ({ data: { type, data } }) => {
try {
if (type === "check") post({ status: "checked", data: await check() });
if (type === "settings") lowMemory = !!data.lowMemory;
if (type === "load") {
const t0 = performance.now();
pipe = await RDFlowPipeline.load(new HubFiles(MODEL_ID, { revision: REVISION, cacheName: "rd-flow-64-webgpu" }), {
ort, device: "webgpu", progress: (e) => post(e),
});
post({ status: "ready", data: { seconds: (performance.now() - t0) / 1000 } });
}
if (type === "draw") { pending = data; drain(); }
} catch (e) {
post({ status: "error", data: String(e?.message ?? e) });
}
};