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.
- 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/types.d.ts
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/** Public types of the webslm API. */
|
|
2
|
+
import type { EngineHandle } from "./models.js";
|
|
3
|
+
import type { WasmFlavour } from "./wasm-flavour.js";
|
|
4
|
+
/**
|
|
5
|
+
* Where the model runs. `"auto"` (the default) picks WebGPU for models above
|
|
6
|
+
* ~100M parameters when an adapter is available, the CPU otherwise.
|
|
7
|
+
*/
|
|
8
|
+
export type Device = "auto" | "cpu" | "webgpu";
|
|
9
|
+
/** How weight matrices are stored once loaded. */
|
|
10
|
+
export type Quant = "q8" | "q4" | "f32";
|
|
11
|
+
/**
|
|
12
|
+
* Precision of the activations multiplied against quantized weights (`"q8"`,
|
|
13
|
+
* `"q4"`). `"quantized"` (the default) quantizes them once per matmul on the
|
|
14
|
+
* CPU (exact integer dot products, fastest); `"f32"` keeps them in f32 and
|
|
15
|
+
* dequantizes the weights instead. WebGPU always uses f32 activations.
|
|
16
|
+
*/
|
|
17
|
+
export type Activations = "quantized" | "f32";
|
|
18
|
+
/** Checkpoint files held by the page: bytes from OPFS, IndexedDB, an upload, a training job... */
|
|
19
|
+
export type FileData = Blob | ArrayBuffer | Uint8Array;
|
|
20
|
+
/**
|
|
21
|
+
* Reads a file of the checkpoint (`range` is `[start, end)`, end exclusive),
|
|
22
|
+
* for custom stores: OPFS, IndexedDB, a mirror. Resolve to `null` (or reject
|
|
23
|
+
* with an error whose `code` is `"NOT_FOUND"`) when the file does not exist:
|
|
24
|
+
* optional files such as `generation_config.json` are probed this way.
|
|
25
|
+
*/
|
|
26
|
+
export type FetchFile = (path: string, range?: readonly [number, number]) => Promise<ArrayBuffer | Uint8Array | null | undefined>;
|
|
27
|
+
/** Where a checkpoint comes from. A plain string is a Hugging Face repository id. */
|
|
28
|
+
export type ModelSource =
|
|
29
|
+
/** A Hugging Face repository, downloaded once into the local cache. */
|
|
30
|
+
{
|
|
31
|
+
readonly hub: string;
|
|
32
|
+
readonly revision?: string;
|
|
33
|
+
readonly hubUrl?: string;
|
|
34
|
+
}
|
|
35
|
+
/** Files by name: `"config.json"`, `"tokenizer.json"`, `"model.safetensors"`... */
|
|
36
|
+
| {
|
|
37
|
+
readonly files: Readonly<Record<string, FileData>>;
|
|
38
|
+
}
|
|
39
|
+
/** A custom store. */
|
|
40
|
+
| {
|
|
41
|
+
readonly fetch: FetchFile;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A PEFT LoRA adapter: a Hugging Face repository id (a string or
|
|
45
|
+
* `{ hub }`), files by name (`adapter_config.json` and
|
|
46
|
+
* `adapter_model.safetensors`) or a custom store.
|
|
47
|
+
*/
|
|
48
|
+
export type AdapterSource = string | ModelSource;
|
|
49
|
+
/** Options of {@link Model.applyAdapter}. */
|
|
50
|
+
export interface ApplyAdapterOptions {
|
|
51
|
+
/** Multiplies the adapter's effect: `1` (default) applies it as trained, `0` leaves the base unchanged. */
|
|
52
|
+
readonly scale?: number;
|
|
53
|
+
/** Revision of a hub adapter given as a string. */
|
|
54
|
+
readonly revision?: string;
|
|
55
|
+
/** Hugging Face access token for a gated or private adapter repository. */
|
|
56
|
+
readonly token?: string;
|
|
57
|
+
/** Reports downloading the adapter and reading the affected base weights. */
|
|
58
|
+
readonly onProgress?: (progress: LoadProgress) => void;
|
|
59
|
+
readonly signal?: AbortSignal;
|
|
60
|
+
}
|
|
61
|
+
/** A LoRA adapter merged into a model's weights. */
|
|
62
|
+
export interface LoraInfo {
|
|
63
|
+
/** Modules whose weights changed, e.g. `"model.layers.0.self_attn.q_proj"`. */
|
|
64
|
+
readonly modules: readonly string[];
|
|
65
|
+
readonly scale: number;
|
|
66
|
+
/** Largest rank over the modules. */
|
|
67
|
+
readonly rank: number;
|
|
68
|
+
/** `base_model_name_or_path` from `adapter_config.json`. */
|
|
69
|
+
readonly baseModel?: string;
|
|
70
|
+
/** Hub repository id, when the adapter came from the hub. */
|
|
71
|
+
readonly repo?: string;
|
|
72
|
+
/** Commit sha of the hub revision, when the adapter came from the hub. */
|
|
73
|
+
readonly revision?: string;
|
|
74
|
+
}
|
|
75
|
+
/** Progress of a model load. */
|
|
76
|
+
export interface LoadProgress {
|
|
77
|
+
/**
|
|
78
|
+
* `"resolve"`: looking up the revision; `"download"`: fetching files into
|
|
79
|
+
* the cache; `"load"`: reading weights into the engine; `"ready"`: done.
|
|
80
|
+
*/
|
|
81
|
+
readonly phase: "resolve" | "download" | "load" | "ready";
|
|
82
|
+
/** File being processed, when there is one. */
|
|
83
|
+
readonly file?: string;
|
|
84
|
+
/** Bytes of `file` done so far. */
|
|
85
|
+
readonly loadedBytes: number;
|
|
86
|
+
/** Size of `file`, when known. */
|
|
87
|
+
readonly totalBytes: number;
|
|
88
|
+
/** Bytes done across all files of the phase. */
|
|
89
|
+
readonly overallLoadedBytes: number;
|
|
90
|
+
/** Size of all files of the phase. */
|
|
91
|
+
readonly overallTotalBytes: number;
|
|
92
|
+
/** Whether `file` was already in the cache. */
|
|
93
|
+
readonly cached?: boolean;
|
|
94
|
+
}
|
|
95
|
+
export interface LoadModelOptions {
|
|
96
|
+
/**
|
|
97
|
+
* Defaults to `"auto"`: WebGPU for models above ~100M parameters when an
|
|
98
|
+
* adapter is available, the CPU otherwise. `"webgpu"` falls back to the CPU
|
|
99
|
+
* when no GPU device can be created; {@link ModelInfo.deviceNote} says why.
|
|
100
|
+
*/
|
|
101
|
+
readonly device?: Device;
|
|
102
|
+
/**
|
|
103
|
+
* Weight format. Defaults to `"q8"`; `"q4"` (4-bit, 16-value blocks) is
|
|
104
|
+
* smaller and less accurate.
|
|
105
|
+
*/
|
|
106
|
+
readonly quant?: Quant;
|
|
107
|
+
/**
|
|
108
|
+
* Precision of the activations against quantized weights (default
|
|
109
|
+
* `"quantized"`). With `"f32"`, `quant: "q8"` on a checkpoint whose
|
|
110
|
+
* matrices hold exact Q8_0 values (a Q8_0 model dequantized to f32) gives
|
|
111
|
+
* the results of `quant: "f32"`, bit for bit on the CPU, at a quarter of
|
|
112
|
+
* the memory; matmuls against quantized weights run slower on the CPU.
|
|
113
|
+
*/
|
|
114
|
+
readonly activations?: Activations;
|
|
115
|
+
/** Revision of a hub source given as a string (branch, tag or commit sha). */
|
|
116
|
+
readonly revision?: string;
|
|
117
|
+
/** Hugging Face access token, for gated or private repositories. Sent to the hub only. */
|
|
118
|
+
readonly token?: string;
|
|
119
|
+
/** Largest number of positions a session holds. Defaults to min(4096, model maximum). */
|
|
120
|
+
readonly contextLength?: number;
|
|
121
|
+
/**
|
|
122
|
+
* A PEFT LoRA adapter merged into the weights as they load (in f32,
|
|
123
|
+
* before quantization). It can be swapped or removed later with
|
|
124
|
+
* {@link Model.applyAdapter} and {@link Model.removeAdapter}.
|
|
125
|
+
*/
|
|
126
|
+
readonly adapter?: AdapterSource;
|
|
127
|
+
/** Scale of {@link LoadModelOptions.adapter} (default `1`). */
|
|
128
|
+
readonly adapterScale?: number;
|
|
129
|
+
readonly onProgress?: (progress: LoadProgress) => void;
|
|
130
|
+
readonly signal?: AbortSignal;
|
|
131
|
+
/**
|
|
132
|
+
* Run the engine in a dedicated worker (default `true`): a module Worker in
|
|
133
|
+
* browsers, `worker_threads` in Node. `false` runs it on the calling thread.
|
|
134
|
+
*/
|
|
135
|
+
readonly worker?: boolean;
|
|
136
|
+
/**
|
|
137
|
+
* Load into an engine shared with other models (from `createEngine()`)
|
|
138
|
+
* instead of starting one: several models in one worker. `worker` is then
|
|
139
|
+
* ignored, and `unload()` keeps the engine running.
|
|
140
|
+
*/
|
|
141
|
+
readonly engine?: EngineHandle;
|
|
142
|
+
/**
|
|
143
|
+
* Where the cache lives in Node (default `WEBSLM_CACHE_DIR` or
|
|
144
|
+
* `~/.cache/webslm`). Ignored in browsers, which use OPFS.
|
|
145
|
+
*/
|
|
146
|
+
readonly cacheDir?: string;
|
|
147
|
+
/**
|
|
148
|
+
* Run on CPU kernels whose results are bit-identical in every WebAssembly
|
|
149
|
+
* build and natively (the `webslm` CLI and the Rust crates), at some cost
|
|
150
|
+
* in speed for `f32`, `f16` and `bf16` weights. Same weights and prompt,
|
|
151
|
+
* same logits, whatever the browser, CPU or thread count.
|
|
152
|
+
*/
|
|
153
|
+
readonly deterministic?: boolean;
|
|
154
|
+
/**
|
|
155
|
+
* WebAssembly build to run (advanced; defaults to the fastest one the
|
|
156
|
+
* environment supports: `"threads"` when the page is cross-origin
|
|
157
|
+
* isolated or in Node, `"relaxed"` with relaxed SIMD, else `"simd"`). Each
|
|
158
|
+
* worker instantiates one build: the first model loaded in it decides.
|
|
159
|
+
* A build missing from a package built from source (see the README)
|
|
160
|
+
* fails with `UNSUPPORTED_DEVICE`; the automatic choice skips it.
|
|
161
|
+
*/
|
|
162
|
+
readonly wasmFlavour?: WasmFlavour;
|
|
163
|
+
/**
|
|
164
|
+
* Size of the thread pool of the `"threads"` build. Defaults to the number
|
|
165
|
+
* of logical cores, at most 8.
|
|
166
|
+
*/
|
|
167
|
+
readonly threads?: number;
|
|
168
|
+
}
|
|
169
|
+
/** How the CPU backend runs a model. */
|
|
170
|
+
export interface CpuInfo {
|
|
171
|
+
/** The WebAssembly build. */
|
|
172
|
+
readonly flavour: WasmFlavour;
|
|
173
|
+
/** CPU kernel set, e.g. `"relaxed-simd"`. */
|
|
174
|
+
readonly kernels: string;
|
|
175
|
+
/** Threads the kernels use. */
|
|
176
|
+
readonly threads: number;
|
|
177
|
+
/** Whether the deterministic kernels run (see {@link LoadModelOptions.deterministic}). */
|
|
178
|
+
readonly deterministic: boolean;
|
|
179
|
+
/**
|
|
180
|
+
* Why the WebAssembly build is not the one the environment supports best:
|
|
181
|
+
* the automatic choice skipped builds that are not installed (a package
|
|
182
|
+
* built from source with only some flavours).
|
|
183
|
+
*/
|
|
184
|
+
readonly flavourNote?: string;
|
|
185
|
+
}
|
|
186
|
+
export interface ChatMessage {
|
|
187
|
+
readonly role: "system" | "user" | "assistant" | (string & {});
|
|
188
|
+
readonly content: string;
|
|
189
|
+
}
|
|
190
|
+
/** Options of a generation. Unset sampling options come from the checkpoint's `generation_config.json`. */
|
|
191
|
+
export interface GenerateOptions {
|
|
192
|
+
/** Largest number of new tokens (default 512). */
|
|
193
|
+
readonly maxTokens?: number;
|
|
194
|
+
/** `0` is greedy decoding. */
|
|
195
|
+
readonly temperature?: number;
|
|
196
|
+
readonly topK?: number;
|
|
197
|
+
readonly topP?: number;
|
|
198
|
+
readonly minP?: number;
|
|
199
|
+
readonly repetitionPenalty?: number;
|
|
200
|
+
/** Seed of the sampler, for reproducible sampling. */
|
|
201
|
+
readonly seed?: number;
|
|
202
|
+
/** Strings that end the generation (not included in the output). */
|
|
203
|
+
readonly stop?: readonly string[];
|
|
204
|
+
/** Extra chat template variables, e.g. `{ enable_thinking: false }` for Qwen3. */
|
|
205
|
+
readonly templateKwargs?: Readonly<Record<string, unknown>>;
|
|
206
|
+
/** Keep generating past stop tokens (for comparisons with reference implementations). */
|
|
207
|
+
readonly ignoreStopTokens?: boolean;
|
|
208
|
+
/** Penalty on tokens already generated, once each (OpenAI's presence penalty; 0 disables). */
|
|
209
|
+
readonly presencePenalty?: number;
|
|
210
|
+
/** Penalty on tokens already generated, per occurrence (OpenAI's frequency penalty; 0 disables). */
|
|
211
|
+
readonly frequencyPenalty?: number;
|
|
212
|
+
/** Token ids that end the generation, besides the checkpoint's own (left out of the text). */
|
|
213
|
+
readonly stopTokens?: readonly number[];
|
|
214
|
+
/**
|
|
215
|
+
* Per-token log-probabilities, passed to `onToken`: `true` for the chosen
|
|
216
|
+
* token's, a number `n` for those of the `n` most likely tokens too (at
|
|
217
|
+
* most 20). They are the model's own (before temperature, penalties and
|
|
218
|
+
* constraints).
|
|
219
|
+
*/
|
|
220
|
+
readonly logprobs?: boolean | number;
|
|
221
|
+
/**
|
|
222
|
+
* Answer with a JSON object: the output is constrained token by token to
|
|
223
|
+
* valid JSON (a reasoning block before it stays free). Generation ends as
|
|
224
|
+
* soon as the object is closed; `maxTokens` can still cut it.
|
|
225
|
+
*/
|
|
226
|
+
readonly json?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* Answer with JSON following this JSON schema. Supported: `type` (or a
|
|
229
|
+
* list of types), `properties`, `required`, `additionalProperties`,
|
|
230
|
+
* `items`, `minItems`, `maxItems`, `enum`, `const`. Keywords it cannot
|
|
231
|
+
* enforce (`pattern`, `format`, `minimum`, `anyOf`, `$ref`...) are
|
|
232
|
+
* rejected with `INVALID_ARGUMENT`.
|
|
233
|
+
*/
|
|
234
|
+
readonly schema?: Readonly<Record<string, unknown>> | boolean;
|
|
235
|
+
/**
|
|
236
|
+
* Most tokens of a reasoning block (`<think>…</think>`, Qwen3): the engine
|
|
237
|
+
* then closes it and the model goes on with its answer.
|
|
238
|
+
*/
|
|
239
|
+
readonly thinkingBudget?: number;
|
|
240
|
+
/** Stop (`finishReason: "loop"`) when the output starts repeating itself. */
|
|
241
|
+
readonly loopDetection?: boolean;
|
|
242
|
+
/**
|
|
243
|
+
* When the context is full, drop the oldest tokens (keeping the first
|
|
244
|
+
* `keep`, by default the system message) and go on, instead of stopping
|
|
245
|
+
* with `"context_full"`.
|
|
246
|
+
*/
|
|
247
|
+
readonly contextShift?: boolean | {
|
|
248
|
+
readonly keep?: number;
|
|
249
|
+
};
|
|
250
|
+
/**
|
|
251
|
+
* Called with every generated token. Returning `false` stops the
|
|
252
|
+
* generation right there (`finishReason: "aborted"`): the output ends
|
|
253
|
+
* with this token.
|
|
254
|
+
*/
|
|
255
|
+
readonly onToken?: (token: GeneratedToken) => boolean | void;
|
|
256
|
+
/** Progress of the prompt, processed in pieces before the first token. */
|
|
257
|
+
readonly onPrefill?: (progress: {
|
|
258
|
+
readonly done: number;
|
|
259
|
+
readonly total: number;
|
|
260
|
+
}) => void;
|
|
261
|
+
readonly signal?: AbortSignal;
|
|
262
|
+
}
|
|
263
|
+
/** A generated token, as {@link GenerateOptions.onToken} sees it. */
|
|
264
|
+
export interface GeneratedToken {
|
|
265
|
+
readonly id: number;
|
|
266
|
+
/** Text this token completes (may be empty, or include held-back text). */
|
|
267
|
+
readonly text: string;
|
|
268
|
+
/** Natural log of its probability, when `logprobs` is set. */
|
|
269
|
+
readonly logprob?: number;
|
|
270
|
+
/** The most likely tokens at this position, when `logprobs` is a number. */
|
|
271
|
+
readonly topLogprobs?: readonly {
|
|
272
|
+
readonly id: number;
|
|
273
|
+
readonly logprob: number;
|
|
274
|
+
}[];
|
|
275
|
+
/** Whether the engine forced this token (thinking budget) instead of sampling it. */
|
|
276
|
+
readonly forced: boolean;
|
|
277
|
+
}
|
|
278
|
+
/** Options of {@link Model.generate}. */
|
|
279
|
+
export interface CompletionOptions extends GenerateOptions {
|
|
280
|
+
/**
|
|
281
|
+
* Complete the prompt as raw text, without the chat template. By default a
|
|
282
|
+
* string prompt is sent as a user message when the checkpoint has a chat
|
|
283
|
+
* template.
|
|
284
|
+
*/
|
|
285
|
+
readonly raw?: boolean;
|
|
286
|
+
/** Called with each text delta. */
|
|
287
|
+
readonly onDelta?: (delta: string) => void;
|
|
288
|
+
}
|
|
289
|
+
/** Why a generation ended. */
|
|
290
|
+
export type FinishReason = "stop" | "stop_string" | "length" | "context_full" | "loop" | "aborted";
|
|
291
|
+
/** Summary of the last generation of a stream. */
|
|
292
|
+
export interface GenerationResult {
|
|
293
|
+
readonly text: string;
|
|
294
|
+
/** Every sampled token id, the final stop token included. */
|
|
295
|
+
readonly tokens: readonly number[];
|
|
296
|
+
readonly finishReason: FinishReason;
|
|
297
|
+
/** Tokens in the rendered prompt. */
|
|
298
|
+
readonly promptTokens: number;
|
|
299
|
+
/** Prompt tokens served from the session's cache. */
|
|
300
|
+
readonly reusedTokens: number;
|
|
301
|
+
readonly generatedTokens: number;
|
|
302
|
+
/** Tokens dropped from the context by `contextShift`. */
|
|
303
|
+
readonly droppedTokens: number;
|
|
304
|
+
/** Milliseconds from the call to the first token. */
|
|
305
|
+
readonly timeToFirstTokenMs: number;
|
|
306
|
+
/** Decode speed after the first token. */
|
|
307
|
+
readonly tokensPerSecond: number;
|
|
308
|
+
}
|
|
309
|
+
/** A streamed generation: iterate it for text deltas, await `result` for the summary. */
|
|
310
|
+
export interface ChatStream extends AsyncIterable<string> {
|
|
311
|
+
/** Resolves when the generation ends (rejects with its error). */
|
|
312
|
+
readonly result: Promise<GenerationResult>;
|
|
313
|
+
/** Stops the generation; the stream ends with `finishReason: "aborted"`. */
|
|
314
|
+
stop(): void;
|
|
315
|
+
}
|
|
316
|
+
/** Options of {@link Session.score}. */
|
|
317
|
+
export interface ScoreOptions {
|
|
318
|
+
/** Logits of every position, of the last one (default) or none. */
|
|
319
|
+
readonly logits?: "all" | "last" | "none";
|
|
320
|
+
/**
|
|
321
|
+
* Hidden states to return, indexed like `transformers`' `output_hidden_states`:
|
|
322
|
+
* `0` is the embedding output and `i` the residual stream after layer `i`
|
|
323
|
+
* (counted from 1), all before the final norm.
|
|
324
|
+
*/
|
|
325
|
+
readonly hiddenStates?: readonly number[];
|
|
326
|
+
readonly signal?: AbortSignal;
|
|
327
|
+
}
|
|
328
|
+
/** Options of {@link Session.step}. */
|
|
329
|
+
export interface StepOptions {
|
|
330
|
+
/** Return the logits (default `true`). */
|
|
331
|
+
readonly logits?: boolean;
|
|
332
|
+
readonly hiddenStates?: readonly number[];
|
|
333
|
+
readonly signal?: AbortSignal;
|
|
334
|
+
}
|
|
335
|
+
/** Result of {@link Session.score} and {@link Session.step}. */
|
|
336
|
+
export interface ScoreOutput {
|
|
337
|
+
/** Row-major `[positions, vocabSize]` (or `[1, vocabSize]` for `"last"`). */
|
|
338
|
+
readonly logits?: Float32Array;
|
|
339
|
+
/** Row-major `[positions, hiddenSize]` per requested index. */
|
|
340
|
+
readonly hidden: Readonly<Record<number, Float32Array>>;
|
|
341
|
+
readonly positions: number;
|
|
342
|
+
readonly vocabSize: number;
|
|
343
|
+
readonly hiddenSize: number;
|
|
344
|
+
/** Positions in the session's cache after the call. */
|
|
345
|
+
readonly length: number;
|
|
346
|
+
}
|
|
347
|
+
/** A file read while loading. */
|
|
348
|
+
export interface LoadedFile {
|
|
349
|
+
readonly file: string;
|
|
350
|
+
/** Hex SHA-256 of the whole file, when known. */
|
|
351
|
+
readonly sha256?: string;
|
|
352
|
+
readonly bytesRead: number;
|
|
353
|
+
readonly sizeBytes?: number;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Sampling defaults of a checkpoint, read from its `generation_config.json`.
|
|
357
|
+
* Fields the file does not set are absent. The engine applies them when
|
|
358
|
+
* `doSample` is `true` (greedy decoding otherwise), unless a generation
|
|
359
|
+
* overrides them.
|
|
360
|
+
*/
|
|
361
|
+
export interface GenerationConfig {
|
|
362
|
+
readonly doSample?: boolean;
|
|
363
|
+
readonly temperature?: number;
|
|
364
|
+
readonly topK?: number;
|
|
365
|
+
readonly topP?: number;
|
|
366
|
+
readonly minP?: number;
|
|
367
|
+
readonly repetitionPenalty?: number;
|
|
368
|
+
}
|
|
369
|
+
/** Description of a loaded model. */
|
|
370
|
+
export interface ModelInfo {
|
|
371
|
+
/** Hub repository id, when loaded from the hub. */
|
|
372
|
+
readonly repo?: string;
|
|
373
|
+
/** Commit sha of the hub revision, when loaded from the hub. */
|
|
374
|
+
readonly revision?: string;
|
|
375
|
+
readonly modelType: string;
|
|
376
|
+
readonly architecture: string;
|
|
377
|
+
/** Backend actually used, e.g. `"cpu"`. */
|
|
378
|
+
readonly device: Exclude<Device, "auto">;
|
|
379
|
+
/**
|
|
380
|
+
* Human-readable backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"` or
|
|
381
|
+
* `"WebGPU (Apple M3)"`.
|
|
382
|
+
*/
|
|
383
|
+
readonly backend: string;
|
|
384
|
+
/** How the CPU backend runs, when the model runs on it. */
|
|
385
|
+
readonly cpu?: CpuInfo;
|
|
386
|
+
/** Why the requested device was not used, when it was not (no WebGPU, small model under `"auto"`). */
|
|
387
|
+
readonly deviceNote?: string;
|
|
388
|
+
/** The LoRA adapter merged into the weights, if any. */
|
|
389
|
+
readonly lora?: LoraInfo;
|
|
390
|
+
readonly quant: string;
|
|
391
|
+
/** Precision of the activations against quantized weights (`"f32"` on WebGPU). */
|
|
392
|
+
readonly activations: Activations;
|
|
393
|
+
readonly hiddenSize: number;
|
|
394
|
+
readonly numLayers: number;
|
|
395
|
+
readonly vocabSize: number;
|
|
396
|
+
readonly contextLength: number;
|
|
397
|
+
readonly tiesEmbeddings: boolean;
|
|
398
|
+
readonly hasRecurrentState: boolean;
|
|
399
|
+
readonly hasChatTemplate: boolean;
|
|
400
|
+
readonly stopTokens: readonly number[];
|
|
401
|
+
readonly tokenizer: {
|
|
402
|
+
readonly vocabSize: number;
|
|
403
|
+
readonly stopTokenStrings: readonly string[];
|
|
404
|
+
};
|
|
405
|
+
/** Sampling defaults from the checkpoint's `generation_config.json` (empty when it has none). */
|
|
406
|
+
readonly generationConfig: GenerationConfig;
|
|
407
|
+
readonly files: readonly LoadedFile[];
|
|
408
|
+
/** Whether every file came from the local cache (no download). */
|
|
409
|
+
readonly fromCache: boolean;
|
|
410
|
+
/** Milliseconds spent downloading and loading. */
|
|
411
|
+
readonly loadTimeMs: number;
|
|
412
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebAssembly builds of the engine, and the choice between them.
|
|
3
|
+
*
|
|
4
|
+
* `cargo xtask build-wasm` produces three flavours in `wasm/<flavour>/`:
|
|
5
|
+
*
|
|
6
|
+
* - `simd`: SIMD128, single-threaded. Runs everywhere WebAssembly SIMD does.
|
|
7
|
+
* - `relaxed`: SIMD128 and relaxed SIMD (`relaxed_dot`, `relaxed_madd`),
|
|
8
|
+
* single-threaded; faster quantized kernels.
|
|
9
|
+
* - `threads`: relaxed SIMD with shared memory and a pool of Web Workers
|
|
10
|
+
* (wasm-bindgen-rayon). Needs `SharedArrayBuffer`, so a cross-origin
|
|
11
|
+
* isolated page in browsers; always available in Node.
|
|
12
|
+
*
|
|
13
|
+
* The published package ships all three. A package built from source may
|
|
14
|
+
* lack `relaxed` or `threads` (the `threads` build needs a nightly Rust
|
|
15
|
+
* toolchain): `pnpm --filter webslm build` then writes a placeholder module
|
|
16
|
+
* in their place (`scripts/wasm-flavours.mjs`), so that the package compiles
|
|
17
|
+
* and bundlers resolve every import. Asking for a missing flavour fails with
|
|
18
|
+
* `UNSUPPORTED_DEVICE`; the automatic choice skips it.
|
|
19
|
+
*/
|
|
20
|
+
import { WebslmError } from "./errors.js";
|
|
21
|
+
export type WasmFlavour = "simd" | "relaxed" | "threads";
|
|
22
|
+
/** The globals {@link selectWasmFlavour} reads; `globalThis` by default. */
|
|
23
|
+
export interface FlavourEnvironment {
|
|
24
|
+
readonly WebAssembly?: {
|
|
25
|
+
validate(bytes: BufferSource): boolean;
|
|
26
|
+
} | undefined;
|
|
27
|
+
readonly crossOriginIsolated?: boolean | undefined;
|
|
28
|
+
readonly SharedArrayBuffer?: unknown;
|
|
29
|
+
readonly process?: {
|
|
30
|
+
readonly versions?: {
|
|
31
|
+
readonly node?: string;
|
|
32
|
+
};
|
|
33
|
+
} | undefined;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Smallest module using relaxed SIMD: `(func (result v128) (f32x4.relaxed_madd
|
|
37
|
+
* (v128.const 0) (v128.const 0) (v128.const 0)))`. It only validates where
|
|
38
|
+
* relaxed SIMD is supported.
|
|
39
|
+
*/
|
|
40
|
+
export declare const RELAXED_SIMD_PROBE: Uint8Array<ArrayBuffer>;
|
|
41
|
+
/** Whether this engine supports relaxed SIMD. */
|
|
42
|
+
export declare function supportsRelaxedSimd(wasm: FlavourEnvironment["WebAssembly"]): boolean;
|
|
43
|
+
/** Whether a pool of workers can share the module's memory. */
|
|
44
|
+
export declare function supportsWasmThreads(env: FlavourEnvironment): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* The fastest flavour this environment runs: `threads` when relaxed SIMD and
|
|
47
|
+
* shared memory are available, else `relaxed`, else `simd`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function selectWasmFlavour(env?: FlavourEnvironment): WasmFlavour;
|
|
50
|
+
/** The bindings of a flavour (the `threads` one adds `startThreadPool`). */
|
|
51
|
+
export type FlavourBindings = typeof import("../wasm/simd/webslm_wasm.js") & {
|
|
52
|
+
readonly startThreadPool?: (threads: number) => Promise<void>;
|
|
53
|
+
};
|
|
54
|
+
/** The error for a flavour that is not installed, with how to build it. */
|
|
55
|
+
export declare function missingFlavourError(flavour: WasmFlavour): WebslmError;
|
|
56
|
+
/**
|
|
57
|
+
* Imports the bindings of `flavour`. Literal paths let bundlers emit each
|
|
58
|
+
* flavour. Fails with `UNSUPPORTED_DEVICE` when the flavour was not built
|
|
59
|
+
* (a placeholder module, or no file at all when running from the sources).
|
|
60
|
+
*/
|
|
61
|
+
export declare function importFlavour(flavour: WasmFlavour): Promise<FlavourBindings>;
|
|
62
|
+
/** The flavour {@link resolveFlavour} settled on. */
|
|
63
|
+
export interface ResolvedFlavour {
|
|
64
|
+
readonly flavour: WasmFlavour;
|
|
65
|
+
readonly bindings: FlavourBindings;
|
|
66
|
+
/** Why `flavour` is not the one preferred: the builds that were skipped. */
|
|
67
|
+
readonly note?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Imports `preferred` when `forced` (an explicit `wasmFlavour`: a missing
|
|
71
|
+
* build fails with `UNSUPPORTED_DEVICE`); otherwise falls back from a
|
|
72
|
+
* missing build to the next simpler one (`threads`, then `relaxed`, then
|
|
73
|
+
* `simd`), saying so in `note`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function resolveFlavour(preferred: WasmFlavour, forced: boolean, load?: (flavour: WasmFlavour) => Promise<FlavourBindings>): Promise<ResolvedFlavour>;
|
|
76
|
+
/** Reads the `.wasm` file of `flavour` from disk (Node, where fetch cannot read files). */
|
|
77
|
+
export declare function readFlavourModule(flavour: WasmFlavour): Promise<Uint8Array<ArrayBuffer>>;
|
|
78
|
+
/** Upper bound of the default pool size: past it, memory bandwidth limits decode anyway. */
|
|
79
|
+
export declare const MAX_DEFAULT_THREADS = 8;
|
|
80
|
+
/**
|
|
81
|
+
* Default size of the worker pool: the number of logical cores
|
|
82
|
+
* (`navigator.hardwareConcurrency`, or `os.availableParallelism()` in Node),
|
|
83
|
+
* capped at {@link MAX_DEFAULT_THREADS}.
|
|
84
|
+
*/
|
|
85
|
+
export declare function defaultThreadCount(): Promise<number>;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebAssembly builds of the engine, and the choice between them.
|
|
3
|
+
*
|
|
4
|
+
* `cargo xtask build-wasm` produces three flavours in `wasm/<flavour>/`:
|
|
5
|
+
*
|
|
6
|
+
* - `simd`: SIMD128, single-threaded. Runs everywhere WebAssembly SIMD does.
|
|
7
|
+
* - `relaxed`: SIMD128 and relaxed SIMD (`relaxed_dot`, `relaxed_madd`),
|
|
8
|
+
* single-threaded; faster quantized kernels.
|
|
9
|
+
* - `threads`: relaxed SIMD with shared memory and a pool of Web Workers
|
|
10
|
+
* (wasm-bindgen-rayon). Needs `SharedArrayBuffer`, so a cross-origin
|
|
11
|
+
* isolated page in browsers; always available in Node.
|
|
12
|
+
*
|
|
13
|
+
* The published package ships all three. A package built from source may
|
|
14
|
+
* lack `relaxed` or `threads` (the `threads` build needs a nightly Rust
|
|
15
|
+
* toolchain): `pnpm --filter webslm build` then writes a placeholder module
|
|
16
|
+
* in their place (`scripts/wasm-flavours.mjs`), so that the package compiles
|
|
17
|
+
* and bundlers resolve every import. Asking for a missing flavour fails with
|
|
18
|
+
* `UNSUPPORTED_DEVICE`; the automatic choice skips it.
|
|
19
|
+
*/
|
|
20
|
+
import { WebslmError } from "./errors.js";
|
|
21
|
+
import { importNode, isNode } from "./runtime.js";
|
|
22
|
+
const V128_ZERO = [0xfd, 0x0c, ...new Array(16).fill(0)];
|
|
23
|
+
const PROBE_BODY = [0x00, ...V128_ZERO, ...V128_ZERO, ...V128_ZERO, 0xfd, 0x85, 0x02, 0x0b];
|
|
24
|
+
/**
|
|
25
|
+
* Smallest module using relaxed SIMD: `(func (result v128) (f32x4.relaxed_madd
|
|
26
|
+
* (v128.const 0) (v128.const 0) (v128.const 0)))`. It only validates where
|
|
27
|
+
* relaxed SIMD is supported.
|
|
28
|
+
*/
|
|
29
|
+
export const RELAXED_SIMD_PROBE = new Uint8Array([
|
|
30
|
+
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
|
31
|
+
// Type section: one function type, () -> v128.
|
|
32
|
+
0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b,
|
|
33
|
+
// Function section: one function of type 0.
|
|
34
|
+
0x03, 0x02, 0x01, 0x00,
|
|
35
|
+
// Code section.
|
|
36
|
+
0x0a, PROBE_BODY.length + 2, 0x01, PROBE_BODY.length, ...PROBE_BODY,
|
|
37
|
+
]);
|
|
38
|
+
/** Whether this engine supports relaxed SIMD. */
|
|
39
|
+
export function supportsRelaxedSimd(wasm) {
|
|
40
|
+
if (wasm === undefined)
|
|
41
|
+
return false;
|
|
42
|
+
try {
|
|
43
|
+
return wasm.validate(RELAXED_SIMD_PROBE);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Whether a pool of workers can share the module's memory. */
|
|
50
|
+
export function supportsWasmThreads(env) {
|
|
51
|
+
if (typeof env.SharedArrayBuffer !== "function")
|
|
52
|
+
return false;
|
|
53
|
+
return typeof env.process?.versions?.node === "string" || env.crossOriginIsolated === true;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The fastest flavour this environment runs: `threads` when relaxed SIMD and
|
|
57
|
+
* shared memory are available, else `relaxed`, else `simd`.
|
|
58
|
+
*/
|
|
59
|
+
export function selectWasmFlavour(env = globalThis) {
|
|
60
|
+
if (!supportsRelaxedSimd(env.WebAssembly))
|
|
61
|
+
return "simd";
|
|
62
|
+
return supportsWasmThreads(env) ? "threads" : "relaxed";
|
|
63
|
+
}
|
|
64
|
+
/** The error for a flavour that is not installed, with how to build it. */
|
|
65
|
+
export function missingFlavourError(flavour) {
|
|
66
|
+
const toolchain = flavour === "threads" ? " (it needs the pinned nightly Rust toolchain)" : "";
|
|
67
|
+
return new WebslmError("UNSUPPORTED_DEVICE", `the "${flavour}" WebAssembly build is not installed in this copy of webslm: build it with ` +
|
|
68
|
+
`\`cargo xtask build-wasm --release --flavours ${flavour}\`${toolchain} and rebuild the package, ` +
|
|
69
|
+
"or leave wasmFlavour unset to run the builds that are installed");
|
|
70
|
+
}
|
|
71
|
+
/** Whether `error` says that a module file does not exist (Node). */
|
|
72
|
+
function isModuleNotFound(error) {
|
|
73
|
+
return error?.code === "ERR_MODULE_NOT_FOUND";
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Imports the bindings of `flavour`. Literal paths let bundlers emit each
|
|
77
|
+
* flavour. Fails with `UNSUPPORTED_DEVICE` when the flavour was not built
|
|
78
|
+
* (a placeholder module, or no file at all when running from the sources).
|
|
79
|
+
*/
|
|
80
|
+
export async function importFlavour(flavour) {
|
|
81
|
+
let module;
|
|
82
|
+
try {
|
|
83
|
+
// The `relaxed` and `threads` builds may be missing (a package built
|
|
84
|
+
// from source with some flavours only); their types come from `simd`.
|
|
85
|
+
switch (flavour) {
|
|
86
|
+
case "simd":
|
|
87
|
+
module = await import("../wasm/simd/webslm_wasm.js");
|
|
88
|
+
break;
|
|
89
|
+
case "relaxed":
|
|
90
|
+
// @ts-ignore: present once built (or as a placeholder).
|
|
91
|
+
module = (await import("../wasm/relaxed/webslm_wasm.js"));
|
|
92
|
+
break;
|
|
93
|
+
case "threads":
|
|
94
|
+
// @ts-ignore: present once built (or as a placeholder).
|
|
95
|
+
module = (await import("../wasm/threads/webslm_wasm.js"));
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (isModuleNotFound(error))
|
|
101
|
+
throw missingFlavourError(flavour);
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
if (typeof module.missingFlavour === "string")
|
|
105
|
+
throw missingFlavourError(flavour);
|
|
106
|
+
return module;
|
|
107
|
+
}
|
|
108
|
+
/** Simpler flavours to try, in order, when the automatic choice is missing. */
|
|
109
|
+
const FALLBACK = {
|
|
110
|
+
threads: ["threads", "relaxed", "simd"],
|
|
111
|
+
relaxed: ["relaxed", "simd"],
|
|
112
|
+
simd: ["simd"],
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Imports `preferred` when `forced` (an explicit `wasmFlavour`: a missing
|
|
116
|
+
* build fails with `UNSUPPORTED_DEVICE`); otherwise falls back from a
|
|
117
|
+
* missing build to the next simpler one (`threads`, then `relaxed`, then
|
|
118
|
+
* `simd`), saying so in `note`.
|
|
119
|
+
*/
|
|
120
|
+
export async function resolveFlavour(preferred, forced, load = importFlavour) {
|
|
121
|
+
if (forced)
|
|
122
|
+
return { flavour: preferred, bindings: await load(preferred) };
|
|
123
|
+
const skipped = [];
|
|
124
|
+
let lastError;
|
|
125
|
+
for (const flavour of FALLBACK[preferred]) {
|
|
126
|
+
try {
|
|
127
|
+
const bindings = await load(flavour);
|
|
128
|
+
if (skipped.length === 0)
|
|
129
|
+
return { flavour, bindings };
|
|
130
|
+
return { flavour, bindings, note: `${skipped.join("; ")}; running the "${flavour}" build` };
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
lastError = error;
|
|
134
|
+
// Other failures (a network error in a browser...) fall back too.
|
|
135
|
+
const missing = error instanceof WebslmError && error.code === "UNSUPPORTED_DEVICE";
|
|
136
|
+
const reason = missing
|
|
137
|
+
? "is not installed (webslm built from source without it)"
|
|
138
|
+
: `failed to load (${error instanceof Error ? error.message : String(error)})`;
|
|
139
|
+
skipped.push(`the "${flavour}" build ${reason}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
throw lastError;
|
|
143
|
+
}
|
|
144
|
+
/** Reads the `.wasm` file of `flavour` from disk (Node, where fetch cannot read files). */
|
|
145
|
+
export async function readFlavourModule(flavour) {
|
|
146
|
+
const fs = await importNode("fs/promises");
|
|
147
|
+
// Concatenation, not a template: bundlers must not treat this Node-only
|
|
148
|
+
// path as an asset pattern.
|
|
149
|
+
return fs.readFile(new URL("../wasm/" + flavour + "/webslm_wasm_bg.wasm", import.meta.url));
|
|
150
|
+
}
|
|
151
|
+
/** Upper bound of the default pool size: past it, memory bandwidth limits decode anyway. */
|
|
152
|
+
export const MAX_DEFAULT_THREADS = 8;
|
|
153
|
+
/**
|
|
154
|
+
* Default size of the worker pool: the number of logical cores
|
|
155
|
+
* (`navigator.hardwareConcurrency`, or `os.availableParallelism()` in Node),
|
|
156
|
+
* capped at {@link MAX_DEFAULT_THREADS}.
|
|
157
|
+
*/
|
|
158
|
+
export async function defaultThreadCount() {
|
|
159
|
+
let cores;
|
|
160
|
+
if (isNode()) {
|
|
161
|
+
const os = await importNode("os");
|
|
162
|
+
cores = os.availableParallelism?.() ?? os.cpus().length;
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
cores = globalThis.navigator
|
|
166
|
+
?.hardwareConcurrency;
|
|
167
|
+
}
|
|
168
|
+
return Math.max(1, Math.min(cores ?? 1, MAX_DEFAULT_THREADS));
|
|
169
|
+
}
|