webslm 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/ai-sdk/index.d.ts +81 -0
  4. package/dist/ai-sdk/index.js +90 -0
  5. package/dist/ai-sdk/language-model.d.ts +77 -0
  6. package/dist/ai-sdk/language-model.js +422 -0
  7. package/dist/ai-sdk/loader.d.ts +54 -0
  8. package/dist/ai-sdk/loader.js +170 -0
  9. package/dist/ai-sdk/output.d.ts +43 -0
  10. package/dist/ai-sdk/output.js +152 -0
  11. package/dist/ai-sdk/prompt.d.ts +21 -0
  12. package/dist/ai-sdk/prompt.js +111 -0
  13. package/dist/async-queue.d.ts +22 -0
  14. package/dist/async-queue.js +70 -0
  15. package/dist/cache/cache-api.d.ts +29 -0
  16. package/dist/cache/cache-api.js +115 -0
  17. package/dist/cache/index.d.ts +21 -0
  18. package/dist/cache/index.js +42 -0
  19. package/dist/cache/memory.d.ts +12 -0
  20. package/dist/cache/memory.js +61 -0
  21. package/dist/cache/models.d.ts +67 -0
  22. package/dist/cache/models.js +107 -0
  23. package/dist/cache/node-fs.d.ts +21 -0
  24. package/dist/cache/node-fs.js +147 -0
  25. package/dist/cache/opfs.d.ts +69 -0
  26. package/dist/cache/opfs.js +181 -0
  27. package/dist/cache/store.d.ts +53 -0
  28. package/dist/cache/store.js +64 -0
  29. package/dist/cache-management.d.ts +23 -0
  30. package/dist/cache-management.js +58 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +55 -0
  33. package/dist/client.d.ts +61 -0
  34. package/dist/client.js +256 -0
  35. package/dist/curated.d.ts +22 -0
  36. package/dist/curated.js +53 -0
  37. package/dist/download.d.ts +51 -0
  38. package/dist/download.js +289 -0
  39. package/dist/engine.d.ts +54 -0
  40. package/dist/engine.js +510 -0
  41. package/dist/errors.d.ts +81 -0
  42. package/dist/errors.js +89 -0
  43. package/dist/hub.d.ts +185 -0
  44. package/dist/hub.js +409 -0
  45. package/dist/index.d.ts +37 -0
  46. package/dist/index.js +41 -0
  47. package/dist/models.d.ts +225 -0
  48. package/dist/models.js +730 -0
  49. package/dist/node-pool-worker.d.ts +6 -0
  50. package/dist/node-pool-worker.js +32 -0
  51. package/dist/node-web-worker.d.ts +23 -0
  52. package/dist/node-web-worker.js +84 -0
  53. package/dist/node-worker.d.ts +2 -0
  54. package/dist/node-worker.js +9 -0
  55. package/dist/pool-worker.d.ts +36 -0
  56. package/dist/pool-worker.js +30 -0
  57. package/dist/pool.d.ts +17 -0
  58. package/dist/pool.js +41 -0
  59. package/dist/protocol.d.ts +246 -0
  60. package/dist/protocol.js +19 -0
  61. package/dist/runtime.d.ts +21 -0
  62. package/dist/runtime.js +53 -0
  63. package/dist/safetensors.d.ts +20 -0
  64. package/dist/safetensors.js +2 -0
  65. package/dist/simple.d.ts +310 -0
  66. package/dist/simple.js +553 -0
  67. package/dist/types.d.ts +412 -0
  68. package/dist/types.js +2 -0
  69. package/dist/wasm-flavour.d.ts +85 -0
  70. package/dist/wasm-flavour.js +169 -0
  71. package/dist/wasm.d.ts +34 -0
  72. package/dist/wasm.js +38 -0
  73. package/dist/worker.d.ts +6 -0
  74. package/dist/worker.js +11 -0
  75. package/package.json +92 -3
  76. package/wasm/relaxed/webslm_wasm.d.ts +325 -0
  77. package/wasm/relaxed/webslm_wasm.js +1899 -0
  78. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  79. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
  80. package/wasm/simd/webslm_wasm.d.ts +325 -0
  81. package/wasm/simd/webslm_wasm.js +1899 -0
  82. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  83. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
  84. package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
  85. package/wasm/threads/webslm_wasm.d.ts +357 -0
  86. package/wasm/threads/webslm_wasm.js +2100 -0
  87. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  88. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
