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.
- package/LICENSE +21 -0
- package/README.md +373 -2
- package/dist/ai-sdk/index.d.ts +81 -0
- package/dist/ai-sdk/index.js +90 -0
- package/dist/ai-sdk/language-model.d.ts +77 -0
- package/dist/ai-sdk/language-model.js +422 -0
- package/dist/ai-sdk/loader.d.ts +54 -0
- package/dist/ai-sdk/loader.js +170 -0
- package/dist/ai-sdk/output.d.ts +43 -0
- package/dist/ai-sdk/output.js +152 -0
- package/dist/ai-sdk/prompt.d.ts +21 -0
- package/dist/ai-sdk/prompt.js +111 -0
- package/dist/async-queue.d.ts +22 -0
- package/dist/async-queue.js +70 -0
- package/dist/cache/cache-api.d.ts +29 -0
- package/dist/cache/cache-api.js +115 -0
- package/dist/cache/index.d.ts +21 -0
- package/dist/cache/index.js +42 -0
- package/dist/cache/memory.d.ts +12 -0
- package/dist/cache/memory.js +61 -0
- package/dist/cache/models.d.ts +67 -0
- package/dist/cache/models.js +107 -0
- package/dist/cache/node-fs.d.ts +21 -0
- package/dist/cache/node-fs.js +147 -0
- package/dist/cache/opfs.d.ts +69 -0
- package/dist/cache/opfs.js +181 -0
- package/dist/cache/store.d.ts +53 -0
- package/dist/cache/store.js +64 -0
- package/dist/cache-management.d.ts +23 -0
- package/dist/cache-management.js +58 -0
- package/dist/capabilities.d.ts +67 -0
- package/dist/capabilities.js +55 -0
- package/dist/client.d.ts +61 -0
- package/dist/client.js +256 -0
- package/dist/curated.d.ts +22 -0
- package/dist/curated.js +53 -0
- package/dist/download.d.ts +51 -0
- package/dist/download.js +289 -0
- package/dist/engine.d.ts +54 -0
- package/dist/engine.js +510 -0
- package/dist/errors.d.ts +81 -0
- package/dist/errors.js +89 -0
- package/dist/hub.d.ts +185 -0
- package/dist/hub.js +409 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +41 -0
- package/dist/models.d.ts +225 -0
- package/dist/models.js +730 -0
- package/dist/node-pool-worker.d.ts +6 -0
- package/dist/node-pool-worker.js +32 -0
- package/dist/node-web-worker.d.ts +23 -0
- package/dist/node-web-worker.js +84 -0
- package/dist/node-worker.d.ts +2 -0
- package/dist/node-worker.js +9 -0
- package/dist/pool-worker.d.ts +36 -0
- package/dist/pool-worker.js +30 -0
- package/dist/pool.d.ts +17 -0
- package/dist/pool.js +41 -0
- package/dist/protocol.d.ts +246 -0
- package/dist/protocol.js +19 -0
- package/dist/runtime.d.ts +21 -0
- package/dist/runtime.js +53 -0
- package/dist/safetensors.d.ts +20 -0
- package/dist/safetensors.js +2 -0
- package/dist/simple.d.ts +310 -0
- package/dist/simple.js +553 -0
- package/dist/types.d.ts +412 -0
- package/dist/types.js +2 -0
- package/dist/wasm-flavour.d.ts +85 -0
- package/dist/wasm-flavour.js +169 -0
- package/dist/wasm.d.ts +34 -0
- package/dist/wasm.js +38 -0
- package/dist/worker.d.ts +6 -0
- package/dist/worker.js +11 -0
- package/package.json +92 -3
- package/wasm/relaxed/webslm_wasm.d.ts +325 -0
- package/wasm/relaxed/webslm_wasm.js +1899 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/simd/webslm_wasm.d.ts +325 -0
- package/wasm/simd/webslm_wasm.js +1899 -0
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
- package/wasm/threads/webslm_wasm.d.ts +357 -0
- package/wasm/threads/webslm_wasm.js +2100 -0
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
package/dist/hub.d.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hugging Face Hub client: revision lookup, file URLs, model search and
|
|
3
|
+
* compatibility checks. Everything here is plain `fetch`; no weights are
|
|
4
|
+
* downloaded by the search and check helpers.
|
|
5
|
+
*/
|
|
6
|
+
/** Default Hub endpoint. */
|
|
7
|
+
export declare const DEFAULT_HUB_URL = "https://huggingface.co";
|
|
8
|
+
/**
|
|
9
|
+
* `model_type` values (from `config.json`) of the architectures this release
|
|
10
|
+
* runs. Kept in sync with the engine's `supportedModelTypes()` by a test.
|
|
11
|
+
*/
|
|
12
|
+
export declare const SUPPORTED_MODEL_TYPES: readonly string[];
|
|
13
|
+
/** Files read besides the weights, when the repository has them. */
|
|
14
|
+
export declare const CHECKPOINT_SIDE_FILES: readonly string[];
|
|
15
|
+
export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
16
|
+
export declare const SAFETENSORS_SINGLE = "model.safetensors";
|
|
17
|
+
/** Configuration of a PEFT LoRA adapter. */
|
|
18
|
+
export declare const ADAPTER_CONFIG = "adapter_config.json";
|
|
19
|
+
/** Weights of a PEFT LoRA adapter. */
|
|
20
|
+
export declare const ADAPTER_WEIGHTS = "adapter_model.safetensors";
|
|
21
|
+
/**
|
|
22
|
+
* Whether a repository file list is a PEFT LoRA adapter rather than a model:
|
|
23
|
+
* `adapter_config.json` and `adapter_model.safetensors`, no `config.json`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isAdapterListing(names: readonly string[]): boolean;
|
|
26
|
+
/** Options shared by the Hub helpers. */
|
|
27
|
+
export interface HubOptions {
|
|
28
|
+
/** Hub endpoint (mirrors, self-hosting). Defaults to `https://huggingface.co`. */
|
|
29
|
+
readonly hubUrl?: string;
|
|
30
|
+
/** Access token for gated or private repositories. Only sent to `hubUrl`. */
|
|
31
|
+
readonly token?: string;
|
|
32
|
+
readonly signal?: AbortSignal;
|
|
33
|
+
/** `fetch` implementation (defaults to the global one). */
|
|
34
|
+
readonly fetch?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
/** A file of a repository revision. */
|
|
37
|
+
export interface HubFile {
|
|
38
|
+
readonly name: string;
|
|
39
|
+
readonly size?: number;
|
|
40
|
+
/** SHA-256 of LFS files (weights), as published by the Hub. */
|
|
41
|
+
readonly lfsSha256?: string;
|
|
42
|
+
}
|
|
43
|
+
/** A resolved repository revision. */
|
|
44
|
+
export interface RevisionInfo {
|
|
45
|
+
readonly repo: string;
|
|
46
|
+
/** Commit sha. */
|
|
47
|
+
readonly sha: string;
|
|
48
|
+
readonly files: readonly HubFile[];
|
|
49
|
+
readonly gated: false | "auto" | "manual";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The Hub endpoint: `hubUrl`, else `HF_ENDPOINT` from the environment (Node,
|
|
53
|
+
* Bun, Deno; a mirror or a local stand-in, as for the `webslm` command-line
|
|
54
|
+
* tool and `huggingface_hub`), else {@link DEFAULT_HUB_URL}.
|
|
55
|
+
*/
|
|
56
|
+
export declare function hubBase(hubUrl?: string): string;
|
|
57
|
+
/** URL of a file at a revision. */
|
|
58
|
+
export declare function fileUrl(repo: string, revision: string, file: string, hubUrl?: string): string;
|
|
59
|
+
/** Request headers, with the token only for requests to the Hub itself. */
|
|
60
|
+
export declare function hubHeaders(url: string, options: HubOptions, extra?: Record<string, string>): Record<string, string>;
|
|
61
|
+
/**
|
|
62
|
+
* Whether network access is forbidden: `WEBSLM_OFFLINE` or `HF_HUB_OFFLINE`
|
|
63
|
+
* set to `1`, `true`, `yes` or `on` in the environment (Node, Bun, Deno), as
|
|
64
|
+
* for the `webslm` command-line tool. Models already in the cache still load.
|
|
65
|
+
*/
|
|
66
|
+
export declare function offlineMode(): boolean;
|
|
67
|
+
/** Fetches `url`, mapping failures to {@link WebslmError}s; refused in {@link offlineMode}. */
|
|
68
|
+
export declare function hubFetch(url: string, options: HubOptions, init?: {
|
|
69
|
+
headers?: Record<string, string>;
|
|
70
|
+
}, what?: string): Promise<Response>;
|
|
71
|
+
/** Resolves `revision` (branch, tag or sha) of `repo` and lists its files with sizes. */
|
|
72
|
+
export declare function fetchRevision(repo: string, revision: string, options?: HubOptions): Promise<RevisionInfo>;
|
|
73
|
+
/**
|
|
74
|
+
* Picks the files to download: the side files the repository has, plus the
|
|
75
|
+
* weights (the shards named by the index, `model.safetensors`, or every
|
|
76
|
+
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
77
|
+
*/
|
|
78
|
+
export declare function selectCheckpointFiles(names: readonly string[], index?: {
|
|
79
|
+
weight_map?: Record<string, string>;
|
|
80
|
+
}): {
|
|
81
|
+
side: string[];
|
|
82
|
+
weights: string[];
|
|
83
|
+
index?: string;
|
|
84
|
+
};
|
|
85
|
+
/** A repository returned by {@link searchModels}. */
|
|
86
|
+
export interface HubModel {
|
|
87
|
+
readonly repo: string;
|
|
88
|
+
/** `model_type` from the repository's config, when published. */
|
|
89
|
+
readonly modelType?: string;
|
|
90
|
+
readonly architectures?: readonly string[];
|
|
91
|
+
/** Parameter count from the safetensors metadata. */
|
|
92
|
+
readonly params?: number;
|
|
93
|
+
/** Size of the safetensors weights in bytes. */
|
|
94
|
+
readonly sizeBytes?: number;
|
|
95
|
+
/** Approximate engine memory for the weights, per quant. */
|
|
96
|
+
readonly estimatedMemoryBytes?: {
|
|
97
|
+
readonly q8: number;
|
|
98
|
+
readonly q4: number;
|
|
99
|
+
readonly f32: number;
|
|
100
|
+
};
|
|
101
|
+
/** Whether a token with accepted terms is needed to download it. */
|
|
102
|
+
readonly gated: false | "auto" | "manual";
|
|
103
|
+
/** Whether webslm can run it (architecture supported, safetensors weights, under `maxParams`). */
|
|
104
|
+
readonly supported: boolean;
|
|
105
|
+
/** Why it is not supported. */
|
|
106
|
+
readonly reason?: string;
|
|
107
|
+
readonly downloads?: number;
|
|
108
|
+
readonly pipelineTag?: string;
|
|
109
|
+
}
|
|
110
|
+
export interface SearchModelsOptions extends HubOptions {
|
|
111
|
+
/** Largest parameter count considered runnable (default 2e9). */
|
|
112
|
+
readonly maxParams?: number;
|
|
113
|
+
/** Repositories requested from the Hub (default 20). */
|
|
114
|
+
readonly limit?: number;
|
|
115
|
+
/** Drop unsupported repositories from the result (default `false`). */
|
|
116
|
+
readonly supportedOnly?: boolean;
|
|
117
|
+
}
|
|
118
|
+
/** Bytes of a tensor collection given its parameter count per dtype. */
|
|
119
|
+
export declare function bytesForParams(paramsByDtype: Readonly<Record<string, number>>): number;
|
|
120
|
+
/** Weight memory once loaded: Q8_0 stores 34 bytes per 32 values, Q4_0 18. */
|
|
121
|
+
export declare function estimateMemory(params: number): {
|
|
122
|
+
q8: number;
|
|
123
|
+
q4: number;
|
|
124
|
+
f32: number;
|
|
125
|
+
};
|
|
126
|
+
/** Why a model type cannot run, or `undefined` when it can. */
|
|
127
|
+
export declare function unsupportedReason(modelType: string | undefined): string | undefined;
|
|
128
|
+
/**
|
|
129
|
+
* Why a checkpoint's dtypes rule it out: pre-quantized weights (MLX, GPTQ,
|
|
130
|
+
* AWQ, bitsandbytes, FP8) packed in integer or 8-bit float tensors, which
|
|
131
|
+
* webslm does not read. A few integer buffers (position ids) are fine.
|
|
132
|
+
*/
|
|
133
|
+
export declare function packedWeightsReason(byDtype: Readonly<Record<string, number>>): string | undefined;
|
|
134
|
+
/**
|
|
135
|
+
* Searches the Hub for models matching `query`, most downloaded first, and
|
|
136
|
+
* tells for each whether webslm can run it. No weights are downloaded.
|
|
137
|
+
*/
|
|
138
|
+
export declare function searchModels(query: string, options?: SearchModelsOptions): Promise<HubModel[]>;
|
|
139
|
+
/** `1.5B`, `360M`, `135M`. */
|
|
140
|
+
export declare function formatParams(params: number): string;
|
|
141
|
+
/** Result of {@link checkModel}. */
|
|
142
|
+
export interface ModelCheck {
|
|
143
|
+
readonly repo: string;
|
|
144
|
+
readonly revision: string;
|
|
145
|
+
/** Commit sha the revision resolved to. */
|
|
146
|
+
readonly sha: string;
|
|
147
|
+
readonly supported: boolean;
|
|
148
|
+
/** Everything that prevents loading (empty when supported). */
|
|
149
|
+
readonly reasons: readonly string[];
|
|
150
|
+
readonly modelType?: string;
|
|
151
|
+
readonly gated: false | "auto" | "manual";
|
|
152
|
+
readonly hasTokenizer: boolean;
|
|
153
|
+
readonly hasChatTemplate: boolean;
|
|
154
|
+
/** Safetensors files holding the weights. */
|
|
155
|
+
readonly weightFiles: readonly string[];
|
|
156
|
+
/** Every file a load downloads. */
|
|
157
|
+
readonly files: readonly string[];
|
|
158
|
+
/** Parameter count, from the safetensors headers. */
|
|
159
|
+
readonly params: number;
|
|
160
|
+
/** Parameters per dtype. */
|
|
161
|
+
readonly dtypes: Readonly<Record<string, number>>;
|
|
162
|
+
/** Bytes to download. */
|
|
163
|
+
readonly sizeBytes: number;
|
|
164
|
+
readonly estimatedMemoryBytes: {
|
|
165
|
+
readonly q8: number;
|
|
166
|
+
readonly q4: number;
|
|
167
|
+
readonly f32: number;
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export interface CheckModelOptions extends HubOptions {
|
|
171
|
+
/** Defaults to `"main"`. */
|
|
172
|
+
readonly revision?: string;
|
|
173
|
+
}
|
|
174
|
+
/** A parsed safetensors header: tensor name to dtype and shape. */
|
|
175
|
+
export type HeaderTensors = Record<string, {
|
|
176
|
+
dtype: string;
|
|
177
|
+
shape: number[];
|
|
178
|
+
}>;
|
|
179
|
+
/** Reads a safetensors header with two Range requests. */
|
|
180
|
+
export declare function fetchSafetensorsHeader(url: string, options: HubOptions): Promise<HeaderTensors>;
|
|
181
|
+
/**
|
|
182
|
+
* Checks that webslm can run `repo` without downloading weights: config,
|
|
183
|
+
* tokenizer and chat template present, safetensors headers read by Range.
|
|
184
|
+
*/
|
|
185
|
+
export declare function checkModel(repo: string, options?: CheckModelOptions): Promise<ModelCheck>;
|
package/dist/hub.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hugging Face Hub client: revision lookup, file URLs, model search and
|
|
3
|
+
* compatibility checks. Everything here is plain `fetch`; no weights are
|
|
4
|
+
* downloaded by the search and check helpers.
|
|
5
|
+
*/
|
|
6
|
+
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
7
|
+
/** Default Hub endpoint. */
|
|
8
|
+
export const DEFAULT_HUB_URL = "https://huggingface.co";
|
|
9
|
+
/**
|
|
10
|
+
* `model_type` values (from `config.json`) of the architectures this release
|
|
11
|
+
* runs. Kept in sync with the engine's `supportedModelTypes()` by a test.
|
|
12
|
+
*/
|
|
13
|
+
export const SUPPORTED_MODEL_TYPES = [
|
|
14
|
+
"llama",
|
|
15
|
+
"mistral",
|
|
16
|
+
"qwen2",
|
|
17
|
+
"qwen3",
|
|
18
|
+
"lfm2",
|
|
19
|
+
"lfm3",
|
|
20
|
+
"qwen3_5",
|
|
21
|
+
"qwen3_5_text",
|
|
22
|
+
];
|
|
23
|
+
/** Files read besides the weights, when the repository has them. */
|
|
24
|
+
export const CHECKPOINT_SIDE_FILES = [
|
|
25
|
+
"config.json",
|
|
26
|
+
"generation_config.json",
|
|
27
|
+
"tokenizer.json",
|
|
28
|
+
"tokenizer_config.json",
|
|
29
|
+
"special_tokens_map.json",
|
|
30
|
+
"chat_template.jinja",
|
|
31
|
+
"chat_template.json",
|
|
32
|
+
];
|
|
33
|
+
export const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
34
|
+
export const SAFETENSORS_SINGLE = "model.safetensors";
|
|
35
|
+
/** Configuration of a PEFT LoRA adapter. */
|
|
36
|
+
export const ADAPTER_CONFIG = "adapter_config.json";
|
|
37
|
+
/** Weights of a PEFT LoRA adapter. */
|
|
38
|
+
export const ADAPTER_WEIGHTS = "adapter_model.safetensors";
|
|
39
|
+
/**
|
|
40
|
+
* Whether a repository file list is a PEFT LoRA adapter rather than a model:
|
|
41
|
+
* `adapter_config.json` and `adapter_model.safetensors`, no `config.json`.
|
|
42
|
+
*/
|
|
43
|
+
export function isAdapterListing(names) {
|
|
44
|
+
const present = new Set(names);
|
|
45
|
+
return present.has(ADAPTER_CONFIG) && present.has(ADAPTER_WEIGHTS) && !present.has("config.json");
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The Hub endpoint: `hubUrl`, else `HF_ENDPOINT` from the environment (Node,
|
|
49
|
+
* Bun, Deno; a mirror or a local stand-in, as for the `webslm` command-line
|
|
50
|
+
* tool and `huggingface_hub`), else {@link DEFAULT_HUB_URL}.
|
|
51
|
+
*/
|
|
52
|
+
export function hubBase(hubUrl) {
|
|
53
|
+
return (hubUrl ?? endpointFromEnv() ?? DEFAULT_HUB_URL).replace(/\/+$/, "");
|
|
54
|
+
}
|
|
55
|
+
function endpointFromEnv() {
|
|
56
|
+
const env = globalThis.process?.env;
|
|
57
|
+
const value = env?.HF_ENDPOINT?.trim();
|
|
58
|
+
return value === undefined || value === "" ? undefined : value;
|
|
59
|
+
}
|
|
60
|
+
function encodePath(path) {
|
|
61
|
+
return path.split("/").map(encodeURIComponent).join("/");
|
|
62
|
+
}
|
|
63
|
+
/** URL of a file at a revision. */
|
|
64
|
+
export function fileUrl(repo, revision, file, hubUrl) {
|
|
65
|
+
return `${hubBase(hubUrl)}/${repo}/resolve/${encodeURIComponent(revision)}/${encodePath(file)}`;
|
|
66
|
+
}
|
|
67
|
+
/** Request headers, with the token only for requests to the Hub itself. */
|
|
68
|
+
export function hubHeaders(url, options, extra) {
|
|
69
|
+
const headers = { ...extra };
|
|
70
|
+
if (options.token !== undefined && options.token !== "") {
|
|
71
|
+
const hub = new URL(hubBase(options.hubUrl));
|
|
72
|
+
if (new URL(url).origin === hub.origin)
|
|
73
|
+
headers.authorization = `Bearer ${options.token}`;
|
|
74
|
+
}
|
|
75
|
+
return headers;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Whether network access is forbidden: `WEBSLM_OFFLINE` or `HF_HUB_OFFLINE`
|
|
79
|
+
* set to `1`, `true`, `yes` or `on` in the environment (Node, Bun, Deno), as
|
|
80
|
+
* for the `webslm` command-line tool. Models already in the cache still load.
|
|
81
|
+
*/
|
|
82
|
+
export function offlineMode() {
|
|
83
|
+
const env = globalThis.process?.env;
|
|
84
|
+
if (env === undefined)
|
|
85
|
+
return false;
|
|
86
|
+
return ["WEBSLM_OFFLINE", "HF_HUB_OFFLINE"].some((name) => ["1", "true", "yes", "on"].includes((env[name] ?? "").trim().toLowerCase()));
|
|
87
|
+
}
|
|
88
|
+
/** Fetches `url`, mapping failures to {@link WebslmError}s; refused in {@link offlineMode}. */
|
|
89
|
+
export async function hubFetch(url, options, init = {}, what = url) {
|
|
90
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
91
|
+
if (isAborted(options.signal))
|
|
92
|
+
throw abortError(options.signal);
|
|
93
|
+
if (offlineMode()) {
|
|
94
|
+
throw new WebslmError("NETWORK", `offline mode is on (WEBSLM_OFFLINE / HF_HUB_OFFLINE): cannot fetch ${what}; only cached models load`);
|
|
95
|
+
}
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
const requestInit = { headers: hubHeaders(url, options, init.headers) };
|
|
99
|
+
if (options.signal !== undefined)
|
|
100
|
+
requestInit.signal = options.signal;
|
|
101
|
+
response = await fetchImpl(url, requestInit);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (isAborted(options.signal))
|
|
105
|
+
throw abortError(options.signal);
|
|
106
|
+
throw toWebslmError(error, "NETWORK");
|
|
107
|
+
}
|
|
108
|
+
if (!response.ok)
|
|
109
|
+
throw await httpError(response, what);
|
|
110
|
+
return response;
|
|
111
|
+
}
|
|
112
|
+
async function httpError(response, what) {
|
|
113
|
+
let detail = "";
|
|
114
|
+
try {
|
|
115
|
+
const body = (await response.json());
|
|
116
|
+
if (typeof body.error === "string")
|
|
117
|
+
detail = `: ${body.error}`;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// Not JSON.
|
|
121
|
+
}
|
|
122
|
+
const { status } = response;
|
|
123
|
+
if (status === 401 || status === 403) {
|
|
124
|
+
return new WebslmError("UNAUTHORIZED", `${what} needs authorization (HTTP ${status}${detail}); the repository may be gated or private: accept its terms on the Hub and pass a token`);
|
|
125
|
+
}
|
|
126
|
+
if (status === 404)
|
|
127
|
+
return new WebslmError("NOT_FOUND", `${what} was not found (HTTP 404${detail})`);
|
|
128
|
+
return new WebslmError("NETWORK", `${what} failed with HTTP ${status}${detail}`);
|
|
129
|
+
}
|
|
130
|
+
/** Resolves `revision` (branch, tag or sha) of `repo` and lists its files with sizes. */
|
|
131
|
+
export async function fetchRevision(repo, revision, options = {}) {
|
|
132
|
+
const url = `${hubBase(options.hubUrl)}/api/models/${repo}/revision/${encodeURIComponent(revision)}?blobs=true`;
|
|
133
|
+
const response = await hubFetch(url, options, {}, `${repo}@${revision}`);
|
|
134
|
+
const body = (await response.json());
|
|
135
|
+
if (typeof body.sha !== "string") {
|
|
136
|
+
throw new WebslmError("NETWORK", `unexpected Hub response for ${repo}@${revision}: no sha`);
|
|
137
|
+
}
|
|
138
|
+
const files = [];
|
|
139
|
+
for (const sibling of body.siblings ?? []) {
|
|
140
|
+
if (typeof sibling.rfilename !== "string")
|
|
141
|
+
continue;
|
|
142
|
+
const file = { name: sibling.rfilename };
|
|
143
|
+
if (typeof sibling.size === "number")
|
|
144
|
+
file.size = sibling.size;
|
|
145
|
+
if (typeof sibling.lfs?.sha256 === "string")
|
|
146
|
+
file.lfsSha256 = sibling.lfs.sha256;
|
|
147
|
+
files.push(file);
|
|
148
|
+
}
|
|
149
|
+
return { repo, sha: body.sha, files, gated: parseGated(body.gated) };
|
|
150
|
+
}
|
|
151
|
+
function parseGated(value) {
|
|
152
|
+
return value === "auto" || value === "manual" ? value : false;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Picks the files to download: the side files the repository has, plus the
|
|
156
|
+
* weights (the shards named by the index, `model.safetensors`, or every
|
|
157
|
+
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
158
|
+
*/
|
|
159
|
+
export function selectCheckpointFiles(names, index) {
|
|
160
|
+
// A LoRA adapter needs only its two files.
|
|
161
|
+
if (isAdapterListing(names))
|
|
162
|
+
return { side: [ADAPTER_CONFIG], weights: [ADAPTER_WEIGHTS] };
|
|
163
|
+
const present = new Set(names);
|
|
164
|
+
const side = CHECKPOINT_SIDE_FILES.filter((f) => present.has(f));
|
|
165
|
+
if (present.has(SAFETENSORS_INDEX) && index !== undefined) {
|
|
166
|
+
const weights = [...new Set(Object.values(index.weight_map ?? {}))].sort();
|
|
167
|
+
return { side, weights, index: SAFETENSORS_INDEX };
|
|
168
|
+
}
|
|
169
|
+
if (present.has(SAFETENSORS_SINGLE))
|
|
170
|
+
return { side, weights: [SAFETENSORS_SINGLE] };
|
|
171
|
+
const weights = names.filter((n) => !n.includes("/") && n.endsWith(".safetensors")).sort();
|
|
172
|
+
return { side, weights };
|
|
173
|
+
}
|
|
174
|
+
const DTYPE_BYTES = {
|
|
175
|
+
F64: 8,
|
|
176
|
+
I64: 8,
|
|
177
|
+
U64: 8,
|
|
178
|
+
F32: 4,
|
|
179
|
+
I32: 4,
|
|
180
|
+
U32: 4,
|
|
181
|
+
F16: 2,
|
|
182
|
+
BF16: 2,
|
|
183
|
+
I16: 2,
|
|
184
|
+
U16: 2,
|
|
185
|
+
F8_E4M3: 1,
|
|
186
|
+
F8_E5M2: 1,
|
|
187
|
+
I8: 1,
|
|
188
|
+
U8: 1,
|
|
189
|
+
BOOL: 1,
|
|
190
|
+
};
|
|
191
|
+
/** Bytes of a tensor collection given its parameter count per dtype. */
|
|
192
|
+
export function bytesForParams(paramsByDtype) {
|
|
193
|
+
let total = 0;
|
|
194
|
+
for (const [dtype, count] of Object.entries(paramsByDtype))
|
|
195
|
+
total += count * (DTYPE_BYTES[dtype] ?? 2);
|
|
196
|
+
return total;
|
|
197
|
+
}
|
|
198
|
+
/** Weight memory once loaded: Q8_0 stores 34 bytes per 32 values, Q4_0 18. */
|
|
199
|
+
export function estimateMemory(params) {
|
|
200
|
+
return {
|
|
201
|
+
q8: Math.ceil((params * 34) / 32),
|
|
202
|
+
q4: Math.ceil((params * 18) / 32),
|
|
203
|
+
f32: params * 4,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** Why a model type cannot run, or `undefined` when it can. */
|
|
207
|
+
export function unsupportedReason(modelType) {
|
|
208
|
+
if (modelType === undefined)
|
|
209
|
+
return "no config.json model_type published";
|
|
210
|
+
if (SUPPORTED_MODEL_TYPES.includes(modelType))
|
|
211
|
+
return undefined;
|
|
212
|
+
return `architecture "${modelType}" is not supported yet`;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Why a checkpoint's dtypes rule it out: pre-quantized weights (MLX, GPTQ,
|
|
216
|
+
* AWQ, bitsandbytes, FP8) packed in integer or 8-bit float tensors, which
|
|
217
|
+
* webslm does not read. A few integer buffers (position ids) are fine.
|
|
218
|
+
*/
|
|
219
|
+
export function packedWeightsReason(byDtype) {
|
|
220
|
+
const total = Object.values(byDtype).reduce((a, b) => a + b, 0);
|
|
221
|
+
const packed = Object.entries(byDtype)
|
|
222
|
+
.filter(([dtype, n]) => !["F32", "F16", "BF16", "F64"].includes(dtype) && n * 100 > total)
|
|
223
|
+
.map(([dtype]) => dtype)
|
|
224
|
+
.sort();
|
|
225
|
+
if (packed.length === 0)
|
|
226
|
+
return undefined;
|
|
227
|
+
return `pre-quantized weights (${packed.join(", ")}); webslm converts F32, F16 and BF16 checkpoints itself`;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Searches the Hub for models matching `query`, most downloaded first, and
|
|
231
|
+
* tells for each whether webslm can run it. No weights are downloaded.
|
|
232
|
+
*/
|
|
233
|
+
export async function searchModels(query, options = {}) {
|
|
234
|
+
const maxParams = options.maxParams ?? 2e9;
|
|
235
|
+
const limit = Math.max(1, Math.min(options.limit ?? 20, 100));
|
|
236
|
+
const params = new URLSearchParams({ search: query.trim(), sort: "downloads", limit: String(limit) });
|
|
237
|
+
for (const field of ["safetensors", "config", "gated", "downloads", "pipeline_tag"]) {
|
|
238
|
+
params.append("expand[]", field);
|
|
239
|
+
}
|
|
240
|
+
const url = `${hubBase(options.hubUrl)}/api/models?${params.toString()}`;
|
|
241
|
+
const response = await hubFetch(url, options, {}, `search "${query}"`);
|
|
242
|
+
const body = (await response.json());
|
|
243
|
+
if (!Array.isArray(body))
|
|
244
|
+
throw new WebslmError("NETWORK", "unexpected Hub search response");
|
|
245
|
+
const models = body.flatMap((entry) => {
|
|
246
|
+
const model = toHubModel(entry, maxParams);
|
|
247
|
+
return model === undefined ? [] : [model];
|
|
248
|
+
});
|
|
249
|
+
return options.supportedOnly === true ? models.filter((m) => m.supported) : models;
|
|
250
|
+
}
|
|
251
|
+
function toHubModel(entry, maxParams) {
|
|
252
|
+
if (typeof entry.id !== "string")
|
|
253
|
+
return undefined;
|
|
254
|
+
const modelType = typeof entry.config?.model_type === "string" ? entry.config.model_type : undefined;
|
|
255
|
+
const architectures = Array.isArray(entry.config?.architectures)
|
|
256
|
+
? entry.config.architectures.filter((a) => typeof a === "string")
|
|
257
|
+
: undefined;
|
|
258
|
+
const byDtype = {};
|
|
259
|
+
for (const [dtype, count] of Object.entries(entry.safetensors?.parameters ?? {})) {
|
|
260
|
+
if (typeof count === "number")
|
|
261
|
+
byDtype[dtype] = count;
|
|
262
|
+
}
|
|
263
|
+
const total = entry.safetensors?.total;
|
|
264
|
+
const params = typeof total === "number" ? total : undefined;
|
|
265
|
+
let reason = unsupportedReason(modelType);
|
|
266
|
+
if (reason === undefined && params === undefined)
|
|
267
|
+
reason = "no safetensors weights";
|
|
268
|
+
if (reason === undefined)
|
|
269
|
+
reason = packedWeightsReason(byDtype);
|
|
270
|
+
if (reason === undefined && params !== undefined && params > maxParams) {
|
|
271
|
+
reason = `${formatParams(params)} parameters exceed the ${formatParams(maxParams)} limit`;
|
|
272
|
+
}
|
|
273
|
+
const model = {
|
|
274
|
+
repo: entry.id,
|
|
275
|
+
gated: parseGated(entry.gated),
|
|
276
|
+
supported: reason === undefined,
|
|
277
|
+
};
|
|
278
|
+
if (modelType !== undefined)
|
|
279
|
+
model.modelType = modelType;
|
|
280
|
+
if (architectures !== undefined)
|
|
281
|
+
model.architectures = architectures;
|
|
282
|
+
if (params !== undefined) {
|
|
283
|
+
model.params = params;
|
|
284
|
+
model.sizeBytes = bytesForParams(byDtype);
|
|
285
|
+
model.estimatedMemoryBytes = estimateMemory(params);
|
|
286
|
+
}
|
|
287
|
+
if (reason !== undefined)
|
|
288
|
+
model.reason = reason;
|
|
289
|
+
if (typeof entry.downloads === "number")
|
|
290
|
+
model.downloads = entry.downloads;
|
|
291
|
+
if (typeof entry.pipeline_tag === "string")
|
|
292
|
+
model.pipelineTag = entry.pipeline_tag;
|
|
293
|
+
return model;
|
|
294
|
+
}
|
|
295
|
+
/** `1.5B`, `360M`, `135M`. */
|
|
296
|
+
export function formatParams(params) {
|
|
297
|
+
if (params >= 1e9)
|
|
298
|
+
return `${+(params / 1e9).toFixed(params >= 1e10 ? 0 : 1)}B`;
|
|
299
|
+
if (params >= 1e6)
|
|
300
|
+
return `${Math.round(params / 1e6)}M`;
|
|
301
|
+
if (params >= 1e3)
|
|
302
|
+
return `${Math.round(params / 1e3)}K`;
|
|
303
|
+
return String(params);
|
|
304
|
+
}
|
|
305
|
+
/** Reads a safetensors header with two Range requests. */
|
|
306
|
+
export async function fetchSafetensorsHeader(url, options) {
|
|
307
|
+
const prefix = new Uint8Array(await (await hubFetch(url, options, { headers: { range: "bytes=0-7" } })).arrayBuffer());
|
|
308
|
+
if (prefix.length < 8)
|
|
309
|
+
throw new WebslmError("INVALID_CHECKPOINT", `${url}: truncated safetensors header`);
|
|
310
|
+
const length = Number(new DataView(prefix.buffer, prefix.byteOffset, 8).getBigUint64(0, true));
|
|
311
|
+
if (length > 100 * 1024 * 1024) {
|
|
312
|
+
throw new WebslmError("INVALID_CHECKPOINT", `${url}: safetensors header of ${length} bytes`);
|
|
313
|
+
}
|
|
314
|
+
const response = await hubFetch(url, options, { headers: { range: `bytes=8-${8 + length - 1}` } });
|
|
315
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
316
|
+
// A server that ignores Range sends the whole file.
|
|
317
|
+
const json = bytes.length === length ? bytes : bytes.subarray(8, 8 + length);
|
|
318
|
+
const parsed = JSON.parse(new TextDecoder().decode(json));
|
|
319
|
+
const tensors = {};
|
|
320
|
+
for (const [name, info] of Object.entries(parsed)) {
|
|
321
|
+
if (name === "__metadata__")
|
|
322
|
+
continue;
|
|
323
|
+
const { dtype, shape } = info;
|
|
324
|
+
if (typeof dtype === "string" && Array.isArray(shape)) {
|
|
325
|
+
tensors[name] = { dtype, shape: shape.map(Number) };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return tensors;
|
|
329
|
+
}
|
|
330
|
+
async function fetchJson(url, options) {
|
|
331
|
+
return (await hubFetch(url, options)).json();
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Checks that webslm can run `repo` without downloading weights: config,
|
|
335
|
+
* tokenizer and chat template present, safetensors headers read by Range.
|
|
336
|
+
*/
|
|
337
|
+
export async function checkModel(repo, options = {}) {
|
|
338
|
+
const revision = options.revision ?? "main";
|
|
339
|
+
const info = await fetchRevision(repo, revision, options);
|
|
340
|
+
const names = info.files.map((f) => f.name);
|
|
341
|
+
const reasons = [];
|
|
342
|
+
const url = (file) => fileUrl(repo, info.sha, file, options.hubUrl);
|
|
343
|
+
let modelType;
|
|
344
|
+
if (names.includes("config.json")) {
|
|
345
|
+
const config = (await fetchJson(url("config.json"), options));
|
|
346
|
+
modelType = typeof config.model_type === "string" ? config.model_type : undefined;
|
|
347
|
+
const reason = unsupportedReason(modelType);
|
|
348
|
+
if (reason !== undefined)
|
|
349
|
+
reasons.push(reason);
|
|
350
|
+
}
|
|
351
|
+
else {
|
|
352
|
+
reasons.push("no config.json");
|
|
353
|
+
}
|
|
354
|
+
const hasTokenizer = names.includes("tokenizer.json");
|
|
355
|
+
if (!hasTokenizer)
|
|
356
|
+
reasons.push("no tokenizer.json (only fast tokenizers are supported)");
|
|
357
|
+
let hasChatTemplate = names.includes("chat_template.jinja") || names.includes("chat_template.json");
|
|
358
|
+
if (!hasChatTemplate && names.includes("tokenizer_config.json")) {
|
|
359
|
+
const config = (await fetchJson(url("tokenizer_config.json"), options));
|
|
360
|
+
hasChatTemplate = config.chat_template !== undefined && config.chat_template !== null;
|
|
361
|
+
}
|
|
362
|
+
let index;
|
|
363
|
+
if (names.includes(SAFETENSORS_INDEX)) {
|
|
364
|
+
index = (await fetchJson(url(SAFETENSORS_INDEX), options));
|
|
365
|
+
}
|
|
366
|
+
const selected = selectCheckpointFiles(names, index);
|
|
367
|
+
if (selected.weights.length === 0)
|
|
368
|
+
reasons.push("no safetensors weights");
|
|
369
|
+
const dtypes = {};
|
|
370
|
+
let params = 0;
|
|
371
|
+
let hasEmbeddings = false;
|
|
372
|
+
for (const file of selected.weights) {
|
|
373
|
+
const tensors = await fetchSafetensorsHeader(url(file), options);
|
|
374
|
+
for (const [name, tensor] of Object.entries(tensors)) {
|
|
375
|
+
const count = tensor.shape.reduce((n, d) => n * d, 1);
|
|
376
|
+
params += count;
|
|
377
|
+
dtypes[tensor.dtype] = (dtypes[tensor.dtype] ?? 0) + count;
|
|
378
|
+
if (name === "model.embed_tokens.weight")
|
|
379
|
+
hasEmbeddings = true;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (selected.weights.length > 0 && !hasEmbeddings) {
|
|
383
|
+
reasons.push("unexpected weight layout (no model.embed_tokens.weight)");
|
|
384
|
+
}
|
|
385
|
+
const packed = packedWeightsReason(dtypes);
|
|
386
|
+
if (packed !== undefined)
|
|
387
|
+
reasons.push(packed);
|
|
388
|
+
const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];
|
|
389
|
+
const sizes = new Map(info.files.map((f) => [f.name, f.size ?? 0]));
|
|
390
|
+
const check = {
|
|
391
|
+
repo,
|
|
392
|
+
revision,
|
|
393
|
+
sha: info.sha,
|
|
394
|
+
supported: reasons.length === 0,
|
|
395
|
+
reasons,
|
|
396
|
+
gated: info.gated,
|
|
397
|
+
hasTokenizer,
|
|
398
|
+
hasChatTemplate,
|
|
399
|
+
weightFiles: selected.weights,
|
|
400
|
+
files,
|
|
401
|
+
params,
|
|
402
|
+
dtypes,
|
|
403
|
+
sizeBytes: files.reduce((n, f) => n + (sizes.get(f) ?? 0), 0),
|
|
404
|
+
estimatedMemoryBytes: estimateMemory(params),
|
|
405
|
+
};
|
|
406
|
+
if (modelType !== undefined)
|
|
407
|
+
check.modelType = modelType;
|
|
408
|
+
return check;
|
|
409
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webslm: small language models in the browser and in Node, straight from
|
|
3
|
+
* their original Hugging Face checkpoints.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { ask } from "webslm";
|
|
7
|
+
*
|
|
8
|
+
* console.log(await ask("Write a haiku about the sea"));
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* The simple API is {@link load}, {@link ask}, {@link stream} and
|
|
12
|
+
* {@link LLM.chat}; {@link loadModel}, {@link Model} and {@link Session} are
|
|
13
|
+
* the advanced layer it is built on.
|
|
14
|
+
*
|
|
15
|
+
* @packageDocumentation
|
|
16
|
+
*/
|
|
17
|
+
import type { SafetensorsHeader } from "./safetensors.js";
|
|
18
|
+
export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, type Answer, type AskOptions, type Chat, type ChatOptions, type ChatTurnOptions, type LLM, type PromptOptions, type SharedAskOptions, type SharedStreamOptions, type TextStream, } from "./simple.js";
|
|
19
|
+
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
|
+
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
21
|
+
export type { Activations, AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
22
|
+
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
23
|
+
export { CURATED_MODELS, type CuratedModel } from "./curated.js";
|
|
24
|
+
export { checkModel, DEFAULT_HUB_URL, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
25
|
+
export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
|
|
26
|
+
export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
|
|
27
|
+
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
|
|
28
|
+
export { loadWasm, type WasmExports, type WasmSource } from "./wasm.js";
|
|
29
|
+
/** Version of the Rust engine, read from the WebAssembly module. */
|
|
30
|
+
export declare function version(): Promise<string>;
|
|
31
|
+
/**
|
|
32
|
+
* Parses the header of a safetensors file with the Rust engine.
|
|
33
|
+
*
|
|
34
|
+
* @param bytes At least the 8-byte length prefix and the whole JSON header.
|
|
35
|
+
* @throws Error if the header is malformed.
|
|
36
|
+
*/
|
|
37
|
+
export declare function parseSafetensorsHeader(bytes: Uint8Array): Promise<SafetensorsHeader>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webslm: small language models in the browser and in Node, straight from
|
|
3
|
+
* their original Hugging Face checkpoints.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { ask } from "webslm";
|
|
7
|
+
*
|
|
8
|
+
* console.log(await ask("Write a haiku about the sea"));
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* The simple API is {@link load}, {@link ask}, {@link stream} and
|
|
12
|
+
* {@link LLM.chat}; {@link loadModel}, {@link Model} and {@link Session} are
|
|
13
|
+
* the advanced layer it is built on.
|
|
14
|
+
*
|
|
15
|
+
* @packageDocumentation
|
|
16
|
+
*/
|
|
17
|
+
import { loadWasm } from "./wasm.js";
|
|
18
|
+
export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, } from "./simple.js";
|
|
19
|
+
export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
|
+
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
|
|
21
|
+
export { WebslmError } from "./errors.js";
|
|
22
|
+
export { CURATED_MODELS } from "./curated.js";
|
|
23
|
+
export { checkModel, DEFAULT_HUB_URL, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
24
|
+
export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
|
|
25
|
+
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
|
|
26
|
+
export { loadWasm } from "./wasm.js";
|
|
27
|
+
/** Version of the Rust engine, read from the WebAssembly module. */
|
|
28
|
+
export async function version() {
|
|
29
|
+
const wasm = await loadWasm();
|
|
30
|
+
return wasm.version();
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Parses the header of a safetensors file with the Rust engine.
|
|
34
|
+
*
|
|
35
|
+
* @param bytes At least the 8-byte length prefix and the whole JSON header.
|
|
36
|
+
* @throws Error if the header is malformed.
|
|
37
|
+
*/
|
|
38
|
+
export async function parseSafetensorsHeader(bytes) {
|
|
39
|
+
const wasm = await loadWasm();
|
|
40
|
+
return wasm.parseSafetensorsHeader(bytes);
|
|
41
|
+
}
|