webslm 0.4.0 → 0.5.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.
- package/README.md +10 -6
- package/dist/cache/models.d.ts +27 -3
- package/dist/cache/models.js +108 -11
- package/dist/cache/node-fs.d.ts +26 -3
- package/dist/cache/node-fs.js +43 -9
- package/dist/cache-management.d.ts +1 -1
- package/dist/download.d.ts +9 -0
- package/dist/download.js +38 -8
- package/dist/engine.js +42 -12
- package/dist/hub.d.ts +22 -2
- package/dist/hub.js +53 -5
- package/dist/models.d.ts +8 -2
- package/dist/models.js +46 -12
- package/dist/protocol.d.ts +4 -0
- package/dist/simple.d.ts +2 -2
- package/dist/simple.js +2 -2
- package/dist/types.d.ts +18 -4
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +6 -0
- package/wasm/relaxed/webslm_wasm.js +12 -6
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm.d.ts +6 -0
- package/wasm/simd/webslm_wasm.js +12 -6
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm.d.ts +6 -0
- package/wasm/threads/webslm_wasm.js +14 -8
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
package/README.md
CHANGED
|
@@ -273,15 +273,17 @@ await engine.terminate();
|
|
|
273
273
|
|
|
274
274
|
```ts
|
|
275
275
|
type ModelSource =
|
|
276
|
-
| { hub: string; revision?: string; hubUrl?: string } // a plain string is a hub repo id
|
|
277
|
-
| { files: Record<string, Blob | ArrayBuffer | Uint8Array
|
|
278
|
-
| { fetch: (path: string, range?: [number, number]) => Promise<ArrayBuffer | Uint8Array | null
|
|
276
|
+
| { hub: string; revision?: string; hubUrl?: string; file?: string } // a plain string is a hub repo id
|
|
277
|
+
| { files: Record<string, Blob | ArrayBuffer | Uint8Array>; file?: string } // "config.json", "tokenizer.json", "model.safetensors", "model.gguf"...
|
|
278
|
+
| { fetch: (path: string, range?: [number, number]) => Promise<ArrayBuffer | Uint8Array | null>; file?: string };
|
|
279
279
|
```
|
|
280
280
|
|
|
281
281
|
- **Hub**: the revision (default `main`) is resolved to a commit sha, every needed file is downloaded fully into the cache under `webslm/{repo}/{sha}/`, and the engine reads ranges from there. A later load of the same revision makes no request at all; delete the cached model (or pass a newer revision) to pick up new commits. Pass `token` in the options for gated or private repositories; it is only sent to `hubUrl`.
|
|
282
282
|
- **Files**: bytes the page already holds (an upload, IndexedDB, a training job's output).
|
|
283
283
|
- **Fetch**: a custom store. `range` is `[start, end)`. Return `null` for a missing file: optional files such as `generation_config.json` are probed.
|
|
284
284
|
|
|
285
|
+
`file` names a GGUF file of the source to load instead of safetensors weights, e.g. `{ hub: "bartowski/SmolLM2-135M-Instruct-GGUF", file: "SmolLM2-135M-Instruct-Q8_0.gguf" }`: only that file (and the repository's tokenizer files, if any) is downloaded, its metadata gives the configuration, the tokenizer (unless a `tokenizer.json` sits next to it) and the chat template. A hub repository or `files` holding GGUF files and no safetensors loads its preferred GGUF file (Q8_0, else Q4_K_M, Q4_0...) without `file`; a `fetch` source needs it. A GGUF source loads in the format of its matrices unless `quant` says otherwise: a Q8_0 file runs as Q8_0 with its blocks unchanged. Checkpoints written by `webslm export --quant q8` (Q8_0 matrices stored as an `I8` and an `F16` tensor each) load the same way, at Q8_0 size. See [GGUF and pre-quantized checkpoints](../../README.md#gguf-and-pre-quantized-checkpoints) for the tensor types and architectures. `searchModels` lists GGUF repositories of supported architectures (`gguf: true`).
|
|
286
|
+
|
|
285
287
|
`model.info()` lists every file read with its SHA-256, so an application can check what it runs.
|
|
286
288
|
|
|
287
289
|
## LoRA adapters
|
|
@@ -363,7 +365,9 @@ The first load writes the file as it converts (0.1 to 1.8 s more, once). Each we
|
|
|
363
365
|
|
|
364
366
|
## Node, Bun and Deno
|
|
365
367
|
|
|
366
|
-
The same API works in Node 20+ and Bun, as a plain ESM script with no bundler, on the [native engine](#native-engine-in-node) when it is available, else on WebAssembly. The cache
|
|
368
|
+
The same API works in Node 20+ and Bun, as a plain ESM script with no bundler, on the [native engine](#native-engine-in-node) when it is available, else on WebAssembly. The cache is the [command-line tool's](https://github.com/maxgfr/webslm#cache-and-hugging-face-tokens): `WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS, `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` or `~/.cache/webslm` on Linux (`cacheDir` in the options overrides it). It has the same layout, so a model pulled with `webslm pull` loads in Node without a download, and a model downloaded in Node runs with `webslm run`. `WEBSLM_OFFLINE=1` (or `HF_HUB_OFFLINE=1`) forbids network access: models already in the cache load, anything else rejects with `NETWORK`. `HF_ENDPOINT` replaces `https://huggingface.co` (a mirror, or a local stand-in in tests) unless a source gives its own `hubUrl`. The engine runs in a `worker_threads` worker, which does not keep the process alive between calls; pass `worker: false` to run it on the calling thread. Deno 2 runs Hub models as is; for a `files` source of a few hundred megabytes, pass `worker: false` (Deno's `worker_threads` cannot copy buffers that large).
|
|
369
|
+
|
|
370
|
+
Earlier versions kept the Node cache in `~/.cache/webslm` on macOS and in `%USERPROFILE%\.cache\webslm` on Windows (or `$XDG_CACHE_HOME/webslm` when set), apart from the command-line tool's. webslm does not touch that directory: models in it download again into the new one. To keep them, move the directory when the new one does not exist yet (`mv ~/.cache/webslm ~/Library/Caches/webslm` on macOS), or merge it into the new one and delete it (`rsync -a --ignore-existing ~/.cache/webslm/ ~/Library/Caches/webslm/ && rm -rf ~/.cache/webslm`); or just delete it (`rm -rf ~/.cache/webslm`). Its `native/` directory, the native engine, is downloaded again when needed. With `WEBSLM_CACHE_DIR` set nothing changes.
|
|
367
371
|
|
|
368
372
|
```ts
|
|
369
373
|
import { readFile } from "node:fs/promises";
|
|
@@ -388,7 +392,7 @@ Each release attaches to its [GitHub Release](https://github.com/maxgfr/webslm/r
|
|
|
388
392
|
- the native CPU kernels (NEON with dotprod and i8mm, AVX2, AVX-512 VNNI) on every core, capped by the container's CPU quota, instead of WebAssembly SIMD on at most 8 threads;
|
|
389
393
|
- the GPU through Metal (macOS), Vulkan or DX12 (Linux, Windows), with the device rules of the command-line tool: `device: "auto"` runs models above ~100M parameters on a hardware GPU that holds them (software rasterizers such as llvmpipe are skipped; the model is sized against the GPU's memory before anything is uploaded), the CPU otherwise; `device: "gpu"` fails with `UNSUPPORTED_DEVICE` when there is no GPU;
|
|
390
394
|
- `quant: "auto"` decided against the machine's memory and the GPU's (measured with [sift](https://github.com/maxgfr/sift)), not the 4 GiB of WebAssembly;
|
|
391
|
-
- the converted-weight cache in the same file as the command-line tool (`<repo>/<sha>/quantized/<format>/weights.webslmq`), so `webslm pull --quant q8` and the package share it
|
|
395
|
+
- the converted-weight cache in the same file as the command-line tool (`<repo>/<sha>/quantized/<format>/weights.webslmq`), in the same cache directory, so `webslm pull --quant q8` and the package share it.
|
|
392
396
|
|
|
393
397
|
The API is the same (`load`, `ask`, `stream`, `loadModel`, sessions with `score`, `step`, `fork`, LoRA adapters, the AI SDK provider), and so are the results on the CPU: the quantized kernels are bit-identical across builds, so `q8` gives the WebAssembly engine's greedy tokens, and `f32` the `transformers` goldens (both checked in CI).
|
|
394
398
|
|
|
@@ -426,7 +430,7 @@ export default defineConfig({
|
|
|
426
430
|
});
|
|
427
431
|
```
|
|
428
432
|
|
|
429
|
-
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.
|
|
433
|
+
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.5.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
|
|
430
434
|
|
|
431
435
|
## Errors
|
|
432
436
|
|
package/dist/cache/models.d.ts
CHANGED
|
@@ -2,10 +2,18 @@
|
|
|
2
2
|
* Layout of cached checkpoints inside a {@link CacheStore}:
|
|
3
3
|
*
|
|
4
4
|
* ```text
|
|
5
|
-
* {repo}/refs/{revision}
|
|
6
|
-
* {repo}/{sha}/.webslm.json
|
|
7
|
-
* {repo}/{sha}
|
|
5
|
+
* {repo}/refs/{revision} commit sha a revision resolved to
|
|
6
|
+
* {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
|
|
7
|
+
* {repo}/{sha}/.webslm-manifest.json the command-line tool's manifest (complete snapshots)
|
|
8
|
+
* {repo}/{sha}/{file} checkpoint files
|
|
9
|
+
* {repo}/{sha}/quantized/{format}/weights.webslmq converted weights
|
|
8
10
|
* ```
|
|
11
|
+
*
|
|
12
|
+
* In Node this is the command-line tool's cache layout
|
|
13
|
+
* (crates/webslm-hub/src/cache.rs) in the same directory, so a model pulled
|
|
14
|
+
* by `webslm pull` loads without a download and the reverse: each side reads
|
|
15
|
+
* the other's manifest, and a completed download in a directory store writes
|
|
16
|
+
* the command-line tool's manifest too.
|
|
9
17
|
*/
|
|
10
18
|
import { type CacheStore } from "./store.js";
|
|
11
19
|
/** Manifest of one cached revision. */
|
|
@@ -49,6 +57,8 @@ export interface CachedModel {
|
|
|
49
57
|
readonly storage: string;
|
|
50
58
|
}
|
|
51
59
|
export declare const MANIFEST_FILE = ".webslm.json";
|
|
60
|
+
/** The command-line tool's manifest of a complete snapshot (`MANIFEST_FILE` in crates/webslm-hub/src/cache.rs). */
|
|
61
|
+
export declare const CLI_MANIFEST_FILE = ".webslm-manifest.json";
|
|
52
62
|
/** Checks a repository id and returns it normalized. */
|
|
53
63
|
export declare function checkRepoId(repo: string): string;
|
|
54
64
|
export declare function refPath(repo: string, revision: string): string;
|
|
@@ -61,10 +71,24 @@ export declare function filePath(repo: string, sha: string, file: string): strin
|
|
|
61
71
|
*/
|
|
62
72
|
export declare function weightCachePath(repo: string, sha: string, quant: string): string;
|
|
63
73
|
export declare function manifestPath(repo: string, sha: string): string;
|
|
74
|
+
export declare function cliManifestPath(repo: string, sha: string): string;
|
|
64
75
|
export declare function readRef(store: CacheStore, repo: string, revision: string): Promise<string | undefined>;
|
|
65
76
|
export declare function writeRef(store: CacheStore, repo: string, revision: string, sha: string): Promise<void>;
|
|
66
77
|
export declare function readManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
|
|
67
78
|
export declare function writeManifest(store: CacheStore, manifest: CacheManifest): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* The snapshot `repo@sha` the command-line tool pulled, as a complete
|
|
81
|
+
* {@link CacheManifest}: `undefined` without its manifest or when a file of
|
|
82
|
+
* it is missing or has another size.
|
|
83
|
+
*/
|
|
84
|
+
export declare function readCliManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
|
|
85
|
+
/**
|
|
86
|
+
* Writes the command-line tool's manifest of a complete snapshot, so that
|
|
87
|
+
* `webslm` (the command-line tool) uses the files without pulling them
|
|
88
|
+
* again. A manifest it already has keeps its entries and gains the files it
|
|
89
|
+
* lacks (another GGUF file of the same commit).
|
|
90
|
+
*/
|
|
91
|
+
export declare function writeCliManifest(store: CacheStore, manifest: CacheManifest, revision: string): Promise<void>;
|
|
68
92
|
/** Every cached repository of `store`. */
|
|
69
93
|
export declare function listCachedModelsIn(store: CacheStore): Promise<CachedModel[]>;
|
|
70
94
|
/** Removes a cached repository (every revision) from `store`. */
|
package/dist/cache/models.js
CHANGED
|
@@ -2,13 +2,23 @@
|
|
|
2
2
|
* Layout of cached checkpoints inside a {@link CacheStore}:
|
|
3
3
|
*
|
|
4
4
|
* ```text
|
|
5
|
-
* {repo}/refs/{revision}
|
|
6
|
-
* {repo}/{sha}/.webslm.json
|
|
7
|
-
* {repo}/{sha}
|
|
5
|
+
* {repo}/refs/{revision} commit sha a revision resolved to
|
|
6
|
+
* {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
|
|
7
|
+
* {repo}/{sha}/.webslm-manifest.json the command-line tool's manifest (complete snapshots)
|
|
8
|
+
* {repo}/{sha}/{file} checkpoint files
|
|
9
|
+
* {repo}/{sha}/quantized/{format}/weights.webslmq converted weights
|
|
8
10
|
* ```
|
|
11
|
+
*
|
|
12
|
+
* In Node this is the command-line tool's cache layout
|
|
13
|
+
* (crates/webslm-hub/src/cache.rs) in the same directory, so a model pulled
|
|
14
|
+
* by `webslm pull` loads without a download and the reverse: each side reads
|
|
15
|
+
* the other's manifest, and a completed download in a directory store writes
|
|
16
|
+
* the command-line tool's manifest too.
|
|
9
17
|
*/
|
|
10
18
|
import { joinPath, readText, writeText } from "./store.js";
|
|
11
19
|
export const MANIFEST_FILE = ".webslm.json";
|
|
20
|
+
/** The command-line tool's manifest of a complete snapshot (`MANIFEST_FILE` in crates/webslm-hub/src/cache.rs). */
|
|
21
|
+
export const CLI_MANIFEST_FILE = ".webslm-manifest.json";
|
|
12
22
|
/** Checks a repository id and returns it normalized. */
|
|
13
23
|
export function checkRepoId(repo) {
|
|
14
24
|
const trimmed = repo.trim().replace(/^\/+|\/+$/g, "");
|
|
@@ -20,6 +30,10 @@ export function checkRepoId(repo) {
|
|
|
20
30
|
export function refPath(repo, revision) {
|
|
21
31
|
return joinPath(repo, "refs", encodeURIComponent(revision));
|
|
22
32
|
}
|
|
33
|
+
/** Where the command-line tool keeps a ref: one directory per `/` of the revision. */
|
|
34
|
+
function cliRefPath(repo, revision) {
|
|
35
|
+
return joinPath(repo, "refs", ...revision.split("/").map(encodeURIComponent));
|
|
36
|
+
}
|
|
23
37
|
export function revisionDir(repo, sha) {
|
|
24
38
|
return joinPath(repo, sha);
|
|
25
39
|
}
|
|
@@ -40,8 +54,15 @@ export function weightCachePath(repo, sha, quant) {
|
|
|
40
54
|
export function manifestPath(repo, sha) {
|
|
41
55
|
return joinPath(repo, sha, MANIFEST_FILE);
|
|
42
56
|
}
|
|
57
|
+
export function cliManifestPath(repo, sha) {
|
|
58
|
+
return joinPath(repo, sha, CLI_MANIFEST_FILE);
|
|
59
|
+
}
|
|
43
60
|
export async function readRef(store, repo, revision) {
|
|
44
|
-
|
|
61
|
+
let text = await readText(store, refPath(repo, revision));
|
|
62
|
+
// A branch with `/` pulled by the command-line tool.
|
|
63
|
+
if (text === undefined && revision.includes("/"))
|
|
64
|
+
text = await readText(store, cliRefPath(repo, revision));
|
|
65
|
+
const sha = text?.trim();
|
|
45
66
|
return sha === undefined || sha === "" ? undefined : sha;
|
|
46
67
|
}
|
|
47
68
|
export async function writeRef(store, repo, revision, sha) {
|
|
@@ -62,21 +83,97 @@ export async function readManifest(store, repo, sha) {
|
|
|
62
83
|
export async function writeManifest(store, manifest) {
|
|
63
84
|
await writeText(store, manifestPath(manifest.repo, manifest.sha), JSON.stringify(manifest, null, 2));
|
|
64
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The snapshot `repo@sha` the command-line tool pulled, as a complete
|
|
88
|
+
* {@link CacheManifest}: `undefined` without its manifest or when a file of
|
|
89
|
+
* it is missing or has another size.
|
|
90
|
+
*/
|
|
91
|
+
export async function readCliManifest(store, repo, sha) {
|
|
92
|
+
const text = await readText(store, cliManifestPath(repo, sha));
|
|
93
|
+
if (text === undefined)
|
|
94
|
+
return undefined;
|
|
95
|
+
let parsed;
|
|
96
|
+
try {
|
|
97
|
+
parsed = JSON.parse(text);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
if (parsed?.sha !== sha || !Array.isArray(parsed.files))
|
|
103
|
+
return undefined;
|
|
104
|
+
const files = {};
|
|
105
|
+
for (const file of parsed.files) {
|
|
106
|
+
if (typeof file?.name !== "string")
|
|
107
|
+
return undefined;
|
|
108
|
+
let size;
|
|
109
|
+
try {
|
|
110
|
+
size = await store.size(filePath(repo, sha, file.name));
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return undefined; // a name the store refuses
|
|
114
|
+
}
|
|
115
|
+
if (size === undefined || (typeof file.size === "number" && file.size !== size))
|
|
116
|
+
return undefined;
|
|
117
|
+
files[file.name] =
|
|
118
|
+
typeof file.sha256 === "string" ? { size, sha256: file.sha256, complete: true } : { size, complete: true };
|
|
119
|
+
}
|
|
120
|
+
const created = typeof parsed.created_unix === "number" ? parsed.created_unix * 1000 : 0;
|
|
121
|
+
return { version: 1, repo, sha, files, complete: true, updatedAt: new Date(created).toISOString() };
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Writes the command-line tool's manifest of a complete snapshot, so that
|
|
125
|
+
* `webslm` (the command-line tool) uses the files without pulling them
|
|
126
|
+
* again. A manifest it already has keeps its entries and gains the files it
|
|
127
|
+
* lacks (another GGUF file of the same commit).
|
|
128
|
+
*/
|
|
129
|
+
export async function writeCliManifest(store, manifest, revision) {
|
|
130
|
+
if (!manifest.complete)
|
|
131
|
+
return;
|
|
132
|
+
const path = cliManifestPath(manifest.repo, manifest.sha);
|
|
133
|
+
let existing;
|
|
134
|
+
if ((await store.size(path)) !== undefined) {
|
|
135
|
+
try {
|
|
136
|
+
existing = JSON.parse((await readText(store, path)) ?? "");
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return; // not ours to repair
|
|
140
|
+
}
|
|
141
|
+
if (!Array.isArray(existing?.files))
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const known = new Set((existing?.files ?? []).map((f) => f.name));
|
|
145
|
+
const added = Object.entries(manifest.files)
|
|
146
|
+
.filter(([name]) => !known.has(name))
|
|
147
|
+
.map(([name, info]) => ({ name, size: info.size, sha256: info.sha256 ?? null, blob_id: null }));
|
|
148
|
+
if (existing !== undefined && added.length === 0)
|
|
149
|
+
return;
|
|
150
|
+
const cli = {
|
|
151
|
+
repo: manifest.repo,
|
|
152
|
+
revision: existing?.revision ?? revision,
|
|
153
|
+
sha: manifest.sha,
|
|
154
|
+
files: [...(existing?.files ?? []), ...added],
|
|
155
|
+
created_unix: existing?.created_unix ?? Math.floor(Date.now() / 1000),
|
|
156
|
+
};
|
|
157
|
+
await writeText(store, path, JSON.stringify(cli, null, 2));
|
|
158
|
+
}
|
|
65
159
|
/** Every cached repository of `store`. */
|
|
66
160
|
export async function listCachedModelsIn(store) {
|
|
67
161
|
const entries = await store.list("");
|
|
68
|
-
const
|
|
162
|
+
const isManifest = (path) => path.endsWith(`/${MANIFEST_FILE}`) || path.endsWith(`/${CLI_MANIFEST_FILE}`);
|
|
163
|
+
// Revisions with either manifest (ours, or the command-line tool's), once each.
|
|
164
|
+
const revisionDirs = new Set(entries.filter((e) => isManifest(e.path)).map((e) => e.path.slice(0, e.path.lastIndexOf("/"))));
|
|
69
165
|
const byRepo = new Map();
|
|
70
|
-
for (const
|
|
71
|
-
const parts =
|
|
72
|
-
const sha = parts[parts.length -
|
|
73
|
-
const repo = parts.slice(0, -
|
|
166
|
+
for (const revision of [...revisionDirs].sort()) {
|
|
167
|
+
const parts = revision.split("/");
|
|
168
|
+
const sha = parts[parts.length - 1];
|
|
169
|
+
const repo = parts.slice(0, -1).join("/");
|
|
74
170
|
if (sha === undefined || repo === "")
|
|
75
171
|
continue;
|
|
76
172
|
const manifest = await readManifest(store, repo, sha);
|
|
173
|
+
const complete = manifest?.complete === true || (await readCliManifest(store, repo, sha)) !== undefined;
|
|
77
174
|
const dir = `${revisionDir(repo, sha)}/`;
|
|
78
175
|
const files = entries
|
|
79
|
-
.filter((e) => e.path.startsWith(dir) && !e.path
|
|
176
|
+
.filter((e) => e.path.startsWith(dir) && !isManifest(e.path))
|
|
80
177
|
.map((e) => ({ name: e.path.slice(dir.length), sizeBytes: e.size }));
|
|
81
178
|
const refs = [];
|
|
82
179
|
const refDir = `${repo}/refs/`;
|
|
@@ -91,7 +188,7 @@ export async function listCachedModelsIn(store) {
|
|
|
91
188
|
refs,
|
|
92
189
|
files,
|
|
93
190
|
sizeBytes: files.reduce((n, f) => n + f.sizeBytes, 0),
|
|
94
|
-
complete
|
|
191
|
+
complete,
|
|
95
192
|
});
|
|
96
193
|
byRepo.set(repo, revisions);
|
|
97
194
|
}
|
package/dist/cache/node-fs.d.ts
CHANGED
|
@@ -1,9 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Directory store for Node.js
|
|
3
|
-
* (
|
|
2
|
+
* Directory store for Node.js, in the command-line tool's cache directory
|
|
3
|
+
* (see {@link resolveCacheDir}).
|
|
4
4
|
*/
|
|
5
5
|
import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
|
|
6
|
-
|
|
6
|
+
interface PathModule {
|
|
7
|
+
join(...parts: string[]): string;
|
|
8
|
+
dirname(path: string): string;
|
|
9
|
+
isAbsolute(path: string): boolean;
|
|
10
|
+
}
|
|
11
|
+
/** What the default cache directory depends on. */
|
|
12
|
+
export interface CacheDirEnvironment {
|
|
13
|
+
/** `process.platform`: `"darwin"`, `"win32"`, `"linux"`... */
|
|
14
|
+
readonly platform: string;
|
|
15
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
16
|
+
/** The home directory; `undefined` or `""` when unknown. */
|
|
17
|
+
readonly homedir: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The cache directory, by the command-line tool's rules (`Cache::from_env`
|
|
21
|
+
* in crates/webslm-hub/src/cache.rs), so that both share one cache:
|
|
22
|
+
* `$WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS,
|
|
23
|
+
* `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` (an
|
|
24
|
+
* absolute `XDG_CACHE_HOME`) or `~/.cache/webslm` elsewhere. `path` is the
|
|
25
|
+
* platform's path module (`node:path`, or its `win32`/`posix` flavour).
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveCacheDir(environment: CacheDirEnvironment, path: Pick<PathModule, "join" | "isAbsolute">): string;
|
|
28
|
+
/** The default cache directory in Node (see {@link resolveCacheDir}). */
|
|
7
29
|
export declare function defaultCacheDir(): Promise<string>;
|
|
8
30
|
export declare class NodeFsStore implements CacheStore {
|
|
9
31
|
#private;
|
|
@@ -19,3 +41,4 @@ export declare class NodeFsStore implements CacheStore {
|
|
|
19
41
|
list(prefix: string): Promise<CacheEntry[]>;
|
|
20
42
|
remove(path: string): Promise<void>;
|
|
21
43
|
}
|
|
44
|
+
export {};
|
package/dist/cache/node-fs.js
CHANGED
|
@@ -1,20 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Directory store for Node.js
|
|
3
|
-
* (
|
|
2
|
+
* Directory store for Node.js, in the command-line tool's cache directory
|
|
3
|
+
* (see {@link resolveCacheDir}).
|
|
4
4
|
*/
|
|
5
5
|
import { importNode } from "../runtime.js";
|
|
6
6
|
import { pathSegments, resolveRange, } from "./store.js";
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* The cache directory, by the command-line tool's rules (`Cache::from_env`
|
|
9
|
+
* in crates/webslm-hub/src/cache.rs), so that both share one cache:
|
|
10
|
+
* `$WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS,
|
|
11
|
+
* `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` (an
|
|
12
|
+
* absolute `XDG_CACHE_HOME`) or `~/.cache/webslm` elsewhere. `path` is the
|
|
13
|
+
* platform's path module (`node:path`, or its `win32`/`posix` flavour).
|
|
14
|
+
*/
|
|
15
|
+
export function resolveCacheDir(environment, path) {
|
|
16
|
+
const { platform, env } = environment;
|
|
17
|
+
const custom = env.WEBSLM_CACHE_DIR;
|
|
18
|
+
if (custom)
|
|
19
|
+
return custom;
|
|
20
|
+
const home = environment.homedir || undefined;
|
|
21
|
+
const noHome = () => new Error("cannot find the home directory; set WEBSLM_CACHE_DIR");
|
|
22
|
+
if (platform === "darwin") {
|
|
23
|
+
if (home === undefined)
|
|
24
|
+
throw noHome();
|
|
25
|
+
return path.join(home, "Library", "Caches", "webslm");
|
|
26
|
+
}
|
|
27
|
+
const localAppData = env.LOCALAPPDATA;
|
|
28
|
+
if (platform === "win32" && localAppData)
|
|
29
|
+
return path.join(localAppData, "webslm", "cache");
|
|
30
|
+
const xdg = env.XDG_CACHE_HOME;
|
|
31
|
+
if (xdg && path.isAbsolute(xdg))
|
|
32
|
+
return path.join(xdg, "webslm");
|
|
33
|
+
if (home === undefined)
|
|
34
|
+
throw noHome();
|
|
35
|
+
return path.join(home, ".cache", "webslm");
|
|
36
|
+
}
|
|
37
|
+
/** The default cache directory in Node (see {@link resolveCacheDir}). */
|
|
8
38
|
export async function defaultCacheDir() {
|
|
9
|
-
const env = globalThis.process
|
|
10
|
-
?.env;
|
|
39
|
+
const env = globalThis.process?.env ?? {};
|
|
11
40
|
const path = await importNode("path");
|
|
12
|
-
if (env
|
|
41
|
+
if (env.WEBSLM_CACHE_DIR)
|
|
13
42
|
return env.WEBSLM_CACHE_DIR;
|
|
14
|
-
if (env?.XDG_CACHE_HOME)
|
|
15
|
-
return path.join(env.XDG_CACHE_HOME, "webslm");
|
|
16
43
|
const os = await importNode("os");
|
|
17
|
-
|
|
44
|
+
let homedir;
|
|
45
|
+
try {
|
|
46
|
+
homedir = os.homedir();
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
homedir = undefined;
|
|
50
|
+
}
|
|
51
|
+
return resolveCacheDir({ platform: os.platform(), env, homedir }, path);
|
|
18
52
|
}
|
|
19
53
|
export class NodeFsStore {
|
|
20
54
|
kind = "fs";
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { type CachedModel } from "./cache/models.js";
|
|
3
3
|
export type { CachedModel, CachedRevision } from "./cache/models.js";
|
|
4
4
|
export interface CacheOptions {
|
|
5
|
-
/** Cache directory in Node (default `WEBSLM_CACHE_DIR`
|
|
5
|
+
/** Cache directory in Node (default `WEBSLM_CACHE_DIR`, else the command-line tool's: `~/Library/Caches/webslm` on macOS, `~/.cache/webslm` on Linux). */
|
|
6
6
|
readonly cacheDir?: string;
|
|
7
7
|
}
|
|
8
8
|
/** Models downloaded into the cache (OPFS and Cache API in browsers, the cache directory in Node). */
|
package/dist/download.d.ts
CHANGED
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
* read from the cache without any network request: a revision given as a
|
|
8
8
|
* commit sha, or a branch already resolved once (the cached ref is reused;
|
|
9
9
|
* delete the cached model to pick up new commits).
|
|
10
|
+
*
|
|
11
|
+
* In a directory store (Node) a snapshot the command-line tool pulled is used
|
|
12
|
+
* as is, and a completed download also writes the command-line tool's
|
|
13
|
+
* manifest, so `webslm pull` and the package share the files.
|
|
10
14
|
*/
|
|
11
15
|
import { type CachedFileInfo } from "./cache/models.js";
|
|
12
16
|
import type { CacheStore } from "./cache/store.js";
|
|
@@ -26,6 +30,11 @@ export interface HubDownloadOptions extends HubOptions {
|
|
|
26
30
|
readonly retries?: number;
|
|
27
31
|
/** Minimum delay between two progress events of the same file, in ms (default 50). */
|
|
28
32
|
readonly progressIntervalMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* A GGUF file of the repository to download as the weights (a repository
|
|
35
|
+
* without safetensors weights gets its preferred one anyway).
|
|
36
|
+
*/
|
|
37
|
+
readonly file?: string;
|
|
29
38
|
}
|
|
30
39
|
/** A checkpoint ready to be read from the cache. */
|
|
31
40
|
export interface CachedCheckpoint {
|
package/dist/download.js
CHANGED
|
@@ -7,10 +7,14 @@
|
|
|
7
7
|
* read from the cache without any network request: a revision given as a
|
|
8
8
|
* commit sha, or a branch already resolved once (the cached ref is reused;
|
|
9
9
|
* delete the cached model to pick up new commits).
|
|
10
|
+
*
|
|
11
|
+
* In a directory store (Node) a snapshot the command-line tool pulled is used
|
|
12
|
+
* as is, and a completed download also writes the command-line tool's
|
|
13
|
+
* manifest, so `webslm pull` and the package share the files.
|
|
10
14
|
*/
|
|
11
|
-
import { checkRepoId, filePath, readManifest, readRef, writeManifest, writeRef, } from "./cache/models.js";
|
|
15
|
+
import { checkRepoId, filePath, readCliManifest, readManifest, readRef, writeCliManifest, writeManifest, writeRef, } from "./cache/models.js";
|
|
12
16
|
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
13
|
-
import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, selectCheckpointFiles, } from "./hub.js";
|
|
17
|
+
import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, selectCheckpointFiles, } from "./hub.js";
|
|
14
18
|
const SHA_PATTERN = /^[0-9a-f]{40}$/;
|
|
15
19
|
/** Makes `repo@revision` available in `options.store` and returns a reader over it. */
|
|
16
20
|
export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
@@ -21,8 +25,14 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
|
21
25
|
// Offline path: a known sha whose files are all complete.
|
|
22
26
|
const knownSha = SHA_PATTERN.test(rev) ? rev : await readRef(store, repo, rev);
|
|
23
27
|
if (knownSha !== undefined) {
|
|
24
|
-
const
|
|
25
|
-
|
|
28
|
+
const ours = await readManifest(store, repo, knownSha);
|
|
29
|
+
// A named GGUF file must be in the snapshot (another one may be).
|
|
30
|
+
const holds = (m) => options.file === undefined || m?.files[options.file] !== undefined;
|
|
31
|
+
const manifest = ours?.complete === true && holds(ours) && (await filesPresent(store, ours))
|
|
32
|
+
? ours
|
|
33
|
+
: await readCliManifest(store, repo, knownSha);
|
|
34
|
+
if (manifest !== undefined && holds(manifest)) {
|
|
35
|
+
await shareWithCli(store, manifest, rev);
|
|
26
36
|
emitCachedProgress(manifest, emit);
|
|
27
37
|
return reader(store, manifest, true);
|
|
28
38
|
}
|
|
@@ -34,7 +44,9 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
|
34
44
|
const names = revisionInfo.files.map((f) => f.name);
|
|
35
45
|
return withLock(`webslm:${repo}@${sha}`, async () => {
|
|
36
46
|
const previous = await readManifest(store, repo, sha);
|
|
37
|
-
|
|
47
|
+
// Files the command-line tool pulled count as downloaded.
|
|
48
|
+
const pulled = await readCliManifest(store, repo, sha);
|
|
49
|
+
const done = { ...previous?.files, ...pulled?.files };
|
|
38
50
|
let downloaded = false;
|
|
39
51
|
const download = async (file, progress) => {
|
|
40
52
|
const hubFile = hubFiles.get(file);
|
|
@@ -72,11 +84,14 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
|
72
84
|
throw new WebslmError("INVALID_CHECKPOINT", `invalid ${SAFETENSORS_INDEX}`, { cause: error });
|
|
73
85
|
}
|
|
74
86
|
}
|
|
75
|
-
const selected = selectCheckpointFiles(names, index);
|
|
87
|
+
const selected = selectCheckpointFiles(names, index, options.file);
|
|
76
88
|
if (selected.weights.length === 0) {
|
|
77
|
-
throw new WebslmError("UNSUPPORTED_MODEL",
|
|
89
|
+
throw new WebslmError("UNSUPPORTED_MODEL", options.file === undefined
|
|
90
|
+
? `${repo}@${rev} has no safetensors weights or GGUF files`
|
|
91
|
+
: `${repo}@${rev} has no ${options.file}`);
|
|
78
92
|
}
|
|
79
|
-
|
|
93
|
+
const ggufWeights = selected.weights.some(isGgufFile);
|
|
94
|
+
if (!names.includes("config.json") && !isAdapterListing(names) && !ggufWeights) {
|
|
80
95
|
throw new WebslmError("INVALID_CHECKPOINT", `${repo}@${rev} has no config.json`);
|
|
81
96
|
}
|
|
82
97
|
const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];
|
|
@@ -119,12 +134,27 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
|
119
134
|
await writeManifest(store, manifest);
|
|
120
135
|
if (rev !== sha)
|
|
121
136
|
await writeRef(store, repo, rev, sha);
|
|
137
|
+
await shareWithCli(store, manifest, rev);
|
|
122
138
|
return reader(store, manifest, !downloaded);
|
|
123
139
|
});
|
|
124
140
|
}
|
|
125
141
|
function manifestOf(repo, sha, files, complete) {
|
|
126
142
|
return { version: 1, repo, sha, files, complete, updatedAt: new Date().toISOString() };
|
|
127
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Writes the command-line tool's manifest of a complete snapshot in a
|
|
146
|
+
* directory store (where the tool may share the cache); best effort.
|
|
147
|
+
*/
|
|
148
|
+
async function shareWithCli(store, manifest, revision) {
|
|
149
|
+
if (store.kind !== "fs")
|
|
150
|
+
return;
|
|
151
|
+
try {
|
|
152
|
+
await writeCliManifest(store, manifest, revision);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
// A read-only cache: the command-line tool will pull the files itself.
|
|
156
|
+
}
|
|
157
|
+
}
|
|
128
158
|
async function filesPresent(store, manifest) {
|
|
129
159
|
for (const [file, info] of Object.entries(manifest.files)) {
|
|
130
160
|
if (!info.complete)
|
package/dist/engine.js
CHANGED
|
@@ -19,7 +19,21 @@ import { openStore } from "./cache/index.js";
|
|
|
19
19
|
import { weightCachePath } from "./cache/models.js";
|
|
20
20
|
import { prepareHubCheckpoint } from "./download.js";
|
|
21
21
|
import { WebslmError, abortError, deserializeError, serializeError } from "./errors.js";
|
|
22
|
-
import { SAFETENSORS_INDEX } from "./hub.js";
|
|
22
|
+
import { SAFETENSORS_INDEX, isGgufFile, pickGgufFile } from "./hub.js";
|
|
23
|
+
/** Whether a read is of the weights (safetensors or GGUF), for progress. */
|
|
24
|
+
function isWeightFile(path) {
|
|
25
|
+
return (path.endsWith(".safetensors") && path !== SAFETENSORS_INDEX) || isGgufFile(path);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The GGUF file a source loads: the one it names, else the preferred one of
|
|
29
|
+
* a file list without safetensors weights (a GGUF repository).
|
|
30
|
+
*/
|
|
31
|
+
function ggufFileOf(source, opened) {
|
|
32
|
+
if (source.file !== undefined)
|
|
33
|
+
return source.file;
|
|
34
|
+
const list = opened.list ?? [];
|
|
35
|
+
return list.some((f) => f.endsWith(".safetensors")) ? undefined : pickGgufFile(list);
|
|
36
|
+
}
|
|
23
37
|
import { scoreTransferables } from "./protocol.js";
|
|
24
38
|
import { installNodeWebWorker, nodePoolAvailable } from "./node-web-worker.js";
|
|
25
39
|
import { installPoolWorkerFactory } from "./pool.js";
|
|
@@ -342,7 +356,10 @@ export class Engine {
|
|
|
342
356
|
...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
|
|
343
357
|
...(source.token === undefined ? {} : { token: source.token }),
|
|
344
358
|
};
|
|
345
|
-
const checkpoint = await prepareHubCheckpoint(source.repo, source.revision,
|
|
359
|
+
const checkpoint = await prepareHubCheckpoint(source.repo, source.revision, {
|
|
360
|
+
...hubOptions,
|
|
361
|
+
...(source.file === undefined ? {} : { file: source.file }),
|
|
362
|
+
});
|
|
346
363
|
for (const [file, info] of Object.entries(checkpoint.info)) {
|
|
347
364
|
sizes.set(file, info.size);
|
|
348
365
|
if (info.sha256 !== undefined)
|
|
@@ -392,7 +409,7 @@ export class Engine {
|
|
|
392
409
|
* signal and reports the weight bytes read as the `"load"` phase.
|
|
393
410
|
*/
|
|
394
411
|
#jsSource(opened, active, progress, bindings) {
|
|
395
|
-
const weightFiles = (opened.list ?? []).filter(
|
|
412
|
+
const weightFiles = (opened.list ?? []).filter(isWeightFile);
|
|
396
413
|
const weightTotal = weightFiles.reduce((n, f) => n + (opened.sizes.get(f) ?? 0), 0);
|
|
397
414
|
let weightRead = 0;
|
|
398
415
|
let lastReport = 0;
|
|
@@ -400,7 +417,7 @@ export class Engine {
|
|
|
400
417
|
if (active.signal.aborted)
|
|
401
418
|
throw abortError(active.signal);
|
|
402
419
|
const bytes = await opened.read(path, start, end);
|
|
403
|
-
if (bytes !== null &&
|
|
420
|
+
if (bytes !== null && isWeightFile(path)) {
|
|
404
421
|
weightRead += bytes.length;
|
|
405
422
|
const t = now();
|
|
406
423
|
if (t - lastReport > 50) {
|
|
@@ -504,7 +521,7 @@ export class Engine {
|
|
|
504
521
|
const adapter = adapterSource === undefined
|
|
505
522
|
? undefined
|
|
506
523
|
: await this.#openSource(active, adapterSource, options.cacheDir, progress, createHasher, "adapter");
|
|
507
|
-
return this.#loadNative(native.addon, opened, adapter, options, active, started, progress);
|
|
524
|
+
return this.#loadNative(native.addon, opened, adapter, options, active, started, progress, ggufFileOf(source, opened));
|
|
508
525
|
}
|
|
509
526
|
const engine = await initEngineWasm({
|
|
510
527
|
...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
|
|
@@ -517,11 +534,16 @@ export class Engine {
|
|
|
517
534
|
? undefined
|
|
518
535
|
: await this.#openSource(active, adapterSource, options.cacheDir, progress, wasmHasher, "adapter");
|
|
519
536
|
const { source: jsSource, weightTotal } = this.#jsSource(opened, active, progress, engine.bindings);
|
|
520
|
-
const
|
|
537
|
+
const gguf = ggufFileOf(source, opened);
|
|
538
|
+
// A GGUF file usually holds its weights in the format they load in: no
|
|
539
|
+
// converted-weight cache (whose files are keyed by repository).
|
|
540
|
+
const weightCache = gguf === undefined ? await this.#openWeightCache(opened, options, progress, engine.bindings) : undefined;
|
|
521
541
|
let wasm;
|
|
522
542
|
try {
|
|
523
543
|
wasm = await WasmModel.load(jsSource, JSON.stringify({
|
|
524
|
-
|
|
544
|
+
// `auto` on a GGUF file: the engine keeps the file's own format.
|
|
545
|
+
...(options.quant === "auto" ? {} : { format: options.quant }),
|
|
546
|
+
...(gguf === undefined ? {} : { ggufFile: gguf }),
|
|
525
547
|
device: options.device ?? "auto",
|
|
526
548
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
527
549
|
...(options.deterministic === true ? { deterministic: true } : {}),
|
|
@@ -604,10 +626,13 @@ export class Engine {
|
|
|
604
626
|
* the download wrote (the command-line tool's layout), with its
|
|
605
627
|
* converted-weight cache next to it.
|
|
606
628
|
*/
|
|
607
|
-
async #loadNative(addon, opened, adapter, options, active, started, progress) {
|
|
608
|
-
const
|
|
609
|
-
if (
|
|
629
|
+
async #loadNative(addon, opened, adapter, options, active, started, progress, gguf) {
|
|
630
|
+
const snapshot = await snapshotDirectory(opened);
|
|
631
|
+
if (snapshot === undefined) {
|
|
610
632
|
throw new WebslmError("ENGINE", "the native engine needs the model in the cache directory");
|
|
633
|
+
}
|
|
634
|
+
// A GGUF file is loaded by its path (its directory holds the tokenizer files).
|
|
635
|
+
const dir = gguf === undefined ? snapshot : await joinFsPath(snapshot, gguf);
|
|
611
636
|
// Block-quantized weights only, as the WebAssembly engine keeps them
|
|
612
637
|
// (float formats convert quickly).
|
|
613
638
|
const cache = options.weightCache !== false &&
|
|
@@ -615,11 +640,16 @@ export class Engine {
|
|
|
615
640
|
(options.autoQuant === true || options.quant !== "f32") &&
|
|
616
641
|
opened.repo !== undefined &&
|
|
617
642
|
opened.revision !== undefined
|
|
618
|
-
?
|
|
643
|
+
? gguf === undefined
|
|
644
|
+
? { weightCacheDir: await joinFsPath(dir, "quantized"), weightCacheKey: `${opened.repo}@${opened.revision}` }
|
|
645
|
+
: {
|
|
646
|
+
weightCacheDir: await joinFsPath(snapshot, "quantized", gguf),
|
|
647
|
+
weightCacheKey: `${opened.repo}@${opened.revision}/${gguf}`,
|
|
648
|
+
}
|
|
619
649
|
: {};
|
|
620
650
|
const adapterDir = adapter === undefined ? undefined : await adapterDirectory(adapter);
|
|
621
651
|
const weightTotal = [...opened.sizes]
|
|
622
|
-
.filter(([file]) => file
|
|
652
|
+
.filter(([file]) => isWeightFile(file))
|
|
623
653
|
.reduce((n, [, size]) => n + size, 0);
|
|
624
654
|
progress({ phase: "load", loadedBytes: 0, totalBytes: weightTotal, overallLoadedBytes: 0, overallTotalBytes: weightTotal });
|
|
625
655
|
let model;
|