package/dist/engine.js ADDED
@@ -0,0 +1,510 @@
1
+ /**
2
+ * The engine side of the worker protocol: owns the WebAssembly instance,
3
+ * the loaded models and their sessions, and answers {@link Request}s.
4
+ *
5
+ * It runs in a dedicated Worker in browsers, a `worker_threads` worker in
6
+ * Node, or on the calling thread when `worker: false`. One engine can hold
7
+ * several models, each with several sessions.
8
+ *
9
+ * A model keeps reading its source after the load: applying or removing a
10
+ * LoRA adapter reads the affected base matrices again. Reads of a `fetch`
11
+ * source are forwarded to the page under the request being served.
12
+ */
13
+ import { openStore } from "./cache/index.js";
14
+ import { prepareHubCheckpoint } from "./download.js";
15
+ import { WebslmError, abortError, deserializeError, serializeError } from "./errors.js";
16
+ import { SAFETENSORS_INDEX } from "./hub.js";
17
+ import { scoreTransferables } from "./protocol.js";
18
+ import { installNodeWebWorker, nodePoolAvailable } from "./node-web-worker.js";
19
+ import { installPoolWorkerFactory } from "./pool.js";
20
+ import { isNode, now, yieldToEventLoop } from "./runtime.js";
21
+ import { defaultThreadCount, readFlavourModule, resolveFlavour, selectWasmFlavour, } from "./wasm-flavour.js";
22
+ let wasmReady;
23
+ /**
24
+ * Instantiates the WebAssembly module once per realm (later calls share it,
25
+ * whatever their options), and for the `threads` flavour starts its pool of
26
+ * workers.
27
+ */
28
+ export function initEngineWasm(options = {}) {
29
+ wasmReady ??= (async () => {
30
+ let preferred = options.flavour ?? selectWasmFlavour();
31
+ if (isNode() && preferred === "threads") {
32
+ if (!(await nodePoolAvailable())) {
33
+ if (options.flavour === "threads") {
34
+ throw new WebslmError("INVALID_ARGUMENT", "the threads build runs from the compiled package (dist/) only");
35
+ }
36
+ preferred = "relaxed";
37
+ }
38
+ else {
39
+ // The threads bindings expect a Web Worker environment, even to load.
40
+ await installNodeWebWorker();
41
+ }
42
+ }
43
+ const { flavour, bindings, note } = await resolveFlavour(preferred, options.flavour !== undefined);
44
+ let source = options.source;
45
+ // Node's fetch cannot read file: URLs.
46
+ if (source === undefined && isNode())
47
+ source = await readFlavourModule(flavour);
48
+ await bindings.default(source === undefined ? undefined : { module_or_path: source });
49
+ let threads = 1;
50
+ if (flavour === "threads" && bindings.startThreadPool !== undefined) {
51
+ threads = options.threads ?? (await defaultThreadCount());
52
+ installPoolWorkerFactory();
53
+ await bindings.startThreadPool(threads);
54
+ }
55
+ return { bindings, flavour, threads, ...(note === undefined ? {} : { note }) };
56
+ })();
57
+ wasmReady.catch(() => {
58
+ wasmReady = undefined;
59
+ });
60
+ return wasmReady;
61
+ }
62
+ const FLAVOUR_NAMES = {
63
+ simd: "SIMD128",
64
+ relaxed: "relaxed SIMD",
65
+ threads: "relaxed SIMD",
66
+ };
67
+ /**
68
+ * Human-readable CPU backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"` or
69
+ * `"CPU (wasm, SIMD128, 1 thread, deterministic, f32 activations)"`.
70
+ */
71
+ export function describeCpu(cpu, activations = "quantized") {
72
+ const threads = cpu.threads === 1 ? "1 thread" : `${cpu.threads} threads`;
73
+ const mode = cpu.deterministic ? ", deterministic" : "";
74
+ const precision = activations === "f32" ? ", f32 activations" : "";
75
+ return `CPU (wasm, ${FLAVOUR_NAMES[cpu.flavour]}, ${threads}${mode}${precision})`;
76
+ }
77
+ export class Engine {
78
+ #host;
79
+ #models = new Map();
80
+ #controllers = new Map();
81
+ #pendingReads = new Map();
82
+ #nextModel = 1;
83
+ #nextSession = 1;
84
+ #nextRead = 1;
85
+ constructor(host) {
86
+ this.#host = host;
87
+ }
88
+ /** Handles one message from the page. Answers are posted through the host. */
89
+ handle(request) {
90
+ if (request.type === "abort") {
91
+ this.#controllers.get(request.target)?.abort();
92
+ return;
93
+ }
94
+ if (request.type === "readResult") {
95
+ const pending = this.#pendingReads.get(request.readId);
96
+ if (pending === undefined)
97
+ return;
98
+ this.#pendingReads.delete(request.readId);
99
+ if (request.error !== undefined)
100
+ pending.reject(deserializeError(request.error));
101
+ else
102
+ pending.resolve(request.bytes ?? null);
103
+ return;
104
+ }
105
+ const controller = new AbortController();
106
+ this.#controllers.set(request.id, controller);
107
+ this.#dispatch(request, controller.signal)
108
+ .then(([value, transfer]) => this.#host.post({ type: "result", id: request.id, value }, transfer), (error) => {
109
+ const err = controller.signal.aborted ? abortError(controller.signal) : error;
110
+ this.#host.post({ type: "error", id: request.id, error: serializeError(err) });
111
+ })
112
+ .finally(() => this.#controllers.delete(request.id));
113
+ }
114
+ async #dispatch(request, signal) {
115
+ switch (request.type) {
116
+ case "load":
117
+ return [await this.#load(request.id, request.source, request.adapter, request.options, signal)];
118
+ case "applyAdapter":
119
+ return [await this.#applyAdapter(request, signal)];
120
+ case "removeAdapter":
121
+ return [await this.#removeAdapter(request.id, request.model, signal)];
122
+ case "chat":
123
+ case "generate":
124
+ return [await this.#generate(request, signal)];
125
+ case "createSession": {
126
+ const model = this.#model(request.model);
127
+ const id = this.#nextSession++;
128
+ model.sessions.set(id, model.wasm.createSession());
129
+ return [id];
130
+ }
131
+ case "forkSession": {
132
+ const model = this.#model(request.model);
133
+ const fork = this.#session(request.model, request.session).fork();
134
+ const id = this.#nextSession++;
135
+ model.sessions.set(id, fork);
136
+ return [id];
137
+ }
138
+ case "scoreContinuations": {
139
+ const session = this.#session(request.model, request.session);
140
+ const scores = (await session.scoreContinuations(request.prefix, JSON.stringify(request.continuations)));
141
+ return [scores, scores.map((a) => a.buffer)];
142
+ }
143
+ case "shiftContext": {
144
+ const session = this.#session(request.model, request.session);
145
+ return [(await session.shiftContext(request.keep, request.drop))];
146
+ }
147
+ case "disposeSession": {
148
+ const model = this.#model(request.model);
149
+ model.sessions.get(request.session)?.free();
150
+ model.sessions.delete(request.session);
151
+ return [true];
152
+ }
153
+ case "score":
154
+ case "step": {
155
+ const session = this.#session(request.model, request.session);
156
+ const options = JSON.stringify(request.options);
157
+ const raw = (await (request.type === "score"
158
+ ? session.score(request.ids, options)
159
+ : session.step(request.token, options)));
160
+ return [raw, scoreTransferables(raw)];
161
+ }
162
+ case "truncate": {
163
+ const session = this.#session(request.model, request.session);
164
+ session.truncate(request.length);
165
+ return [session.length];
166
+ }
167
+ case "reset": {
168
+ const model = this.#model(request.model);
169
+ if (request.session === undefined)
170
+ model.wasm.reset();
171
+ else
172
+ this.#session(request.model, request.session).reset();
173
+ return [0];
174
+ }
175
+ case "tokenize": {
176
+ const ids = this.#model(request.model).wasm.tokenize(request.text, request.addSpecialTokens);
177
+ return [ids, [ids.buffer]];
178
+ }
179
+ case "detokenize":
180
+ return [this.#model(request.model).wasm.detokenize(request.ids, request.skipSpecialTokens)];
181
+ case "renderChat":
182
+ return [
183
+ this.#model(request.model).wasm.renderChat(JSON.stringify(request.messages), JSON.stringify(request.templateKwargs)),
184
+ ];
185
+ case "unload": {
186
+ const model = this.#models.get(request.model);
187
+ if (model !== undefined) {
188
+ for (const session of model.sessions.values())
189
+ session.free();
190
+ model.wasm.free();
191
+ this.#models.delete(request.model);
192
+ }
193
+ return [true];
194
+ }
195
+ default:
196
+ throw new WebslmError("INVALID_ARGUMENT", `unexpected request "${request.type}"`);
197
+ }
198
+ }
199
+ #model(id) {
200
+ const model = this.#models.get(id);
201
+ if (model === undefined)
202
+ throw new WebslmError("DISPOSED", "this model was unloaded");
203
+ return model;
204
+ }
205
+ #session(modelId, sessionId) {
206
+ const session = this.#model(modelId).sessions.get(sessionId);
207
+ if (session === undefined)
208
+ throw new WebslmError("DISPOSED", "this session was disposed");
209
+ return session;
210
+ }
211
+ async #generate(request, signal) {
212
+ const model = this.#model(request.model);
213
+ const target = request.session === undefined ? model.wasm : this.#session(request.model, request.session);
214
+ const started = now();
215
+ let first;
216
+ let last = started;
217
+ const onDelta = async (text, token, info) => {
218
+ last = now();
219
+ first ??= last;
220
+ this.#host.post({
221
+ type: "delta",
222
+ id: request.id,
223
+ text,
224
+ token,
225
+ ...(info?.logprob === undefined ? {} : { logprob: info.logprob }),
226
+ ...(info?.topLogprobs === undefined ? {} : { topLogprobs: info.topLogprobs }),
227
+ ...(info?.forced === true ? { forced: true } : {}),
228
+ });
229
+ // Let `abort` messages in before the next token.
230
+ await yieldToEventLoop();
231
+ return !signal.aborted;
232
+ };
233
+ // The prompt runs in pieces, so that an abort can stop a long prefill.
234
+ const onPrefill = async (done, total) => {
235
+ this.#host.post({ type: "prefill", id: request.id, done, total });
236
+ await yieldToEventLoop();
237
+ return !signal.aborted;
238
+ };
239
+ const options = JSON.stringify(request.options);
240
+ const summary = (await (request.type === "chat"
241
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
242
+ : target.generate(request.prompt, options, onDelta, onPrefill)));
243
+ const decoded = summary.generatedTokens - 1;
244
+ const decodeSeconds = first === undefined ? 0 : (last - first) / 1000;
245
+ return {
246
+ ...summary,
247
+ timeToFirstTokenMs: first === undefined ? 0 : first - started,
248
+ tokensPerSecond: decoded > 0 && decodeSeconds > 0 ? decoded / decodeSeconds : 0,
249
+ };
250
+ }
251
+ /**
252
+ * Opens a source: downloads a hub checkpoint (or adapter) into the cache,
253
+ * hashes files held by the page, or forwards reads to the page. `active`
254
+ * names the request reads are served for (it changes after the load).
255
+ */
256
+ async #openSource(active, source, cacheDir, progress, bindings, target) {
257
+ const { Sha256Hasher } = bindings;
258
+ const sizes = new Map();
259
+ const hashes = new Map();
260
+ switch (source.kind) {
261
+ case "hub": {
262
+ const store = await openStore(cacheDir === undefined ? {} : { cacheDir });
263
+ const hubOptions = {
264
+ store,
265
+ signal: active.signal,
266
+ onProgress: progress,
267
+ createHasher: () => new Sha256Hasher(),
268
+ ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
269
+ ...(source.token === undefined ? {} : { token: source.token }),
270
+ };
271
+ const checkpoint = await prepareHubCheckpoint(source.repo, source.revision, hubOptions);
272
+ for (const [file, info] of Object.entries(checkpoint.info)) {
273
+ sizes.set(file, info.size);
274
+ if (info.sha256 !== undefined)
275
+ hashes.set(file, info.sha256);
276
+ }
277
+ return {
278
+ read: checkpoint.read,
279
+ list: [...checkpoint.files],
280
+ sizes,
281
+ hashes,
282
+ repo: checkpoint.repo,
283
+ revision: checkpoint.sha,
284
+ fromCache: checkpoint.fromCache,
285
+ };
286
+ }
287
+ case "files": {
288
+ const files = source.files;
289
+ for (const [name, data] of Object.entries(files)) {
290
+ sizes.set(name, fileSize(data));
291
+ if (active.signal.aborted)
292
+ throw abortError(active.signal);
293
+ hashes.set(name, await hashFile(data, () => new Sha256Hasher()));
294
+ }
295
+ return {
296
+ read: async (path, start, end) => {
297
+ const data = files[path];
298
+ return data === undefined ? null : readFileData(data, start, end);
299
+ },
300
+ list: Object.keys(files),
301
+ sizes,
302
+ hashes,
303
+ fromCache: true,
304
+ };
305
+ }
306
+ case "fetch":
307
+ return {
308
+ read: (path, start, end) => this.#remoteRead(active.id, path, start, end, target),
309
+ sizes,
310
+ hashes,
311
+ fromCache: false,
312
+ };
313
+ }
314
+ }
315
+ /**
316
+ * The engine-side source of `opened`: honours the active request's
317
+ * signal and reports the weight bytes read as the `"load"` phase.
318
+ */
319
+ #jsSource(opened, active, progress, bindings) {
320
+ const weightFiles = (opened.list ?? []).filter((f) => f.endsWith(".safetensors"));
321
+ const weightTotal = weightFiles.reduce((n, f) => n + (opened.sizes.get(f) ?? 0), 0);
322
+ let weightRead = 0;
323
+ let lastReport = 0;
324
+ const read = async (path, start, end) => {
325
+ if (active.signal.aborted)
326
+ throw abortError(active.signal);
327
+ const bytes = await opened.read(path, start, end);
328
+ if (bytes !== null && path.endsWith(".safetensors") && path !== SAFETENSORS_INDEX) {
329
+ weightRead += bytes.length;
330
+ const t = now();
331
+ if (t - lastReport > 50) {
332
+ lastReport = t;
333
+ progress({
334
+ phase: "load",
335
+ file: path,
336
+ loadedBytes: weightRead,
337
+ totalBytes: weightTotal,
338
+ overallLoadedBytes: weightRead,
339
+ overallTotalBytes: weightTotal,
340
+ });
341
+ }
342
+ }
343
+ return bytes;
344
+ };
345
+ const list = opened.list;
346
+ return { source: new bindings.JsSource(read, list === undefined ? undefined : () => list), weightTotal };
347
+ }
348
+ async #load(requestId, source, adapterSource, options, signal) {
349
+ const started = now();
350
+ const active = { id: requestId, signal };
351
+ const progress = (p) => this.#host.post({ type: "progress", id: active.id, progress: p });
352
+ const engine = await initEngineWasm({
353
+ ...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
354
+ ...(options.threads === undefined ? {} : { threads: options.threads }),
355
+ });
356
+ const { WasmModel } = engine.bindings;
357
+ const opened = await this.#openSource(active, source, options.cacheDir, progress, engine.bindings);
358
+ const adapter = adapterSource === undefined
359
+ ? undefined
360
+ : await this.#openSource(active, adapterSource, options.cacheDir, progress, engine.bindings, "adapter");
361
+ const { source: jsSource, weightTotal } = this.#jsSource(opened, active, progress, engine.bindings);
362
+ const wasm = await WasmModel.load(jsSource, JSON.stringify({
363
+ format: options.quant,
364
+ device: options.device ?? "auto",
365
+ ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
366
+ ...(options.deterministic === true ? { deterministic: true } : {}),
367
+ ...(options.activations === undefined ? {} : { activations: options.activations }),
368
+ ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
369
+ }), adapter === undefined ? undefined : this.#jsSource(adapter, active, () => { }, engine.bindings).source);
370
+ if (signal.aborted) {
371
+ wasm.free();
372
+ throw abortError(signal);
373
+ }
374
+ const raw = wasm.info();
375
+ const files = raw.files.map((f) => {
376
+ const sha256 = f.sha256 ?? opened.hashes.get(f.file);
377
+ const size = opened.sizes.get(f.file);
378
+ return {
379
+ file: f.file,
380
+ bytesRead: f.bytesRead,
381
+ ...(sha256 === undefined || sha256 === null ? {} : { sha256 }),
382
+ ...(size === undefined ? {} : { sizeBytes: size }),
383
+ };
384
+ });
385
+ const { weightFormat, kernels, deterministic, threads, backend, deviceNote, adapter: gpuAdapter, lora, files: _files, ...rest } = raw;
386
+ void _files;
387
+ const cpu = {
388
+ flavour: engine.flavour,
389
+ kernels,
390
+ threads,
391
+ deterministic,
392
+ ...(engine.note === undefined ? {} : { flavourNote: engine.note }),
393
+ };
394
+ const gpu = backend === "webgpu";
395
+ const { repo, revision } = opened;
396
+ const info = {
397
+ ...rest,
398
+ ...(repo === undefined ? {} : { repo }),
399
+ ...(revision === undefined ? {} : { revision }),
400
+ device: gpu ? "webgpu" : "cpu",
401
+ backend: gpu
402
+ ? `WebGPU${gpuAdapter === undefined ? "" : ` (${gpuAdapter})`}`
403
+ : describeCpu(cpu, rest.activations),
404
+ ...(gpu ? {} : { cpu }),
405
+ ...(deviceNote === undefined ? {} : { deviceNote }),
406
+ ...(lora === undefined || adapter === undefined ? {} : { lora: withOrigin(lora, adapter) }),
407
+ quant: weightFormat,
408
+ files,
409
+ fromCache: opened.fromCache,
410
+ loadTimeMs: now() - started,
411
+ };
412
+ const id = this.#nextModel++;
413
+ this.#models.set(id, { wasm, sessions: new Map(), info, active, adapterQueue: Promise.resolve() });
414
+ progress({
415
+ phase: "ready",
416
+ loadedBytes: weightTotal,
417
+ totalBytes: weightTotal,
418
+ overallLoadedBytes: weightTotal,
419
+ overallTotalBytes: weightTotal,
420
+ });
421
+ return { model: id, info };
422
+ }
423
+ /**
424
+ * Runs `run` once the model's previous adapter change is done, with the
425
+ * model's source reads attributed to request `id`.
426
+ */
427
+ #exclusive(model, id, signal, run) {
428
+ const next = model.adapterQueue.then(async () => {
429
+ model.active.id = id;
430
+ model.active.signal = signal;
431
+ return run();
432
+ });
433
+ model.adapterQueue = next.catch(() => { });
434
+ return next;
435
+ }
436
+ async #applyAdapter(request, signal) {
437
+ const model = this.#model(request.model);
438
+ return this.#exclusive(model, request.id, signal, async () => {
439
+ const engine = await initEngineWasm();
440
+ const progress = (p) => this.#host.post({ type: "progress", id: request.id, progress: p });
441
+ const active = { id: request.id, signal };
442
+ const opened = await this.#openSource(active, request.source, request.options.cacheDir, progress, engine.bindings, "adapter");
443
+ const adapter = this.#jsSource(opened, active, () => { }, engine.bindings).source;
444
+ const options = JSON.stringify(request.options.scale === undefined ? {} : { scale: request.options.scale });
445
+ const lora = withOrigin((await model.wasm.applyAdapter(adapter, options)), opened);
446
+ model.info = { ...model.info, lora };
447
+ return lora;
448
+ });
449
+ }
450
+ async #removeAdapter(id, modelId, signal) {
451
+ const model = this.#model(modelId);
452
+ return this.#exclusive(model, id, signal, async () => {
453
+ const removed = (await model.wasm.removeAdapter());
454
+ const { lora, ...info } = model.info;
455
+ model.info = info;
456
+ return removed === null ? null : (lora ?? removed);
457
+ });
458
+ }
459
+ #remoteRead(requestId, path, start, end, target) {
460
+ const readId = this.#nextRead++;
461
+ return new Promise((resolve, reject) => {
462
+ this.#pendingReads.set(readId, { resolve, reject });
463
+ this.#host.post({
464
+ type: "read",
465
+ id: requestId,
466
+ readId,
467
+ path,
468
+ ...(start === undefined ? {} : { start }),
469
+ ...(end === undefined ? {} : { end }),
470
+ ...(target === undefined ? {} : { target }),
471
+ });
472
+ });
473
+ }
474
+ }
475
+ /** `lora` with the hub repository and revision it came from, when known. */
476
+ function withOrigin(lora, source) {
477
+ return {
478
+ ...lora,
479
+ ...(source.repo === undefined ? {} : { repo: source.repo }),
480
+ ...(source.revision === undefined ? {} : { revision: source.revision }),
481
+ };
482
+ }
483
+ function fileSize(data) {
484
+ return data instanceof Blob ? data.size : data.byteLength;
485
+ }
486
+ async function readFileData(data, start, end) {
487
+ const size = fileSize(data);
488
+ const s = start ?? 0;
489
+ const e = end ?? size;
490
+ if (s < 0 || e < s || e > size)
491
+ throw new RangeError(`range ${s}..${e} is outside the ${size}-byte file`);
492
+ if (data instanceof Blob)
493
+ return new Uint8Array(await data.slice(s, e).arrayBuffer());
494
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
495
+ return bytes.subarray(s, e);
496
+ }
497
+ const HASH_CHUNK = 16 * 1024 * 1024;
498
+ async function hashFile(data, createHasher) {
499
+ const hasher = createHasher();
500
+ try {
501
+ const size = fileSize(data);
502
+ for (let offset = 0; offset < size; offset += HASH_CHUNK) {
503
+ hasher.update(await readFileData(data, offset, Math.min(size, offset + HASH_CHUNK)));
504
+ }
505
+ return hasher.finish();
506
+ }
507
+ finally {
508
+ hasher.free();
509
+ }
510
+ }
@@ -0,0 +1,81 @@
1
+ /** Typed errors raised by webslm. */
2
+ /** Stable error codes. */
3
+ export type WebslmErrorCode =
4
+ /** The operation was cancelled through an `AbortSignal` or `stop()`. */
5
+ "ABORTED"
6
+ /** A repository, revision or file does not exist. */
7
+ | "NOT_FOUND"
8
+ /** The repository is gated or private: a Hugging Face token with access is needed. */
9
+ | "UNAUTHORIZED"
10
+ /** A network request failed or returned an unexpected status. */
11
+ | "NETWORK"
12
+ /** The checkpoint's architecture (or format) is not supported by this build. */
13
+ | "UNSUPPORTED_MODEL"
14
+ /** The requested device is not available. */
15
+ | "UNSUPPORTED_DEVICE"
16
+ /** Malformed checkpoint files (config, safetensors header, tokenizer...). */
17
+ | "INVALID_CHECKPOINT"
18
+ /** A LoRA adapter that is malformed or does not fit the model. */
19
+ | "INVALID_ADAPTER"
20
+ /** A chat call on a checkpoint without a chat template. */
21
+ | "NO_CHAT_TEMPLATE"
22
+ /** The call does not fit the session state (e.g. rewinding a recurrent model). */
23
+ | "INVALID_STATE"
24
+ /** Bad arguments or options. */
25
+ | "INVALID_ARGUMENT"
26
+ /** A session is already running a call. */
27
+ | "BUSY"
28
+ /** The model was unloaded. */
29
+ | "DISPOSED"
30
+ /** Reading a checkpoint file failed. */
31
+ | "READ_FAILED"
32
+ /** A downloaded file does not match its expected SHA-256. */
33
+ | "INTEGRITY"
34
+ /** The local cache (OPFS, Cache API or directory) failed. */
35
+ | "CACHE"
36
+ /** The worker crashed or could not start. */
37
+ | "WORKER"
38
+ /**
39
+ * The model does not fit in GPU memory, by the estimate made before loading or because the
40
+ * device failed an allocation. `device: "auto"` falls back to the CPU instead (see `deviceNote`).
41
+ */
42
+ | "GPU_OUT_OF_MEMORY"
43
+ /** The GPU device was lost (driver reset, GPU removed): load the model again. */
44
+ | "GPU_DEVICE_LOST"
45
+ /** Any other error the GPU device reported (validation, internal). */
46
+ | "GPU_ERROR"
47
+ /** Any other engine failure. */
48
+ | "ENGINE";
49
+ /** Plain-data form of an error, as sent between the worker and the page. */
50
+ export interface SerializedError {
51
+ readonly code: WebslmErrorCode;
52
+ readonly message: string;
53
+ }
54
+ /** Every error webslm throws on purpose. Check `code` rather than `message`. */
55
+ export declare class WebslmError extends Error {
56
+ readonly name = "WebslmError";
57
+ readonly code: WebslmErrorCode;
58
+ constructor(code: WebslmErrorCode, message: string, options?: {
59
+ cause?: unknown;
60
+ });
61
+ /** Whether `error` is a {@link WebslmError}, optionally with the given code. */
62
+ static is(error: unknown, code?: WebslmErrorCode): error is WebslmError;
63
+ toJSON(): SerializedError;
64
+ }
65
+ /** Whether `code` is a known error code. */
66
+ export declare function isErrorCode(code: unknown): code is WebslmErrorCode;
67
+ /**
68
+ * Converts anything thrown (engine errors carrying a `code`, DOM exceptions,
69
+ * plain errors) into a {@link WebslmError}.
70
+ */
71
+ export declare function toWebslmError(error: unknown, fallback?: WebslmErrorCode): WebslmError;
72
+ /** Serializes an error for `postMessage`. */
73
+ export declare function serializeError(error: unknown): SerializedError;
74
+ /** Rebuilds an error received from the worker. */
75
+ export declare function deserializeError(error: SerializedError): WebslmError;
76
+ /** The error to throw when `signal` is aborted. */
77
+ export declare function abortError(signal?: AbortSignal): WebslmError;
78
+ /** Whether `signal` is aborted (a function, so checks are never narrowed away). */
79
+ export declare function isAborted(signal?: AbortSignal): boolean;
80
+ /** Throws {@link abortError} when `signal` is aborted. */
81
+ export declare function throwIfAborted(signal?: AbortSignal): void;
package/dist/errors.js ADDED
@@ -0,0 +1,89 @@
1
+ /** Typed errors raised by webslm. */
2
+ const CODES = new Set([
3
+ "ABORTED",
4
+ "NOT_FOUND",
5
+ "UNAUTHORIZED",
6
+ "NETWORK",
7
+ "UNSUPPORTED_MODEL",
8
+ "UNSUPPORTED_DEVICE",
9
+ "INVALID_CHECKPOINT",
10
+ "INVALID_ADAPTER",
11
+ "NO_CHAT_TEMPLATE",
12
+ "INVALID_STATE",
13
+ "INVALID_ARGUMENT",
14
+ "BUSY",
15
+ "DISPOSED",
16
+ "READ_FAILED",
17
+ "INTEGRITY",
18
+ "CACHE",
19
+ "WORKER",
20
+ "GPU_OUT_OF_MEMORY",
21
+ "GPU_DEVICE_LOST",
22
+ "GPU_ERROR",
23
+ "ENGINE",
24
+ ]);
25
+ /** Every error webslm throws on purpose. Check `code` rather than `message`. */
26
+ export class WebslmError extends Error {
27
+ name = "WebslmError";
28
+ code;
29
+ constructor(code, message, options) {
30
+ super(message, options);
31
+ this.code = code;
32
+ }
33
+ /** Whether `error` is a {@link WebslmError}, optionally with the given code. */
34
+ static is(error, code) {
35
+ return error instanceof WebslmError && (code === undefined || error.code === code);
36
+ }
37
+ toJSON() {
38
+ return { code: this.code, message: this.message };
39
+ }
40
+ }
41
+ /** Whether `code` is a known error code. */
42
+ export function isErrorCode(code) {
43
+ return typeof code === "string" && CODES.has(code);
44
+ }
45
+ /**
46
+ * Converts anything thrown (engine errors carrying a `code`, DOM exceptions,
47
+ * plain errors) into a {@link WebslmError}.
48
+ */
49
+ export function toWebslmError(error, fallback = "ENGINE") {
50
+ if (error instanceof WebslmError)
51
+ return error;
52
+ if (typeof error === "object" && error !== null) {
53
+ const { code, name, message } = error;
54
+ const text = typeof message === "string" ? message : String(error);
55
+ if (name === "AbortError")
56
+ return new WebslmError("ABORTED", text || "aborted", { cause: error });
57
+ if (name === "NotFoundError")
58
+ return new WebslmError("NOT_FOUND", text, { cause: error });
59
+ if (name === "QuotaExceededError")
60
+ return new WebslmError("CACHE", text, { cause: error });
61
+ if (isErrorCode(code))
62
+ return new WebslmError(code, text, { cause: error });
63
+ return new WebslmError(fallback, text, { cause: error });
64
+ }
65
+ return new WebslmError(fallback, String(error));
66
+ }
67
+ /** Serializes an error for `postMessage`. */
68
+ export function serializeError(error) {
69
+ return toWebslmError(error).toJSON();
70
+ }
71
+ /** Rebuilds an error received from the worker. */
72
+ export function deserializeError(error) {
73
+ return new WebslmError(isErrorCode(error.code) ? error.code : "ENGINE", error.message);
74
+ }
75
+ /** The error to throw when `signal` is aborted. */
76
+ export function abortError(signal) {
77
+ const reason = signal?.reason;
78
+ const message = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "aborted";
79
+ return new WebslmError("ABORTED", message, { cause: reason });
80
+ }
81
+ /** Whether `signal` is aborted (a function, so checks are never narrowed away). */
82
+ export function isAborted(signal) {
83
+ return signal?.aborted === true;
84
+ }
85
+ /** Throws {@link abortError} when `signal` is aborted. */
86
+ export function throwIfAborted(signal) {
87
+ if (signal?.aborted === true)
88
+ throw abortError(signal);
89
+ }