File size: 4,254 Bytes
48441eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// ONNX Runtime Web: downloads (cached in Cache Storage), sessions on WebGPU with a WASM fallback.

import * as ort from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/ort.all.min.mjs';

export { ort };

ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/';
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(8, navigator.hardwareConcurrency || 2) : 1;
ort.env.logLevel = 'error';

const CACHE = 'solstice-webgpu-models-v1';

export function hasWebGPU() {
  return typeof navigator !== 'undefined' && !!navigator.gpu;
}

export class HttpError extends Error {
  constructor(status, url) {
    super(status === 404 ? `not published yet (404): ${url}` : `HTTP ${status} fetching ${url}`);
    this.status = status;
  }
}

async function openCache() {
  try {
    return await caches.open(CACHE);
  } catch {
    return null;
  }
}

// Fetch a (large) file with progress callbacks, from Cache Storage when it is there.
export async function fetchBytes(url, onProgress = () => {}) {
  const cache = await openCache();
  if (cache) {
    try {
      const hit = await cache.match(url);
      if (hit) {
        const buf = new Uint8Array(await hit.arrayBuffer());
        onProgress(buf.length, buf.length, true);
        return buf;
      }
    } catch {
      // fall through to the network
    }
  }
  const res = await fetch(url);
  if (!res.ok) throw new HttpError(res.status, url);
  const total = parseInt(res.headers.get('content-length') || res.headers.get('x-linked-size') || '0', 10);
  const reader = res.body.getReader();
  const chunks = [];
  let received = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
    received += value.length;
    onProgress(received, total, false);
  }
  const out = new Uint8Array(received);
  let off = 0;
  for (const c of chunks) {
    out.set(c, off);
    off += c.length;
  }
  if (cache) {
    try {
      await cache.put(url, new Response(out, { headers: { 'content-type': 'application/octet-stream' } }));
    } catch (err) {
      console.warn('Could not cache', url, err);
    }
  }
  return out;
}

// Is the file there? (HEAD through the Hub's redirect; false on 404.)
export async function exists(url) {
  try {
    const cache = await openCache();
    if (cache && (await cache.match(url))) return true;
    const res = await fetch(url, { method: 'HEAD' });
    return res.ok;
  } catch {
    return false;
  }
}

export async function clearModelCache() {
  try {
    await caches.delete(CACHE);
  } catch {
    // nothing cached
  }
}

// Create a session: WebGPU first (unless wasmOnly or disabled), WASM if that fails.
export async function createSession(bytes, { wasmOnly = false, preferWebGPU = true } = {}) {
  const opts = { graphOptimizationLevel: 'all' };
  if (!wasmOnly && preferWebGPU && hasWebGPU()) {
    try {
      const session = await ort.InferenceSession.create(bytes, { ...opts, executionProviders: ['webgpu'] });
      return { session, backend: 'webgpu' };
    } catch (err) {
      console.warn('WebGPU session failed, falling back to WASM:', err);
    }
  }
  const session = await ort.InferenceSession.create(bytes, { ...opts, executionProviders: ['wasm'] });
  return { session, backend: 'wasm' };
}

// A float32 tensor that lives on the GPU, for inputs that stay the same across many runs (text conditioning,
// LoRA factors). Falls back to an ordinary CPU tensor.
export async function constTensor(backend, data, dims, type = 'float32') {
  if (backend === 'webgpu' && type === 'float32') {
    try {
      const device = await ort.env.webgpu.device;
      if (device) {
        const size = Math.ceil(data.byteLength / 16) * 16;
        const buffer = device.createBuffer({
          size,
          usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
        });
        device.queue.writeBuffer(buffer, 0, data.buffer, data.byteOffset, data.byteLength);
        return ort.Tensor.fromGpuBuffer(buffer, { dataType: 'float32', dims, dispose: () => buffer.destroy() });
      }
    } catch (err) {
      console.warn('GPU tensor upload failed; using a CPU tensor', err);
    }
  }
  return new ort.Tensor(type, data, dims);
}