webslm 0.0.0-stage → 0.2.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
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Downloads a Hub checkpoint into the cache, then serves reads from it.
3
+ *
4
+ * The first load resolves the revision to a commit sha, downloads every
5
+ * needed file fully (resuming partial files with `Range`), hashes it and
6
+ * checks the Hub's SHA-256 for LFS files. Later loads of the same revision
7
+ * read from the cache without any network request: a revision given as a
8
+ * commit sha, or a branch already resolved once (the cached ref is reused;
9
+ * delete the cached model to pick up new commits).
10
+ */
11
+ import { type CachedFileInfo } from "./cache/models.js";
12
+ import type { CacheStore } from "./cache/store.js";
13
+ import { type HubOptions } from "./hub.js";
14
+ import type { LoadProgress } from "./types.js";
15
+ /** Incremental hash (the engine's SHA-256, or `node:crypto` in tests). */
16
+ export interface Hasher {
17
+ update(bytes: Uint8Array): void;
18
+ /** Lowercase hex digest of everything fed so far; resets the hasher. */
19
+ finish(): string;
20
+ }
21
+ export interface HubDownloadOptions extends HubOptions {
22
+ readonly store: CacheStore;
23
+ readonly onProgress?: (progress: LoadProgress) => void;
24
+ readonly createHasher?: () => Hasher;
25
+ /** Attempts per file when the connection drops (default 4). */
26
+ readonly retries?: number;
27
+ /** Minimum delay between two progress events of the same file, in ms (default 50). */
28
+ readonly progressIntervalMs?: number;
29
+ }
30
+ /** A checkpoint ready to be read from the cache. */
31
+ export interface CachedCheckpoint {
32
+ readonly repo: string;
33
+ readonly sha: string;
34
+ /** Files of the checkpoint, as the engine names them. */
35
+ readonly files: readonly string[];
36
+ readonly info: Readonly<Record<string, CachedFileInfo>>;
37
+ /** Whether nothing had to be downloaded. */
38
+ readonly fromCache: boolean;
39
+ /** Reads a file or a range of it; `null` for files the checkpoint does not have. */
40
+ read(file: string, start?: number, end?: number): Promise<Uint8Array | null>;
41
+ }
42
+ /** Makes `repo@revision` available in `options.store` and returns a reader over it. */
43
+ export declare function prepareHubCheckpoint(repoId: string, revision: string | undefined, options: HubDownloadOptions): Promise<CachedCheckpoint>;
44
+ /** Downloads `url` into `path`, resuming from the bytes already stored. */
45
+ export declare function downloadFile(url: string, path: string, expected: {
46
+ readonly size?: number;
47
+ readonly sha256?: string;
48
+ }, options: HubDownloadOptions, onBytes: (loaded: number) => void): Promise<{
49
+ size: number;
50
+ sha256?: string;
51
+ }>;
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Downloads a Hub checkpoint into the cache, then serves reads from it.
3
+ *
4
+ * The first load resolves the revision to a commit sha, downloads every
5
+ * needed file fully (resuming partial files with `Range`), hashes it and
6
+ * checks the Hub's SHA-256 for LFS files. Later loads of the same revision
7
+ * read from the cache without any network request: a revision given as a
8
+ * commit sha, or a branch already resolved once (the cached ref is reused;
9
+ * delete the cached model to pick up new commits).
10
+ */
11
+ import { checkRepoId, filePath, readManifest, readRef, writeManifest, writeRef, } from "./cache/models.js";
12
+ import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
13
+ import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, selectCheckpointFiles, } from "./hub.js";
14
+ const SHA_PATTERN = /^[0-9a-f]{40}$/;
15
+ /** Makes `repo@revision` available in `options.store` and returns a reader over it. */
16
+ export async function prepareHubCheckpoint(repoId, revision, options) {
17
+ const repo = checkRepoId(repoId);
18
+ const rev = revision ?? "main";
19
+ const { store } = options;
20
+ const emit = options.onProgress ?? (() => { });
21
+ // Offline path: a known sha whose files are all complete.
22
+ const knownSha = SHA_PATTERN.test(rev) ? rev : await readRef(store, repo, rev);
23
+ if (knownSha !== undefined) {
24
+ const manifest = await readManifest(store, repo, knownSha);
25
+ if (manifest?.complete === true && (await filesPresent(store, manifest))) {
26
+ emitCachedProgress(manifest, emit);
27
+ return reader(store, manifest, true);
28
+ }
29
+ }
30
+ emit({ phase: "resolve", loadedBytes: 0, totalBytes: 0, overallLoadedBytes: 0, overallTotalBytes: 0 });
31
+ const revisionInfo = await fetchRevision(repo, rev, options);
32
+ const { sha } = revisionInfo;
33
+ const hubFiles = new Map(revisionInfo.files.map((f) => [f.name, f]));
34
+ const names = revisionInfo.files.map((f) => f.name);
35
+ return withLock(`webslm:${repo}@${sha}`, async () => {
36
+ const previous = await readManifest(store, repo, sha);
37
+ const done = { ...previous?.files };
38
+ let downloaded = false;
39
+ const download = async (file, progress) => {
40
+ const hubFile = hubFiles.get(file);
41
+ const known = done[file];
42
+ const path = filePath(repo, sha, file);
43
+ if (known?.complete === true && (await store.size(path)) === known.size) {
44
+ progress(known.size);
45
+ return;
46
+ }
47
+ downloaded = true;
48
+ const expected = {};
49
+ if (hubFile?.size !== undefined)
50
+ expected.size = hubFile.size;
51
+ if (hubFile?.lfsSha256 !== undefined)
52
+ expected.sha256 = hubFile.lfsSha256;
53
+ const result = await downloadFile(fileUrl(repo, sha, file, options.hubUrl), path, expected, options, progress);
54
+ const entry = {
55
+ size: result.size,
56
+ complete: true,
57
+ };
58
+ if (result.sha256 !== undefined)
59
+ entry.sha256 = result.sha256;
60
+ done[file] = entry;
61
+ await writeManifest(store, manifestOf(repo, sha, done, false));
62
+ };
63
+ // The index decides which shards are needed: fetch it first.
64
+ let index;
65
+ if (names.includes(SAFETENSORS_INDEX)) {
66
+ await download(SAFETENSORS_INDEX, () => { });
67
+ const bytes = await store.read(filePath(repo, sha, SAFETENSORS_INDEX));
68
+ try {
69
+ index = JSON.parse(new TextDecoder().decode(bytes));
70
+ }
71
+ catch (error) {
72
+ throw new WebslmError("INVALID_CHECKPOINT", `invalid ${SAFETENSORS_INDEX}`, { cause: error });
73
+ }
74
+ }
75
+ const selected = selectCheckpointFiles(names, index);
76
+ if (selected.weights.length === 0) {
77
+ throw new WebslmError("UNSUPPORTED_MODEL", `${repo}@${rev} has no safetensors weights`);
78
+ }
79
+ if (!names.includes("config.json") && !isAdapterListing(names)) {
80
+ throw new WebslmError("INVALID_CHECKPOINT", `${repo}@${rev} has no config.json`);
81
+ }
82
+ const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];
83
+ const sizes = files.map((f) => hubFiles.get(f)?.size ?? 0);
84
+ const overallTotal = sizes.reduce((a, b) => a + b, 0);
85
+ let finished = 0;
86
+ const interval = options.progressIntervalMs ?? 50;
87
+ for (const [i, file] of files.entries()) {
88
+ const total = sizes[i] ?? 0;
89
+ let last = 0;
90
+ const wasCached = done[file]?.complete === true;
91
+ const report = (loaded, force = false) => {
92
+ const t = Date.now();
93
+ if (!force && t - last < interval && loaded < total)
94
+ return;
95
+ last = t;
96
+ emit({
97
+ phase: "download",
98
+ file,
99
+ loadedBytes: loaded,
100
+ totalBytes: total,
101
+ overallLoadedBytes: finished + loaded,
102
+ overallTotalBytes: overallTotal,
103
+ cached: wasCached,
104
+ });
105
+ };
106
+ report(0, true);
107
+ await download(file, (loaded) => report(loaded));
108
+ report(total, true);
109
+ finished += total;
110
+ }
111
+ // Keep only the files of this checkpoint in the manifest.
112
+ const manifestFiles = {};
113
+ for (const file of files) {
114
+ const info = done[file];
115
+ if (info !== undefined)
116
+ manifestFiles[file] = info;
117
+ }
118
+ const manifest = manifestOf(repo, sha, manifestFiles, true);
119
+ await writeManifest(store, manifest);
120
+ if (rev !== sha)
121
+ await writeRef(store, repo, rev, sha);
122
+ return reader(store, manifest, !downloaded);
123
+ });
124
+ }
125
+ function manifestOf(repo, sha, files, complete) {
126
+ return { version: 1, repo, sha, files, complete, updatedAt: new Date().toISOString() };
127
+ }
128
+ async function filesPresent(store, manifest) {
129
+ for (const [file, info] of Object.entries(manifest.files)) {
130
+ if (!info.complete)
131
+ return false;
132
+ if ((await store.size(filePath(manifest.repo, manifest.sha, file))) !== info.size)
133
+ return false;
134
+ }
135
+ return true;
136
+ }
137
+ function emitCachedProgress(manifest, emit) {
138
+ const total = Object.values(manifest.files).reduce((n, f) => n + f.size, 0);
139
+ let done = 0;
140
+ for (const [file, info] of Object.entries(manifest.files)) {
141
+ done += info.size;
142
+ emit({
143
+ phase: "download",
144
+ file,
145
+ loadedBytes: info.size,
146
+ totalBytes: info.size,
147
+ overallLoadedBytes: done,
148
+ overallTotalBytes: total,
149
+ cached: true,
150
+ });
151
+ }
152
+ }
153
+ function reader(store, manifest, fromCache) {
154
+ const files = Object.keys(manifest.files);
155
+ const known = new Set(files);
156
+ return {
157
+ repo: manifest.repo,
158
+ sha: manifest.sha,
159
+ files,
160
+ info: manifest.files,
161
+ fromCache,
162
+ read: async (file, start, end) => {
163
+ if (!known.has(file))
164
+ return null;
165
+ try {
166
+ return await store.read(filePath(manifest.repo, manifest.sha, file), start, end);
167
+ }
168
+ catch (error) {
169
+ throw toWebslmError(error, "CACHE");
170
+ }
171
+ },
172
+ };
173
+ }
174
+ /** Runs `task` under a Web Lock when the platform has them (one download per file across tabs). */
175
+ async function withLock(name, task) {
176
+ const locks = globalThis.navigator?.locks;
177
+ return locks === undefined ? task() : locks.request(name, task);
178
+ }
179
+ /** Downloads `url` into `path`, resuming from the bytes already stored. */
180
+ export async function downloadFile(url, path, expected, options, onBytes) {
181
+ const { store, signal } = options;
182
+ const retries = options.retries ?? 4;
183
+ let have = store.resumable ? ((await store.size(path)) ?? 0) : 0;
184
+ if (expected.size !== undefined && have > expected.size)
185
+ have = 0;
186
+ if (expected.size === 0) {
187
+ const writer = await store.openWriter(path, 0);
188
+ await writer.close();
189
+ onBytes(0);
190
+ const hasher = options.createHasher?.();
191
+ return hasher === undefined ? { size: 0 } : { size: 0, sha256: hasher.finish() };
192
+ }
193
+ const hasher = options.createHasher?.();
194
+ if (hasher !== undefined && have > 0) {
195
+ // Resuming: hash the bytes already stored.
196
+ const step = 8 * 1024 * 1024;
197
+ for (let offset = 0; offset < have; offset += step) {
198
+ hasher.update(await store.read(path, offset, Math.min(have, offset + step)));
199
+ }
200
+ }
201
+ onBytes(have);
202
+ for (let attempt = 0;; attempt++) {
203
+ if (expected.size !== undefined && have === expected.size)
204
+ break;
205
+ if (isAborted(signal))
206
+ throw abortError(signal);
207
+ const headers = have > 0 ? { range: `bytes=${have}-` } : {};
208
+ let response;
209
+ try {
210
+ response = await hubFetch(url, options, { headers }, path.split("/").pop());
211
+ }
212
+ catch (error) {
213
+ if (WebslmError.is(error, "NETWORK") && attempt + 1 < retries) {
214
+ await delay(500 * 2 ** attempt, signal);
215
+ continue;
216
+ }
217
+ throw error;
218
+ }
219
+ if (have > 0 && response.status !== 206) {
220
+ // The server ignored Range: start over.
221
+ have = 0;
222
+ if (hasher !== undefined)
223
+ hasher.finish();
224
+ }
225
+ const writer = await store.openWriter(path, have);
226
+ let failure;
227
+ try {
228
+ const body = response.body;
229
+ if (body === null) {
230
+ const bytes = new Uint8Array(await response.arrayBuffer());
231
+ await writer.write(bytes);
232
+ hasher?.update(bytes);
233
+ have += bytes.length;
234
+ onBytes(have);
235
+ }
236
+ else {
237
+ const chunks = body.getReader();
238
+ for (;;) {
239
+ const { done, value } = await chunks.read();
240
+ if (done)
241
+ break;
242
+ await writer.write(value);
243
+ hasher?.update(value);
244
+ have += value.length;
245
+ onBytes(have);
246
+ }
247
+ }
248
+ await writer.close();
249
+ }
250
+ catch (error) {
251
+ failure = error;
252
+ await writer.abort().catch(() => { });
253
+ if (!store.resumable) {
254
+ have = 0;
255
+ if (hasher !== undefined)
256
+ hasher.finish();
257
+ }
258
+ }
259
+ if (failure === undefined) {
260
+ if (expected.size === undefined || have === expected.size)
261
+ break;
262
+ failure = new WebslmError("NETWORK", `${url}: got ${have} of ${expected.size} bytes`);
263
+ }
264
+ if (isAborted(signal))
265
+ throw abortError(signal);
266
+ if (attempt + 1 >= retries)
267
+ throw toWebslmError(failure, "NETWORK");
268
+ await delay(500 * 2 ** attempt, signal);
269
+ }
270
+ const sha256 = hasher?.finish();
271
+ if (expected.sha256 !== undefined && sha256 !== undefined && sha256 !== expected.sha256) {
272
+ await store.remove(path);
273
+ throw new WebslmError("INTEGRITY", `${path}: SHA-256 ${sha256} does not match the Hub's ${expected.sha256}; the partial file was removed`);
274
+ }
275
+ return sha256 === undefined ? { size: have } : { size: have, sha256 };
276
+ }
277
+ function delay(ms, signal) {
278
+ return new Promise((resolve, reject) => {
279
+ const timer = setTimeout(() => {
280
+ signal?.removeEventListener("abort", onAbort);
281
+ resolve();
282
+ }, ms);
283
+ const onAbort = () => {
284
+ clearTimeout(timer);
285
+ reject(abortError(signal));
286
+ };
287
+ signal?.addEventListener("abort", onAbort, { once: true });
288
+ });
289
+ }
@@ -0,0 +1,54 @@
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 type { Request, Response } from "./protocol.js";
14
+ import type { Activations, CpuInfo } from "./types.js";
15
+ import { type FlavourBindings, type WasmFlavour } from "./wasm-flavour.js";
16
+ /** How the engine talks back to the page. */
17
+ export interface EngineHost {
18
+ post(message: Response, transfer?: Transferable[]): void;
19
+ }
20
+ /** The instantiated engine: its bindings and how it runs. */
21
+ export interface EngineWasm {
22
+ readonly bindings: FlavourBindings;
23
+ readonly flavour: WasmFlavour;
24
+ /** Threads the CPU kernels use (1 unless `flavour` is `"threads"`). */
25
+ readonly threads: number;
26
+ /** Why `flavour` is not the one preferred (builds that are not installed). */
27
+ readonly note?: string;
28
+ }
29
+ /** How {@link initEngineWasm} instantiates the engine. */
30
+ export interface EngineWasmOptions {
31
+ /** Defaults to {@link selectWasmFlavour}. */
32
+ readonly flavour?: WasmFlavour;
33
+ /** Size of the `threads` pool; defaults to {@link defaultThreadCount}. */
34
+ readonly threads?: number;
35
+ /** The `.wasm` module, instead of the file shipped with the flavour. */
36
+ readonly source?: BufferSource | URL | string;
37
+ }
38
+ /**
39
+ * Instantiates the WebAssembly module once per realm (later calls share it,
40
+ * whatever their options), and for the `threads` flavour starts its pool of
41
+ * workers.
42
+ */
43
+ export declare function initEngineWasm(options?: EngineWasmOptions): Promise<EngineWasm>;
44
+ /**
45
+ * Human-readable CPU backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"` or
46
+ * `"CPU (wasm, SIMD128, 1 thread, deterministic, f32 activations)"`.
47
+ */
48
+ export declare function describeCpu(cpu: CpuInfo, activations?: Activations): string;
49
+ export declare class Engine {
50
+ #private;
51
+ constructor(host: EngineHost);
52
+ /** Handles one message from the page. Answers are posted through the host. */
53
+ handle(request: Request): void;
54
+ }