File size: 2,503 Bytes
8556da7
dc9af15
 
8556da7
 
 
 
 
 
 
dc9af15
8556da7
 
 
 
 
 
 
 
 
 
 
 
dc9af15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8556da7
 
 
 
 
 
 
 
 
 
 
dc9af15
 
 
8556da7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Runs the whole pipeline off the main thread. Protocol: check -> load -> generate, with status/progress messages.
// Generate requests are "latest wins": while one runs, newer requests replace each other, so live typing never builds
// a backlog and the image always catches up with the newest prompt.
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";
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;

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 = await pipe.generate(req.prompt, { seed: req.seed });
      post({ status: "image", data: { rgb: out.rgb, timings: out.timings, seed: req.seed, prompt: req.prompt, id: req.id, skipped: req.skipped } });
    } catch (e) {
      post({ status: "error", data: String(e?.message ?? e) });
    }
  }
  busy = false;
}

let skipped = 0;
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, { cacheName: "jeveration-webgpu" }), {
        ort, device: "webgpu", progress: (e) => post(e),
      });
      post({ status: "ready", data: { seconds: (performance.now() - t0) / 1000 } });
    }
    if (type === "generate") {
      if (pending) skipped++;
      pending = { ...data, skipped };
      drain();
    }
  } catch (e) {
    post({ status: "error", data: String(e?.message ?? e) });
  }
};