Style transfer test: Jeveration image-to-image on WebGPU
Browse filesFiles changed (13)
- .gitattributes+2
- README.md+14-5
- examples/gray_pancakes.jpgAdded
- examples/photo_boathouse.jpgAdded
- examples/photo_croissant.jpgAdded
- examples/photo_owl.jpgAdded
- examples/photo_snowcabin.jpgAdded
- examples/photo_valley.jpgAdded
- examples/photo_waterfall.jpgAdded
- hub.jsAdded+137
- index.html+230-17
- jeveration.jsAdded+298
- worker.jsAdded+59
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/photo_snowcabin.jpg filter=lfs diff=lfs merge=lfs -textexamples/photo_valley.jpg filter=lfs diff=lfs merge=lfs -text
12345678910---title: Jeveration WebGPU StyleTransferemoji: 📉colorFrom: pinkcolorTo: redsdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819---title: Jeveration WebGPU (style transfer test)emoji: ⚡colorFrom: indigocolorTo: graysdk: staticapp_file: index.htmlpinned: falselicense: apache-2.0short_description: One-pass text-to-image and style transfer on WebGPUmodels:- linoyts/Jeveration-int8-ONNX- linlinlinlinsdada/Jeveration---Test copy of [linoyts/Jeveration-WebGPU](https://huggingface.co/spaces/linoyts/Jeveration-WebGPU) with Jeveration'simage-to-image style transfer (watercolor, anime, Ghibli) and colorization, fully in the browser with ONNX Runtime Web.Weights from the `i2i` branch of [linoyts/Jeveration-int8-ONNX](https://huggingface.co/linoyts/Jeveration-int8-ONNX).Example photos from the [Jeveration repository](https://github.com/Carol-lyh/Jeveration).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137// Vendored from diffusers-js (js/src/hub.js): Hub file access with a content-addressed Cache API cache.// File access for pipelines. A pipeline only asks for paths inside a model repo ("transformer/config.json");// where the bytes come from (Hub + browser Cache API, or a local folder in Node) is decided here.
/** Cache API keys must be http(s) URLs; this host is reserved (RFC 2606) so it can never collide with a real file. */const CONTENT_ORIGIN = "https://diffusers-js.invalid";const contentKey = (sha256) => `${CONTENT_ORIGIN}/sha256/${sha256}`;
/** * Hub repo, cached in the browser's Cache API (survives reloads, same idea as transformers.js). * * Large (LFS) files are cached by content: the key is the file's SHA-256 from the Hub's file listing, not its URL. * A renamed repo, a new revision that leaves a file unchanged, or the same file in two repos is downloaded once. * Every download is checked against that hash before it is cached. Copies cached by URL by earlier versions are * adopted after the same check, so moving to content keys costs no re-download. */export class HubFiles { constructor(repo, { revision = "main", endpoint = "https://huggingface.co", cacheName = "diffusers-js" } = {}) { this.repo = repo; this.revision = revision; this.endpoint = endpoint; this.cacheName = cacheName; this._manifest = null; this._legacy = null; }
url(path) { return `${this.endpoint}/${this.repo}/resolve/${this.revision}/${path}`; }
async _cache() { try { return await caches.open(this.cacheName); } catch { return null; } } // no Cache API (some private modes)
/** * Configs are small and change when the repo is updated, so they always come from the network (the cached copy is * only a fallback when offline). */ async json(path) { const url = this.url(path); const cache = await this._cache(); try { const res = await fetch(url, { cache: "no-cache" }); // revalidate: unchanged files come back as 304 if (!res.ok) throw new Error(`${res.status} fetching ${url}`); const text = await res.text(); if (cache) { try { await cache.put(url, new Response(text, { headers: { "content-type": "application/json" } })); } catch { /* quota */ } } return JSON.parse(text); } catch (e) { const hit = cache ? await cache.match(url) : undefined; if (hit) return JSON.parse(await hit.text()); throw e; } }
/** path -> {sha256, size} for every LFS file in the repo, from the Hub's tree listing (cached for offline use). */ manifest() { return (this._manifest ??= (async () => { const cache = await this._cache(); const key = `${CONTENT_ORIGIN}/manifest/${this.repo}@${this.revision}`; let entries = null; try { entries = []; let next = `${this.endpoint}/api/models/${this.repo}/tree/${encodeURIComponent(this.revision)}?recursive=true`; while (next) { const res = await fetch(next, { cache: "no-cache" }); if (!res.ok) throw new Error(`${res.status} listing ${this.repo}`); entries.push(...(await res.json())); next = /<([^>]+)>;\s*rel="next"/.exec(res.headers.get("link") ?? "")?.[1] ?? null; } if (cache) { try { await cache.put(key, new Response(JSON.stringify(entries))); } catch { /* quota */ } } } catch { const hit = cache ? await cache.match(key) : undefined; entries = hit ? await hit.json() : null; // offline and never listed: fall back to URL keys } if (!entries) return null; const map = new Map(); for (const e of entries) if (e.type === "file" && e.lfs?.oid) map.set(e.path, { sha256: e.lfs.oid, size: e.lfs.size }); return map; })()); }
/** @param {(e:{file:string,loaded:number,total:number,fromCache:boolean})=>void} [onProgress] */ async bytes(path, onProgress) { const url = this.url(path); const cache = await this._cache(); const entry = (await this.manifest())?.get(path); const key = entry ? contentKey(entry.sha256) : url; // small non-LFS files keep URL keys
if (cache) { const hit = await cache.match(key); if (hit) return read(hit, path, onProgress, true); if (entry) { const adopted = await this._adopt(cache, path, entry, onProgress); if (adopted) return adopted; } }
const res = await fetch(url); if (!res.ok) throw new Error(`${res.status} fetching ${url}`); const buf = await read(res, path, onProgress, false); if (entry && (await sha256(buf)) !== entry.sha256) throw new Error(`checksum mismatch for ${path}; the download was corrupted, please retry`); if (cache) { try { await cache.put(key, new Response(buf, { headers: { "content-length": String(buf.length) } })); } catch { /* quota */ } } return buf; }
/** A copy of `path` cached by URL (older versions, possibly under another repo name or revision) with the right hash. */ async _adopt(cache, path, entry, onProgress) { this._legacy ??= cache.keys().then((reqs) => reqs.map((r) => r.url).filter((u) => !u.startsWith(CONTENT_ORIGIN) && u.includes("/resolve/"))); for (const u of await this._legacy) { if (!u.endsWith("/" + path)) continue; const res = await cache.match(u); if (!res || Number(res.headers.get("content-length") || entry.size) !== entry.size) continue; const buf = await read(res, path, onProgress, true); if (buf.length !== entry.size || (await sha256(buf)) !== entry.sha256) continue; try { await cache.put(contentKey(entry.sha256), new Response(buf, { headers: { "content-length": String(buf.length) } })); await cache.delete(u); } catch { /* quota */ } return buf; } return null; }}
/** Read a response body into one Uint8Array, reporting progress. */async function read(res, path, onProgress, fromCache) { const total = Number(res.headers.get("content-length")) || 0; const reader = res.body.getReader(); // content-length is only a hint (it is the compressed size when the body is gzipped), so overflow goes to `parts`. const out = new Uint8Array(total || 0); const parts = []; let loaded = 0, filled = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; if (!parts.length && filled + value.length <= total) { out.set(value, filled); filled += value.length; } else parts.push(value); loaded += value.length; onProgress?.({ file: path, loaded, total: Math.max(total, loaded), fromCache }); } if (filled === total && !parts.length) return out; return concat([out.subarray(0, filled), ...parts], loaded);}
async function sha256(buf) { const d = new Uint8Array(await crypto.subtle.digest("SHA-256", buf)); let s = ""; for (const b of d) s += b.toString(16).padStart(2, "0"); return s;}
function concat(parts, n) { const o = new Uint8Array(n); let k = 0; for (const p of parts) { o.set(p, k); k += p.length; } return o; }12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Jeveration WebGPU</title><style>:root { --bg: #fafaf9; --fg: #1c1917; --muted: #78716c; --line: #e7e5e4; --card: #ffffff; --accent: #4f46e5; --accent-fg: #fff; --err: #b91c1c; }@media (prefers-color-scheme: dark) {:root { --bg: #0c0a09; --fg: #f5f5f4; --muted: #a8a29e; --line: #292524; --card: #1c1917; --accent: #818cf8; --accent-fg: #0c0a09; --err: #f87171; }}*, *::before, *::after { box-sizing: border-box; }body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }main { max-width: 980px; margin: 0 auto; padding: 24px 16px 48px; }h1 { font-size: 1.5rem; margin: 0 0 4px; overflow-wrap: anywhere; }.sub { color: var(--muted); margin: 0 0 20px; overflow-wrap: anywhere; }.grid { display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start; }.controls { flex: 1 1 320px; min-width: 0; display: flex; flex-direction: column; gap: 12px; }.out { flex: 1 1 420px; min-width: 0; }label { font-weight: 600; font-size: .9rem; }textarea, input[type=number] { width: 100%; max-width: 100%; padding: 10px; border: 1px solid var(--line); border-radius: 8px;background: var(--card); color: var(--fg); font: inherit; }textarea { min-height: 96px; resize: vertical; }.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; }.row > * { min-width: 0; }.seed { flex: 1 1 120px; }button { padding: 10px 16px; border: 0; border-radius: 8px; background: var(--accent); color: var(--accent-fg); font: inherit;font-weight: 600; cursor: pointer; white-space: nowrap; }button.secondary { background: transparent; color: var(--fg); border: 1px solid var(--line); }button:disabled { opacity: .5; cursor: not-allowed; }.frame { width: 100%; aspect-ratio: 1; border: 1px solid var(--line); border-radius: 10px; background: var(--card); overflow: hidden;display: flex; align-items: center; justify-content: center; color: var(--muted); }canvas { width: 100%; height: 100%; display: block; object-fit: contain; }.status { font-size: .9rem; color: var(--muted); overflow-wrap: anywhere; }.status.err { color: var(--err); }.bar { height: 6px; background: var(--line); border-radius: 99px; overflow: hidden; }.bar > div { height: 100%; width: 0; background: var(--accent); transition: width .2s; }table { width: 100%; border-collapse: collapse; font-size: .85rem; font-variant-numeric: tabular-nums; }td { padding: 3px 0; border-bottom: 1px solid var(--line); }td:last-child { text-align: right; }.note { font-size: .8rem; color: var(--muted); }a { color: var(--accent); }.toggle { display: flex; gap: 8px; align-items: flex-start; font-weight: 500; overflow-wrap: anywhere; }.toggle input { flex: 0 0 auto; margin-top: 4px; }.chips { display: flex; flex-wrap: wrap; gap: 8px; min-width: 0; }.chip { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 4px 12px; border-radius: 99px;border: 1px solid var(--line); background: transparent; color: var(--fg); font-size: .78rem; font-weight: 500; }.chip:hover, .chip:focus-visible { border-color: var(--accent); }.chip[aria-pressed="true"] { border-color: var(--accent); background: var(--accent); color: var(--accent-fg); }.tabs { display: flex; gap: 4px; padding: 4px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); }.tabs button { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; background: transparent; color: var(--fg); padding: 8px 10px; }.tabs button[aria-selected="true"] { background: var(--accent); color: var(--accent-fg); }.drop { display: flex; gap: 12px; align-items: center; padding: 10px; border: 1px dashed var(--line); border-radius: 10px; cursor: pointer;min-width: 0; color: var(--muted); font-weight: 500; }.drop.over { border-color: var(--accent); }.drop canvas { flex: 0 0 auto; width: 96px; height: 96px; border-radius: 8px; background: var(--line); }.drop span { min-width: 0; overflow-wrap: anywhere; }.thumbs { display: flex; flex-wrap: wrap; gap: 8px; }.thumbs button { padding: 0; width: 56px; height: 56px; border-radius: 8px; overflow: hidden; border: 2px solid transparent; background: var(--line); }.thumbs button:hover, .thumbs button:focus-visible { border-color: var(--accent); }.thumbs img { width: 100%; height: 100%; object-fit: cover; display: block; }.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }[hidden] { display: none !important; }</style></head><body><main><h1>Jeveration WebGPU</h1><p class="sub">Text-to-image and style transfer in one forward pass, running entirely in your browser on WebGPU.<a href="https://huggingface.co/linlinlinlinsdada/Jeveration" target="_blank" rel="noopener">Jeveration</a> (Qwen3.5-4B + LoRA, int8) exported to ONNX:<a href="https://huggingface.co/linoyts/Jeveration-int8-ONNX" target="_blank" rel="noopener">linoyts/Jeveration-int8-ONNX</a>.</p><div class="grid"><section class="controls"><div class="status" id="gpu">Checking WebGPU...</div><button id="load" disabled>Load model (~7.5 GB, cached after the first visit)</button><div class="bar"><div id="bar"></div></div><div class="status" id="status"></div><div class="tabs" role="tablist"><button role="tab" id="tab-t2i" aria-selected="true">Text to image</button><button role="tab" id="tab-i2i" aria-selected="false">Style transfer</button></div><div id="t2i-panel" class="controls" style="flex: none;"><label for="prompt">Prompt</label><textarea id="prompt">Pixel art of a cozy wooden cabin in a snowy pine forest at night, warm light glowing in the windows.</textarea><div class="chips" id="examples"></div></div><div id="i2i-panel" class="controls" style="flex: none;" hidden><label>Photo</label><label class="drop" id="drop"><canvas id="src" width="512" height="512"></canvas><span>Drop a photo here or click to choose one. It is cropped to a square.</span><input type="file" id="file" accept="image/*" class="sr-only"></label><div class="thumbs" id="thumbs"></div><label>Style</label><div class="chips" id="styles"></div></div><div class="row"><div class="seed"><label for="seed">Seed</label><input id="seed" type="number" value="0" min="0"></div><button class="secondary" id="rand" type="button">Random</button><button id="go" disabled>Generate</button></div><label class="toggle"><input id="live" type="checkbox" checked> Live: regenerate on every change (same seed, so the image changes smoothly)</label><div class="status" id="live-stats"></div><table id="timings"></table><p class="note">512 x 512. The first generation includes shader compilation; time the second one.</p></section><section class="out"><div class="frame" id="frame"><canvas id="canvas" width="512" height="512"></canvas></div></section></div></main><script type="module">const $ = (id) => document.getElementById(id);const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });const EXAMPLES = ["Pixel art of a cozy wooden cabin in a snowy pine forest at night, warm light glowing in the windows.","A watercolor painting of a red fox curled up asleep under an autumn tree, soft washes on textured paper.","A comic book panel of a cat in a superhero cape leaping between city rooftops, bold ink lines and halftone dots.","An anime illustration of a girl holding a red umbrella on a rainy street at dusk, glowing shop signs.","A low-poly 3D illustration of a lighthouse on a rocky cliff at sunset, pastel colors.","A Japanese woodblock print of a crane flying over snowy mountains, flat colors and fine outlines.","A children's book illustration of a bear reading a book under a lamp, crayon and colored pencil texture.","A stained glass window of a peacock with its tail spread, bright jewel tones and thick black leading.","A flat vector illustration of hot air balloons over a patchwork of green fields, simple shapes.","An oil painting in thick impasto strokes of a sunflower field under a swirling blue sky.",];const STYLES = [["watercolor", "Watercolor"], ["anime", "Anime"], ["ghibli", "Ghibli"], ["colorize", "Colorize (black and white photo)"]];const PHOTOS = ["photo_snowcabin", "photo_owl", "photo_valley", "photo_boathouse", "photo_croissant", "photo_waterfall", "gray_pancakes"];let mode = "t2i", task = "watercolor", imageId = 0, haveImage = false;for (const ex of EXAMPLES) {const b = document.createElement("button");b.type = "button"; b.className = "chip"; b.title = ex; b.textContent = ex;b.onclick = () => { $("prompt").value = ex; $("prompt").dispatchEvent(new Event("input")); };$("examples").append(b);}for (const [key, name] of STYLES) {const b = document.createElement("button");b.type = "button"; b.className = "chip"; b.textContent = name; b.dataset.task = key; b.setAttribute("aria-pressed", String(key === task));b.onclick = () => { task = key; for (const c of $("styles").children) c.setAttribute("aria-pressed", String(c.dataset.task === key)); live(); };$("styles").append(b);}for (const f of PHOTOS) {const b = document.createElement("button"), im = document.createElement("img");b.type = "button"; b.title = f.replace(/^(photo|gray)_/, ""); im.src = `examples/${f}.jpg`; im.alt = b.title; b.append(im);b.onclick = async () => { await setPhoto(await (await fetch(`examples/${f}.jpg`)).blob()); if (f.startsWith("gray_")) $("styles").children[3].click(); };$("thumbs").append(b);}/** a picture -> 512 x 512 RGB (shorter side to 512, centre crop), shown in the drop zone and sent to the worker once */async function setPhoto(blob) {const bmp = await createImageBitmap(blob), s = 512 / Math.min(bmp.width, bmp.height);const w = Math.max(512, Math.round(bmp.width * s)), h = Math.max(512, Math.round(bmp.height * s));const ctx = $("src").getContext("2d"); ctx.imageSmoothingQuality = "high";ctx.drawImage(bmp, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h);const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);for (let i = 0; i < 512 * 512; i++) { rgb[3 * i] = px[4 * i]; rgb[3 * i + 1] = px[4 * i + 1]; rgb[3 * i + 2] = px[4 * i + 2]; }worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);haveImage = true; live();}$("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };$("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };$("drop").ondragleave = () => $("drop").classList.remove("over");$("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };const setMode = (m) => {mode = m;$("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));$("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else live();};$("tab-t2i").onclick = () => setMode("t2i");$("tab-i2i").onclick = () => setMode("i2i");const files = new Map();const setStatus = (t, err = false) => { $("status").textContent = t; $("status").className = "status" + (err ? " err" : ""); };const fmt = (b) => (b / 1e9).toFixed(2) + " GB";const TOTAL = 7.55e9;let ready = false, reqId = 0;const sent = new Map(), frames = [];const request = () => {if (mode === "i2i" && !haveImage) return;const id = ++reqId; sent.set(id, performance.now());worker.postMessage({ type: "generate", data: { mode, prompt: $("prompt").value, task, seed: Number($("seed").value) || 0, id } });};worker.onmessage = ({ data: m }) => {if (m.status === "checked") {$("gpu").textContent = `WebGPU ready: ${m.data.vendor || "GPU"} ${m.data.architecture || ""}`.trim();$("load").disabled = false;} else if (m.status === "loading") {setStatus(`Loading ${m.file}...`);} else if (m.status === "progress") {files.set(m.file, m);let loaded = 0; for (const f of files.values()) loaded += f.loaded;$("bar").style.width = Math.min(100, (100 * loaded) / TOTAL) + "%";setStatus(`${m.fromCache ? "From cache" : "Downloading"}: ${m.file} (${fmt(loaded)} of ~${fmt(TOTAL)})`);} else if (m.status === "ready") {$("bar").style.width = "100%";setStatus(`Ready (loaded in ${m.data.seconds.toFixed(1)} s).`);$("go").disabled = false; $("load").disabled = true; ready = true;if ($("live").checked) request();} else if (m.status === "image") {const { rgb, timings } = m.data, img = new ImageData(512, 512);for (let i = 0; i < 512 * 512; i++) { img.data[4 * i] = rgb[3 * i]; img.data[4 * i + 1] = rgb[3 * i + 1]; img.data[4 * i + 2] = rgb[3 * i + 2]; img.data[4 * i + 3] = 255; }$("canvas").getContext("2d").putImageData(img, 0, 0);const rows = [...(m.data.mode === "i2i" ? [["Vision encoder", timings.vision]] : []), ["Backbone (Qwen3.5-4B, int8)", timings.backbone],["Image head", timings.head], ["Sampling", timings.sample], ["CLIP + decoder", timings.decode], ["Total", timings.total]];$("timings").innerHTML = rows.map(([k, v]) => `<tr><td>${k}</td><td>${(v / 1000).toFixed(2)} s</td></tr>`).join("");const now = performance.now(), latency = now - (sent.get(m.data.id) ?? now);sent.forEach((_, k) => { if (k <= m.data.id) sent.delete(k); });frames.push(now); while (frames.length && now - frames[0] > 5000) frames.shift();const fps = frames.length > 1 ? (frames.length - 1) / ((now - frames[0]) / 1000) : 0;setStatus(`Done in ${(timings.total / 1000).toFixed(2)} s.`);$("live-stats").textContent = `Latency from change to image: ${(latency / 1000).toFixed(2)} s` +(fps ? ` · ${fps.toFixed(1)} images/s` : "") + (m.data.skipped ? ` · ${m.data.skipped} stale requests skipped` : "");$("go").disabled = false;} else if (m.status === "error") {setStatus("Error: " + m.data, true); $("go").disabled = false;}};$("load").onclick = () => { $("load").disabled = true; setStatus("Starting..."); worker.postMessage({ type: "load" }); };$("rand").onclick = () => { $("seed").value = Math.floor(Math.random() * 1e6); };$("go").onclick = () => { $("go").disabled = true; setStatus("Generating..."); request(); };function live() { if (ready && $("live").checked) request(); }$("prompt").addEventListener("input", live);$("seed").addEventListener("input", live);$("live").addEventListener("change", live);$("rand").addEventListener("click", live);worker.postMessage({ type: "check" });worker.onerror = (e) => setStatus("Worker error: " + (e.message || e), true);</script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298// Jeveration text-to-image in JS on ONNX Runtime: one backbone pass -> 128 codes -> TA-TiTok decoder -> 512x512 image.// `ort` is injected (onnxruntime-node for tests, onnxruntime-web/webgpu in the browser); `files` resolves graph paths.import { Tokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/+esm";
const N_CODES = 128, CODE_DIM = 64, K = 8192, HIDDEN = 2560, CLIP_LEN = 77;
/** Small seeded RNG (xoshiro128**) with uniform and normal draws. Not torch's stream: same seed != same image as PyTorch. */export class Rng { constructor(seed = 0) { let s = (seed >>> 0) || 1; const sm = () => { s = (s + 0x9e3779b9) >>> 0; let z = s; z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) >>> 0; z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) >>> 0; return (z ^ (z >>> 16)) >>> 0; }; this.a = sm(); this.b = sm(); this.c = sm(); this.d = sm(); } u32() { const r = Math.imul(((Math.imul(this.b, 5) << 7) | (Math.imul(this.b, 5) >>> 25)), 9) >>> 0, t = this.b << 9; this.c ^= this.a; this.d ^= this.b; this.b ^= this.c; this.a ^= this.d; this.c ^= t; this.d = (this.d << 11) | (this.d >>> 21); return r; } uniform() { return (this.u32() + 0.5) / 4294967296; } // (0, 1) normal() { return Math.sqrt(-2 * Math.log(this.uniform())) * Math.cos(2 * Math.PI * this.uniform()); }}
export class JeverationPipeline { /** files: {bytes(path), json(path), path?(path)}; graphs/assets as written by export_rest.py and build_mixed.py */ static async load(files, { ort, device = "cpu", head = "head_fp16.onnx", backbone = "backbone_int8/manifest.json", i2i = false, progress } = {}) { const p = new JeverationPipeline(); p.ort = ort; p.device = device; const S = async (path, { gpuOut = false } = {}) => { const opts = { executionProviders: [device === "webgpu" ? "webgpu" : "cpu"], graphOptimizationLevel: "all" }; if (device === "webgpu" && gpuOut) opts.preferredOutputLocation = "gpu-buffer"; // stays on the GPU for the next graph 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 }); opts.externalData = [{ path: path.split("/").pop() + "_data", data: await files.bytes(path + "_data", onP) }]; return ort.InferenceSession.create(await files.bytes(path, onP), opts); }; p.tpl = await files.json("assets/prompt_template.json"); p.sampling = await files.json("assets/sampling.json"); const f32file = async (f) => { const b = await files.bytes(f); return new Float32Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)); }; p.codebookStd = await f32file("assets/codebook_std.bin"); p.maskEmb = await f32file("assets/mask_emb.bin"); p.qwenTok = new Tokenizer(await files.json("tokenizer/qwen/tokenizer.json"), await files.json("tokenizer/qwen/tokenizer_config.json")); p.clipTok = new Tokenizer(await files.json("tokenizer/clip/tokenizer.json"), await files.json("tokenizer/clip/tokenizer_config.json")); const manifest = await files.json(backbone); // the backbone, split into consecutive-layer chunks p.s = { embed: await S("embed_tokens_q4f16.onnx"), decisionEmbed: await S("decision_embed_fp16.onnx"), chunks: [], head: await S(head), clip: await S("clip_text_fp16.onnx"), decoder: await S("decoder_fp16.onnx"), }; for (const [i, f] of manifest.files.entries()) p.s.chunks.push(await S(f, { gpuOut: i < manifest.files.length - 1 })); p.maxLen = manifest.max_len ?? 320; if (i2i) { // image-to-image: the vision tower, the source decoder, the texts p.i2iTpl = await files.json("assets/i2i_template.json"); p.s.vision = await S("vision_encoder_fp16.onnx"); p.s.sourceDecoder = await S("source_decoder_fp16.onnx"); } return p; }
/** prompt -> backbone token ids: chat head + prompt (<= 128 tokens) + chat tail */ promptIds(prompt) { const ids = this.qwenTok.encode(prompt, { add_special_tokens: false }).ids.slice(0, this.tpl.max_prompt_tokens); return [...this.tpl.head_ids, ...ids, ...this.tpl.tail_ids]; }
/** prompt -> 77 CLIP ids, padded with 0 after the end token (open_clip's convention, which the decoder was trained with) */ clipIds(prompt) { const ids = this.clipTok.encode(prompt.toLowerCase().trim().replace(/\s+/g, " ")).ids; // [BOS, ..., EOS] const out = new BigInt64Array(CLIP_LEN); const body = ids.slice(0, CLIP_LEN); if (body.length === CLIP_LEN) body[CLIP_LEN - 1] = ids[ids.length - 1]; // truncated: keep the end token last body.forEach((v, i) => { out[i] = BigInt(v); }); return out; }
/** the shared random state: each position masked (mask_emb) with prob MASK_PROB or a random standardised code, + noise */ randomState(rng) { const { mask_prob: rho, state_noise: sigma } = this.sampling; const state = new Float32Array(N_CODES * CODE_DIM); let masked = 0; const isMasked = [], code = []; for (let i = 0; i < N_CODES; i++) isMasked.push(rng.uniform() < rho); for (let i = 0; i < N_CODES; i++) code.push(rng.u32() % K); const a = Math.sqrt(1 - sigma * sigma); for (let i = 0; i < N_CODES; i++) { if (isMasked[i]) masked++; for (let j = 0; j < CODE_DIM; j++) { const v = isMasked[i] ? this.maskEmb[j] : this.codebookStd[code[i] * CODE_DIM + j]; state[i * CODE_DIM + j] = a * v + sigma * rng.normal(); } } return { state, t: new Float32Array([masked / N_CODES]) }; }
/** Gumbel noise [128*8192] for sampling all codes: one categorical draw per position is argmax(logits + noise) */ static gumbel(rng) { const g = new Float32Array(N_CODES * K); for (let i = 0; i < g.length; i++) g[i] = -Math.log(-Math.log(rng.uniform())); return g; }
/** logits [128, 8192] + Gumbel noise -> codes. With the noise held fixed, a small change of the logits keeps most codes. */ static sampleCodes(logits, noise) { const codes = new BigInt64Array(N_CODES); for (let i = 0; i < N_CODES; i++) { let best = -Infinity, arg = 0; for (let k = 0, o = i * K; k < K; k++) { const v = logits[o + k] + noise[o + k]; if (v > best) { best = v; arg = k; } } codes[i] = BigInt(arg); } return codes; }
/** Everything a seed decides, computed once and reused while only the prompt changes: the random state, the * decision tokens' input embeddings and the sampling noise. */ async seedCache(seed) { if (this._seed?.seed === seed) return this._seed; const rng = new Rng(seed), { state, t } = this.randomState(rng), noise = JeverationPipeline.gumbel(rng); const tail = await this.decisionTail(state, t); return (this._seed = { seed, state, t, noise, tail }); }
/** the backbone pass and the image head: (ids, state, t) -> logits Float32Array [128*8192] */ async logits(ids, state, t, timings = {}, tailCached = null) { const { ort, s } = this, T = (n, d, dims) => new ort.Tensor(n, d, dims); const t0 = performance.now(); const emb = toF32((await s.embed.run({ input_ids: T("int64", BigInt64Array.from(ids.map(BigInt)), [1, ids.length]) })).inputs_embeds.data); const tail = tailCached ?? await this.decisionTail(state, t); const L = ids.length + N_CODES, x = new Float32Array(L * HIDDEN); x.set(emb, 0); x.set(tail, ids.length * HIDDEN); 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); timings.inputs = performance.now() - t0; return this.backboneAndHead(x, pos, L, state, t, timings); }
async decisionTail(state, t) { const T = (n, d, dims) => new this.ort.Tensor(n, d, dims); return toF32((await this.s.decisionEmbed.run({ state: T("float32", state, [1, N_CODES, CODE_DIM]), t: T("float32", t, [1]) })).tail.data); }
/** x [L*2560] (the decision tokens last), rotary positions [3*L] -> logits Float32Array [128*8192] */ async backboneAndHead(x, pos, L, state, t, timings = {}) { const { ort, s } = this, T = (n, d, dims) => new ort.Tensor(n, d, dims); if (L > this.maxLen) throw new Error(`request of ${L} tokens; this backbone takes at most ${this.maxLen}`); let t0 = performance.now(); const position_ids = T("int64", pos, [3, 1, L]); let h = T("float32", x, [1, L, HIDDEN]); for (const c of s.chunks) { const o = await c.run({ hidden_in: h, position_ids }); if (h.location === "gpu-buffer") h.dispose(); h = o.hidden_out ?? o.hidden; } const hidden = h; timings.backbone = performance.now() - t0; t0 = performance.now(); const lg = (await s.head.run({ hidden, state: T("float32", state, [1, N_CODES, CODE_DIM]), t: T("float32", t, [1]) })).logits; if (hidden.location === "gpu-buffer") hidden.dispose(); timings.head = performance.now() - t0; return toF32(lg.location === "gpu-buffer" ? await lg.getData() : lg.data); }
/** codes + prompt -> RGB uint8 [512*512*3] */ async decode(codes, prompt, timings = {}, source = null) { const { ort, s } = this; let t0 = performance.now(); const tg = (await s.clip.run({ clip_ids: new ort.Tensor("int64", this.clipIds(prompt), [1, CLIP_LEN]) })).text_guidance; const feeds = { codes: new ort.Tensor("int64", codes, [1, N_CODES]), text_guidance: tg }; if (source) { // image-to-image: the source picture (planar, [0, 1]) and its task id const hw = 512 * 512, src = new Float32Array(3 * hw); for (let c = 0; c < 3; c++) for (let i = 0; i < hw; i++) src[c * hw + i] = source.rgb[i * 3 + c] / 255; feeds.source = new ort.Tensor("float32", src, [1, 3, 512, 512]); feeds.task = new ort.Tensor("int64", BigInt64Array.from([BigInt(source.task)]), [1]); } const img = (await (source ? s.sourceDecoder : s.decoder).run(feeds)).image.data; timings.decode = performance.now() - t0; const hw = 512 * 512, rgb = new Uint8Array(hw * 3); for (let c = 0; c < 3; c++) for (let i = 0; i < hw; i++) rgb[i * 3 + c] = Math.round(Math.min(1, Math.max(0, img[c * hw + i])) * 255); return rgb; }
/** prompt -> {rgb, codes, timings}; one backbone pass. Same seed = same random state and sampling noise, so editing * the prompt changes the image smoothly instead of re-rolling it. */ async generate(prompt, { seed = 0 } = {}) { const timings = {}; const t0 = performance.now(); const c = await this.seedCache(seed); timings.seed = performance.now() - t0; const logits = await this.logits(this.promptIds(prompt), c.state, c.t, timings, c.tail); let t1 = performance.now(); const codes = JeverationPipeline.sampleCodes(logits, c.noise); timings.sample = performance.now() - t1; const rgb = await this.decode(codes, prompt, timings); timings.total = performance.now() - t0; return { rgb, codes, timings }; }
// ---- image-to-image ------------------------------------------------------------------------------------------------------ /** RGB uint8 [512*512*3] -> grey (BT.601 luma in all three channels), the colorize task's input */ static toGray(rgb) { const out = new Uint8Array(rgb.length); for (let i = 0; i < rgb.length; i += 3) { const y = Math.min(255, Math.max(0, Math.round(0.299 * rgb[i] + 0.587 * rgb[i + 1] + 0.114 * rgb[i + 2]))); out[i] = out[i + 1] = out[i + 2] = y; } return out; }
/** RGB uint8 [512*512*3] -> the vision tower's patches [1024, 1536] (Qwen-VL order: 2x2 merge blocks, channel, 2 frames, 16x16) */ static patchify(rgb, size = 512) { const p = 16, m = 2, tp = 2, g = size / p, row = 3 * tp * p * p, out = new Float32Array(g * g * row); let r = 0; for (let bh = 0; bh < g / m; bh++) for (let bw = 0; bw < g / m; bw++) for (let mh = 0; mh < m; mh++) for (let mw = 0; mw < m; mw++, r++) { const y0 = (bh * m + mh) * p, x0 = (bw * m + mw) * p; for (let c = 0; c < 3; c++) for (let f = 0; f < tp; f++) for (let py = 0; py < p; py++) for (let px = 0; px < p; px++) out[r * row + ((c * tp + f) * p + py) * p + px] = rgb[((y0 + py) * size + x0 + px) * 3 + c] / 127.5 - 1; } return out; }
/** RGB uint8 [512*512*3] -> visual tokens Float32Array [256*2560]; the last picture's tokens are kept for reuse */ async visionTokens(rgb, timings = {}) { if (this._vis?.rgb === rgb) { timings.vision = 0; return this._vis.vis; } const t0 = performance.now(), g = 512 / 16; const o = await this.s.vision.run({ pixel_values: new this.ort.Tensor("float32", JeverationPipeline.patchify(rgb), [g * g, 1536]), image_grid_thw: new this.ort.Tensor("int64", BigInt64Array.from([1n, BigInt(g), BigInt(g)]), [1, 3]) }); const vis = toF32(o.image_features.data); timings.vision = performance.now() - t0; this._vis = { rgb, vis }; return vis; }
/** a task (a style, or "colorize") -> [instruction the backbone reads, text the decoder reads, decoder task id] */ i2iTexts(task) { const tp = this.i2iTpl; if (task in tp.style) return [tp.style_prefix + tp.style[task], tp.style[task], tp.decoder_task_id[task]]; if (task === "colorize") return [tp.colorize, tp.colorize, tp.decoder_task_id.colorize]; throw new Error("unknown image-to-image task " + task); }
/** photo RGB uint8 [512*512*3] (already 512 x 512) + task -> {rgb, codes, timings}. One backbone pass after the picture's * visual tokens: [chat head] [image] [end of vision] instruction [chat tail] [128 decision tokens]. */ async imageToImage(photo, task, { seed = 0, debug = null } = {}) { const timings = {}, t0 = performance.now(); const src = task === "colorize" ? (this._gray?.photo === photo ? this._gray.gray : (this._gray = { photo, gray: JeverationPipeline.toGray(photo) }).gray) : photo; const c = await this.seedCache(seed); timings.seed = performance.now() - t0; const vis = await this.visionTokens(src, timings); let t1 = performance.now(); const [instr, decText, taskId] = this.i2iTexts(task), tp = this.i2iTpl; const ins = this.qwenTok.encode(instr, { add_special_tokens: false }).ids.slice(0, this.tpl.max_prompt_tokens); const textIds = [...tp.head_ids, ...tp.mid_ids, ...ins, ...tp.tail_ids]; const T = (n, d, dims) => new this.ort.Tensor(n, d, dims); const emb = toF32((await this.s.embed.run({ input_ids: T("int64", BigInt64Array.from(textIds.map(BigInt)), [1, textIds.length]) })).inputs_embeds.data); const nh = tp.head_ids.length, nv = vis.length / HIDDEN, na = textIds.length - nh, g = Math.sqrt(nv); const L = nh + nv + na + N_CODES, x = new Float32Array(L * HIDDEN), pos = new BigInt64Array(3 * L); x.set(emb.subarray(0, nh * HIDDEN), 0); x.set(vis, nh * HIDDEN); x.set(emb.subarray(nh * HIDDEN), (nh + nv) * HIDDEN); x.set(c.tail, (nh + nv + na) * HIDDEN); const P = (a, i, v) => { pos[a * L + i] = BigInt(v); }; for (let i = 0; i < nh; i++) for (let a = 0; a < 3; a++) P(a, i, i); // text before the image for (let k = 0; k < nv; k++) { P(0, nh + k, nh); P(1, nh + k, nh + Math.floor(k / g)); P(2, nh + k, nh + (k % g)); } const after = nh + g; // text after the image for (let i = 0; i < na; i++) for (let a = 0; a < 3; a++) P(a, nh + nv + i, after + i); for (let i = 0; i < N_CODES; i++) for (let a = 0; a < 3; a++) P(a, nh + nv + na + i, after + na + i); // decision tokens timings.inputs = performance.now() - t1; let { state, t } = c; if (debug?.state) { // tests: the reference's random state instead of the seed's ({ state, t } = debug); x.set(await this.decisionTail(state, t), (nh + nv + na) * HIDDEN); } const logits = await this.backboneAndHead(x, pos, L, state, t, timings); if (debug) Object.assign(debug, { x, pos, L, logits }); t1 = performance.now(); const codes = JeverationPipeline.sampleCodes(logits, c.noise); timings.sample = performance.now() - t1; const rgb = await this.decode(codes, decText, timings, { rgb: src, task: taskId }); timings.total = performance.now() - t0; return { rgb, codes, timings, length: L }; }}
function toF32(d) { if (d instanceof Float32Array) return d; if (d instanceof Uint16Array) { const o = new Float32Array(d.length); for (let i = 0; i < d.length; i++) o[i] = half(d[i]); return o; } return Float32Array.from(d);}function half(h) { const s = h & 0x8000 ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff; if (e === 0) return s * 2 ** -14 * (f / 1024); if (e === 31) return f ? NaN : s * Infinity; return s * 2 ** (e - 15) * (1 + f / 1024);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859// Runs the whole pipeline off the main thread. Protocol: check -> load -> (image) -> generate, with status/progress// messages. Generate requests are "latest wins": while one runs, newer requests replace each other, so live editing never// builds a backlog. The style-transfer photo is sent once ("image") and kept here, so its visual tokens are reused.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 { JeverationPipeline } from "./jeveration.js";
const MODEL_ID = "linoyts/Jeveration-int8-ONNX", REVISION = "i2i";ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";ort.env.webgpu.powerPreference = "high-performance";let pipe = null, busy = false, pending = null, photo = null, skipped = 0;
const post = (m) => self.postMessage(m);
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 this model needs."); const info = adapter.info ?? {}; return { vendor: info.vendor, architecture: info.architecture, maxBufferSize: adapter.limits.maxBufferSize };}
async function drain() { if (busy) return; busy = true; while (pending) { const req = pending; pending = null; try { const out = req.mode === "i2i" ? await pipe.imageToImage(photo, req.task, { seed: req.seed }) : await pipe.generate(req.prompt, { seed: req.seed }); post({ status: "image", data: { rgb: out.rgb, timings: out.timings, mode: req.mode, id: req.id, skipped: req.skipped } }); } 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 === "load") { const t0 = performance.now(); pipe = await JeverationPipeline.load(new HubFiles(MODEL_ID, { revision: REVISION, cacheName: "jeveration-webgpu" }), { ort, device: "webgpu", backbone: "backbone_int8_long/manifest.json", i2i: true, progress: (e) => post(e), }); post({ status: "ready", data: { seconds: (performance.now() - t0) / 1000 } }); } if (type === "image") photo = data.rgb; if (type === "generate") { if (pending) skipped++; pending = { ...data, skipped }; drain(); } } catch (e) { post({ status: "error", data: String(e?.message ?? e) }); }};.gitattributes+2
README.md+14-5
examples/gray_pancakes.jpgAdded

examples/photo_boathouse.jpgAdded

examples/photo_croissant.jpgAdded

examples/photo_owl.jpgAdded

examples/photo_snowcabin.jpgAdded

Large File Pointer Details
- SHA256: 5e42b2c0465ecbfbbe34784dbbfeffc50ca7cdf303aa1368f9baeecf10d79ac4
- Pointer size: 131 Bytes
- Size of remote file: 106 kB
examples/photo_valley.jpgAdded

Large File Pointer Details
- SHA256: 007beb86404032a181ade3b3d106e22f3950b92a0055ce6784ecce2d1154569c
- Pointer size: 131 Bytes
- Size of remote file: 101 kB
examples/photo_waterfall.jpgAdded

hub.jsAdded+137
index.html+230-17
jeveration.jsAdded+298
worker.jsAdded+59