webslm 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +64 -12
  2. package/dist/ai-sdk/index.d.ts +1 -1
  3. package/dist/ai-sdk/index.js +1 -1
  4. package/dist/cache/models.d.ts +32 -3
  5. package/dist/cache/models.js +106 -11
  6. package/dist/cache/node-fs.d.ts +26 -3
  7. package/dist/cache/node-fs.js +43 -9
  8. package/dist/cache-management.d.ts +1 -1
  9. package/dist/curated.d.ts +31 -1
  10. package/dist/curated.js +49 -5
  11. package/dist/download.d.ts +4 -0
  12. package/dist/download.js +29 -4
  13. package/dist/engine.d.ts +33 -4
  14. package/dist/engine.js +451 -44
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +1 -1
  17. package/dist/models.d.ts +26 -6
  18. package/dist/models.js +63 -7
  19. package/dist/native.d.ts +165 -0
  20. package/dist/native.js +243 -0
  21. package/dist/protocol.d.ts +12 -2
  22. package/dist/recommended-sampling.d.ts +54 -0
  23. package/dist/recommended-sampling.js +73 -0
  24. package/dist/simple.d.ts +22 -8
  25. package/dist/simple.js +35 -9
  26. package/dist/types.d.ts +85 -17
  27. package/native-manifest.json +47 -0
  28. package/package.json +2 -1
  29. package/wasm/relaxed/webslm_wasm.d.ts +26 -4
  30. package/wasm/relaxed/webslm_wasm.js +70 -17
  31. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  32. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
  33. package/wasm/simd/webslm_wasm.d.ts +26 -4
  34. package/wasm/simd/webslm_wasm.js +70 -17
  35. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  36. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
  37. package/wasm/threads/webslm_wasm.d.ts +26 -4
  38. package/wasm/threads/webslm_wasm.js +75 -22
  39. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  40. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +5 -3
@@ -6,7 +6,7 @@
6
6
  * `read` messages. `abort` and `readResult` get no answer.
7
7
  */
8
8
  import type { SerializedError } from "./errors.js";
9
- import type { Activations, AdapterMode, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
9
+ import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
10
10
  import type { WasmFlavour } from "./wasm-flavour.js";
11
11
  /** A model source in a form that can be posted to a worker. */
12
12
  export type WireSource = {
@@ -25,13 +25,23 @@ export type WireSource = {
25
25
  };
26
26
  export interface WireLoadOptions {
27
27
  readonly quant: string;
28
- /** `"auto"`, `"cpu"` or `"webgpu"`; the engine reports what it used. */
28
+ /**
29
+ * The caller asked for `quant: "auto"` (and resolved it to `quant` for the
30
+ * WebAssembly engine): the native engine decides again, against the
31
+ * machine's memory and GPU.
32
+ */
33
+ readonly autoQuant?: boolean;
34
+ /** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`; the engine reports what it used. */
29
35
  readonly device?: string;
36
+ /** `"auto"` (default), `"native"` or `"wasm"`. */
37
+ readonly backend?: Backend;
30
38
  readonly contextLength?: number;
31
39
  /** Scale of the adapter of a `load` request. */
32
40
  readonly adapterScale?: number;
33
41
  readonly adapterMode?: AdapterMode;
34
42
  readonly cacheDir?: string;
43
+ /** `false` turns the converted-weight cache off. */
44
+ readonly weightCache?: boolean;
35
45
  readonly deterministic?: boolean;
36
46
  readonly activations?: Activations;
37
47
  readonly wasmFlavour?: WasmFlavour;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Sampling settings that model cards recommend: the table of the Rust
3
+ * engine (`crates/webslm-core/src/recommended_sampling.json`, used by the
4
+ * `webslm` command-line tool and server), copied here so that the package
5
+ * needs no file of the repository; `test/sampling.test.ts` checks that both
6
+ * stay identical. See `recommendedSampling` for how a checkpoint gets a set.
7
+ */
8
+ /**
9
+ * Sampling settings a model card recommends. Fields left out keep the
10
+ * engine's defaults (no top-k, top-p 1, min-p 0, no penalty).
11
+ */
12
+ export interface SamplingDefaults {
13
+ readonly temperature: number;
14
+ readonly topK?: number;
15
+ readonly topP?: number;
16
+ readonly minP?: number;
17
+ readonly repetitionPenalty?: number;
18
+ readonly presencePenalty?: number;
19
+ }
20
+ /** The settings of one model family. */
21
+ export interface SamplingSet {
22
+ /** Whether the family reasons when `enable_thinking` is not set (Qwen3, LFM3). */
23
+ readonly thinksByDefault?: boolean;
24
+ /** When the model answers directly. */
25
+ readonly answer: SamplingDefaults;
26
+ /** When it reasons first (`answer` when absent). */
27
+ readonly thinking?: SamplingDefaults;
28
+ }
29
+ /** The table: sets by name, and which repositories and `model_type`s use them. */
30
+ export interface SamplingTable {
31
+ readonly sets: Readonly<Record<string, SamplingSet>>;
32
+ readonly repos: Readonly<Record<string, string>>;
33
+ readonly modelTypes: Readonly<Record<string, string>>;
34
+ }
35
+ export declare const RECOMMENDED_SAMPLING: SamplingTable;
36
+ /** What identifies a checkpoint for {@link samplingSet}. */
37
+ export interface CheckpointTraits {
38
+ /** Hub repository id (a `@revision` suffix is ignored). */
39
+ readonly repo?: string | undefined;
40
+ /** `model_type` of its `config.json`. */
41
+ readonly modelType?: string | undefined;
42
+ /** Whether its `generation_config.json` asks for sampling (`do_sample`). */
43
+ readonly doSample?: boolean | undefined;
44
+ }
45
+ /**
46
+ * The set of a checkpoint, the way the Rust engine picks it: a listed
47
+ * repository (case-insensitive) uses its set whatever its
48
+ * `generation_config.json` says; otherwise a checkpoint whose
49
+ * `generation_config.json` does not ask for sampling uses the set of its
50
+ * `model_type`, when listed; otherwise none.
51
+ */
52
+ export declare function samplingSet(checkpoint: CheckpointTraits): SamplingSet | undefined;
53
+ /** The settings of `set` with or without reasoning (`think` unset: the family's default). */
54
+ export declare function settingsFor(set: SamplingSet, think?: boolean): SamplingDefaults;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Sampling settings that model cards recommend: the table of the Rust
3
+ * engine (`crates/webslm-core/src/recommended_sampling.json`, used by the
4
+ * `webslm` command-line tool and server), copied here so that the package
5
+ * needs no file of the repository; `test/sampling.test.ts` checks that both
6
+ * stay identical. See `recommendedSampling` for how a checkpoint gets a set.
7
+ */
8
+ // Each model card: SmolLM2 (its usage example), LFM2.5 and LFM3
9
+ // ("generation parameters", LFM3's "general" set), Qwen3 (best practices,
10
+ // thinking and non-thinking), Qwen3.5 (the settings its benchmarks used in
11
+ // each mode).
12
+ export const RECOMMENDED_SAMPLING = {
13
+ sets: {
14
+ smollm2: {
15
+ answer: { temperature: 0.2, topP: 0.9 },
16
+ },
17
+ lfm2: {
18
+ answer: { temperature: 0.1, topK: 50, repetitionPenalty: 1.05 },
19
+ },
20
+ lfm3: {
21
+ thinksByDefault: true,
22
+ answer: { temperature: 0.1, topK: 50, repetitionPenalty: 1.1 },
23
+ },
24
+ qwen3: {
25
+ thinksByDefault: true,
26
+ answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0 },
27
+ thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0 },
28
+ },
29
+ qwen3_5: {
30
+ answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0, presencePenalty: 1.5 },
31
+ thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0, presencePenalty: 1.5 },
32
+ },
33
+ },
34
+ repos: {
35
+ "HuggingFaceTB/SmolLM2-135M-Instruct": "smollm2",
36
+ "HuggingFaceTB/SmolLM2-360M-Instruct": "smollm2",
37
+ "LiquidAI/LFM2.5-350M": "lfm2",
38
+ "Qwen/Qwen3-0.6B": "qwen3",
39
+ "Qwen/Qwen3.5-0.8B": "qwen3_5",
40
+ "LiquidAI/LFM3-1.7B": "lfm3",
41
+ },
42
+ modelTypes: {
43
+ lfm2: "lfm2",
44
+ lfm3: "lfm3",
45
+ qwen3: "qwen3",
46
+ qwen3_5: "qwen3_5",
47
+ qwen3_5_text: "qwen3_5",
48
+ },
49
+ };
50
+ /**
51
+ * The set of a checkpoint, the way the Rust engine picks it: a listed
52
+ * repository (case-insensitive) uses its set whatever its
53
+ * `generation_config.json` says; otherwise a checkpoint whose
54
+ * `generation_config.json` does not ask for sampling uses the set of its
55
+ * `model_type`, when listed; otherwise none.
56
+ */
57
+ export function samplingSet(checkpoint) {
58
+ const table = RECOMMENDED_SAMPLING;
59
+ const repo = checkpoint.repo?.split("@")[0]?.toLowerCase();
60
+ const byRepo = repo === undefined
61
+ ? undefined
62
+ : Object.entries(table.repos).find(([id]) => id.toLowerCase() === repo)?.[1];
63
+ const name = byRepo ??
64
+ (checkpoint.doSample !== true && checkpoint.modelType !== undefined
65
+ ? table.modelTypes[checkpoint.modelType]
66
+ : undefined);
67
+ return name === undefined ? undefined : table.sets[name];
68
+ }
69
+ /** The settings of `set` with or without reasoning (`think` unset: the family's default). */
70
+ export function settingsFor(set, think) {
71
+ const thinking = think ?? set.thinksByDefault === true;
72
+ return (thinking ? set.thinking : undefined) ?? set.answer;
73
+ }
package/dist/simple.d.ts CHANGED
@@ -7,11 +7,16 @@ import { type Model } from "./models.js";
7
7
  import type { ChatMessage, LoadModelOptions, ModelInfo, ModelSource } from "./types.js";
8
8
  /**
9
9
  * The model {@link load}, {@link ask} and {@link stream} use when none is
10
- * given: SmolLM2 360M Instruct, small (about 720 MB to download once),
11
- * ungated and quick on the CPU.
10
+ * given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
11
+ * on the CPU, and able to follow a conversation (the SmolLM2 checkpoints of
12
+ * the same size lose track of it after a turn or two).
13
+ */
14
+ export declare const DEFAULT_MODEL = "LiquidAI/LFM2.5-350M";
15
+ /**
16
+ * Sampling temperature used when neither the call, the model card of a
17
+ * curated model (`recommendedSampling`) nor the checkpoint's
18
+ * `generation_config.json` sets one.
12
19
  */
13
- export declare const DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct";
14
- /** Sampling temperature used when neither the call nor the checkpoint's `generation_config.json` sets one. */
15
20
  export declare const DEFAULT_TEMPERATURE = 0.7;
16
21
  /** Largest number of new tokens of an answer, unless `maxTokens` says otherwise. */
17
22
  export declare const DEFAULT_MAX_TOKENS = 512;
@@ -21,7 +26,9 @@ export interface PromptOptions {
21
26
  readonly maxTokens?: number;
22
27
  /**
23
28
  * Sampling temperature; `0` is greedy (deterministic) decoding. Defaults to
24
- * the checkpoint's `generation_config.json` value, else 0.7.
29
+ * the model card's recommended sampling for the curated models
30
+ * (`recommendedSampling`), else the checkpoint's `generation_config.json`
31
+ * value, else 0.7.
25
32
  */
26
33
  readonly temperature?: number;
27
34
  /** System prompt sent before the user message. */
@@ -222,12 +229,19 @@ export declare class ReasoningSplitter {
222
229
  * Text without such a block is all answer. `open` is `true` while the block
223
230
  * is not closed yet (a stream still thinking, or an answer cut by `maxTokens`).
224
231
  *
232
+ * `opened` says that the prompt already opened the block (templates such as
233
+ * Qwen3.5's and LFM3's end with `<think>` when thinking is on), so the output
234
+ * starts inside it. Left out, it is inferred: an output that closes a block
235
+ * it never opened started inside one.
236
+ *
225
237
  * ```ts
226
238
  * splitReasoning("<think>\nThe user greets me.\n</think>\n\nHello!");
227
239
  * // { text: "Hello!", reasoning: "The user greets me.", open: false }
240
+ * splitReasoning("The user greets me.\n</think>\n\nHello!");
241
+ * // the same
228
242
  * ```
229
243
  */
230
- export declare function splitReasoning(output: string): Answer & {
244
+ export declare function splitReasoning(output: string, opened?: boolean): Answer & {
231
245
  readonly open: boolean;
232
246
  };
233
247
  /** @internal Runs async functions one at a time, in call order. */
@@ -251,8 +265,8 @@ export declare function probeTemplateTraits(model: Pick<Model, "info" | "renderC
251
265
  * offline cache).
252
266
  *
253
267
  * The first load downloads the checkpoint from the Hugging Face Hub into the
254
- * cache (OPFS in browsers, `~/.cache/webslm` in Node); later loads read it
255
- * from there without network.
268
+ * cache (OPFS in browsers, the command-line tool's cache directory in Node);
269
+ * later loads read it from there without network.
256
270
  *
257
271
  * ```ts
258
272
  * import { load } from "webslm";
package/dist/simple.js CHANGED
@@ -4,15 +4,21 @@
4
4
  * {@link Session}.
5
5
  */
6
6
  import { AsyncQueue } from "./async-queue.js";
7
+ import { recommendedSampling } from "./curated.js";
7
8
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
8
9
  import { loadModel } from "./models.js";
9
10
  /**
10
11
  * The model {@link load}, {@link ask} and {@link stream} use when none is
11
- * given: SmolLM2 360M Instruct, small (about 720 MB to download once),
12
- * ungated and quick on the CPU.
12
+ * given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
13
+ * on the CPU, and able to follow a conversation (the SmolLM2 checkpoints of
14
+ * the same size lose track of it after a turn or two).
15
+ */
16
+ export const DEFAULT_MODEL = "LiquidAI/LFM2.5-350M";
17
+ /**
18
+ * Sampling temperature used when neither the call, the model card of a
19
+ * curated model (`recommendedSampling`) nor the checkpoint's
20
+ * `generation_config.json` sets one.
13
21
  */
14
- export const DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct";
15
- /** Sampling temperature used when neither the call nor the checkpoint's `generation_config.json` sets one. */
16
22
  export const DEFAULT_TEMPERATURE = 0.7;
17
23
  /** Largest number of new tokens of an answer, unless `maxTokens` says otherwise. */
18
24
  export const DEFAULT_MAX_TOKENS = 512;
@@ -128,18 +134,27 @@ export class ReasoningSplitter {
128
134
  * Text without such a block is all answer. `open` is `true` while the block
129
135
  * is not closed yet (a stream still thinking, or an answer cut by `maxTokens`).
130
136
  *
137
+ * `opened` says that the prompt already opened the block (templates such as
138
+ * Qwen3.5's and LFM3's end with `<think>` when thinking is on), so the output
139
+ * starts inside it. Left out, it is inferred: an output that closes a block
140
+ * it never opened started inside one.
141
+ *
131
142
  * ```ts
132
143
  * splitReasoning("<think>\nThe user greets me.\n</think>\n\nHello!");
133
144
  * // { text: "Hello!", reasoning: "The user greets me.", open: false }
145
+ * splitReasoning("The user greets me.\n</think>\n\nHello!");
146
+ * // the same
134
147
  * ```
135
148
  */
136
- export function splitReasoning(output) {
149
+ export function splitReasoning(output, opened) {
137
150
  let text = "";
138
151
  let reasoning = "";
152
+ const close = output.indexOf(CLOSE);
153
+ const startsInside = opened ?? (close !== -1 && !output.slice(0, close).includes(OPEN));
139
154
  const splitter = new ReasoningSplitter({
140
155
  text: (t) => (text += t),
141
156
  reasoning: (t) => (reasoning += t),
142
- }, false);
157
+ }, startsInside);
143
158
  splitter.push(output);
144
159
  const open = splitter.inReasoning;
145
160
  splitter.end();
@@ -300,7 +315,13 @@ class LLMImpl {
300
315
  }, traits.opensReasoning(options.think));
301
316
  const generation = {
302
317
  maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
303
- temperature: options.temperature ?? this.model.info().generationConfig.temperature ?? DEFAULT_TEMPERATURE,
318
+ // Curated models get their model card's sampling from the model
319
+ // itself (`recommendedSampling`).
320
+ ...(options.temperature === undefined && hasRecommendedSampling(this.model.info())
321
+ ? {}
322
+ : {
323
+ temperature: options.temperature ?? this.model.info().generationConfig.temperature ?? DEFAULT_TEMPERATURE,
324
+ }),
304
325
  ...(options.seed === undefined ? {} : { seed: options.seed }),
305
326
  ...(options.stop === undefined ? {} : { stop: options.stop }),
306
327
  ...passThrough(options),
@@ -326,6 +347,11 @@ class LLMImpl {
326
347
  return this.#traits;
327
348
  }
328
349
  }
350
+ /** Whether the model card's sampling applies to `info` (`recommendedSampling`). */
351
+ function hasRecommendedSampling(info) {
352
+ const traits = { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
353
+ return recommendedSampling(traits) !== undefined;
354
+ }
329
355
  /** Generation options the simple API passes through unchanged. */
330
356
  function passThrough(options) {
331
357
  const keys = [
@@ -467,8 +493,8 @@ class ChatImpl {
467
493
  * offline cache).
468
494
  *
469
495
  * The first load downloads the checkpoint from the Hugging Face Hub into the
470
- * cache (OPFS in browsers, `~/.cache/webslm` in Node); later loads read it
471
- * from there without network.
496
+ * cache (OPFS in browsers, the command-line tool's cache directory in Node);
497
+ * later loads read it from there without network.
472
498
  *
473
499
  * ```ts
474
500
  * import { load } from "webslm";
package/dist/types.d.ts CHANGED
@@ -2,10 +2,25 @@
2
2
  import type { EngineHandle } from "./models.js";
3
3
  import type { WasmFlavour } from "./wasm-flavour.js";
4
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.
5
+ * Where the model runs. `"auto"` (the default) picks the GPU for models above
6
+ * ~100M parameters when an adapter is available, the CPU otherwise. `"gpu"`
7
+ * is the GPU of the engine that runs: WebGPU in browsers, Metal, Vulkan or
8
+ * DX12 with the native engine in Node; `"webgpu"` is a synonym kept for
9
+ * existing code. A loaded model reports `"webgpu"` (WebAssembly engine),
10
+ * `"gpu"` (native engine) or `"cpu"`.
7
11
  */
8
- export type Device = "auto" | "cpu" | "webgpu";
12
+ export type Device = "auto" | "cpu" | "gpu" | "webgpu";
13
+ /**
14
+ * Which build of the engine runs a model in Node (see
15
+ * {@link LoadModelOptions.backend}): `"native"` is the Node-API addon of the
16
+ * engine (native SIMD kernels on every core, the GPU through Metal, Vulkan or
17
+ * DX12), downloaded on first use from the GitHub Release of this version and
18
+ * checked against the SHA-256 the package carries; `"wasm"` the WebAssembly
19
+ * build (the only one in browsers). `"auto"` (the default) picks `"native"`
20
+ * when the addon is available (cached, or downloaded and verified) and the
21
+ * source is a hub model, else `"wasm"`.
22
+ */
23
+ export type Backend = "auto" | "native" | "wasm";
9
24
  /** How weight matrices are stored once loaded. */
10
25
  export type Quant = "q8" | "q4" | "f32";
11
26
  /**
@@ -109,11 +124,23 @@ export interface LoadProgress {
109
124
  }
110
125
  export interface LoadModelOptions {
111
126
  /**
112
- * Defaults to `"auto"`: WebGPU for models above ~100M parameters when an
113
- * adapter is available, the CPU otherwise. `"webgpu"` falls back to the CPU
114
- * when no GPU device can be created; {@link ModelInfo.deviceNote} says why.
127
+ * Defaults to `"auto"`: the GPU for models above ~100M parameters when an
128
+ * adapter is available (a hardware one with the native engine, which skips
129
+ * software rasterizers and checks the model fits the GPU's memory first),
130
+ * the CPU otherwise. With the WebAssembly engine, `"gpu"` (or `"webgpu"`)
131
+ * falls back to the CPU when no GPU device can be created; with the native
132
+ * engine it fails with `UNSUPPORTED_DEVICE` instead, as `webslm run --device
133
+ * gpu` does. {@link ModelInfo.deviceNote} says why a device was not used.
115
134
  */
116
135
  readonly device?: Device;
136
+ /**
137
+ * The engine build in Node (see {@link Backend}). `"native"` fails with
138
+ * `UNSUPPORTED_DEVICE` when the addon is not available (no build for this
139
+ * platform, offline without it in the cache, a failed download or checksum,
140
+ * or a browser); `"wasm"` keeps the WebAssembly build. {@link
141
+ * ModelInfo.runtime} reports which one runs.
142
+ */
143
+ readonly backend?: Backend;
117
144
  /**
118
145
  * Weight format. Defaults to `"q8"`; `"q4"` (4-bit, 16-value blocks) is
119
146
  * smaller and less accurate. `"auto"` estimates the memory of the model
@@ -165,10 +192,20 @@ export interface LoadModelOptions {
165
192
  */
166
193
  readonly engine?: EngineHandle;
167
194
  /**
168
- * Where the cache lives in Node (default `WEBSLM_CACHE_DIR` or
169
- * `~/.cache/webslm`). Ignored in browsers, which use OPFS.
195
+ * Where the cache lives in Node (default `WEBSLM_CACHE_DIR`, else the
196
+ * command-line tool's cache directory: `~/Library/Caches/webslm` on macOS,
197
+ * `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` or
198
+ * `~/.cache/webslm` on Linux). Ignored in browsers, which use OPFS.
170
199
  */
171
200
  readonly cacheDir?: string;
201
+ /**
202
+ * Keep the converted (Q8_0 or 4-bit) weights of a hub model in the cache
203
+ * (OPFS in browsers, the cache directory in Node), so that the next load
204
+ * reads them instead of converting the checkpoint again; `info().weightCache`
205
+ * reports what the load did. Default `true`; `WEBSLM_QUANT_CACHE=0` turns
206
+ * it off in Node, as for the command-line tool.
207
+ */
208
+ readonly weightCache?: boolean;
172
209
  /**
173
210
  * Run on CPU kernels whose results are bit-identical in every WebAssembly
174
211
  * build and natively (the `webslm` CLI and the Rust crates), at some cost
@@ -182,19 +219,22 @@ export interface LoadModelOptions {
182
219
  * isolated or in Node, `"relaxed"` with relaxed SIMD, else `"simd"`). Each
183
220
  * worker instantiates one build: the first model loaded in it decides.
184
221
  * A build missing from a package built from source (see the README)
185
- * fails with `UNSUPPORTED_DEVICE`; the automatic choice skips it.
222
+ * fails with `UNSUPPORTED_DEVICE`; the automatic choice skips it. Under
223
+ * `backend: "auto"`, naming a build runs WebAssembly.
186
224
  */
187
225
  readonly wasmFlavour?: WasmFlavour;
188
226
  /**
189
227
  * Size of the thread pool of the `"threads"` build. Defaults to the number
190
- * of logical cores, at most 8.
228
+ * of logical cores, at most 8. On the native engine, the size of its CPU
229
+ * thread pool (default: the available cores, capped by the cgroup CPU
230
+ * quota), set by the first native load of the process.
191
231
  */
192
232
  readonly threads?: number;
193
233
  }
194
234
  /** How the CPU backend runs a model. */
195
235
  export interface CpuInfo {
196
- /** The WebAssembly build. */
197
- readonly flavour: WasmFlavour;
236
+ /** The WebAssembly build, or `"native"` for the native engine. */
237
+ readonly flavour: WasmFlavour | "native";
198
238
  /** CPU kernel set, e.g. `"relaxed-simd"`. */
199
239
  readonly kernels: string;
200
240
  /** Threads the kernels use. */
@@ -212,11 +252,16 @@ export interface ChatMessage {
212
252
  readonly role: "system" | "user" | "assistant" | (string & {});
213
253
  readonly content: string;
214
254
  }
215
- /** Options of a generation. Unset sampling options come from the checkpoint's `generation_config.json`. */
255
+ /**
256
+ * Options of a generation. Unset sampling options come from the model card's
257
+ * recommendation for the curated models (`CURATED_MODELS`, see
258
+ * `recommendedSampling`), else from the checkpoint's `generation_config.json`
259
+ * (greedy decoding when it does not ask for sampling).
260
+ */
216
261
  export interface GenerateOptions {
217
262
  /** Largest number of new tokens (default 512). */
218
263
  readonly maxTokens?: number;
219
- /** `0` is greedy decoding. */
264
+ /** `0` is greedy decoding (and turns the recommended sampling off). */
220
265
  readonly temperature?: number;
221
266
  readonly topK?: number;
222
267
  readonly topP?: number;
@@ -391,6 +436,19 @@ export interface GenerationConfig {
391
436
  readonly minP?: number;
392
437
  readonly repetitionPenalty?: number;
393
438
  }
439
+ /** What a load did with the converted-weight cache. */
440
+ export interface WeightCacheInfo {
441
+ /**
442
+ * `"hit"`: the converted weights were read from the cache instead of
443
+ * converting the checkpoint; `"written"`: they were converted and stored
444
+ * for the next load; `"failed"`: storing them failed (nothing is kept);
445
+ * `"off"`: not used (turned off, a float format such as `"f32"`, a source
446
+ * other than the hub, or storage that cannot hold it).
447
+ */
448
+ readonly status: "hit" | "written" | "failed" | "off";
449
+ /** Bytes read from the cache, or stored in it. */
450
+ readonly bytes: number;
451
+ }
394
452
  /** Description of a loaded model. */
395
453
  export interface ModelInfo {
396
454
  /** Hub repository id, when loaded from the hub. */
@@ -399,11 +457,19 @@ export interface ModelInfo {
399
457
  readonly revision?: string;
400
458
  readonly modelType: string;
401
459
  readonly architecture: string;
402
- /** Backend actually used, e.g. `"cpu"`. */
460
+ /**
461
+ * Device actually used: `"cpu"`, `"webgpu"` (the WebAssembly engine on
462
+ * WebGPU) or `"gpu"` (the native engine on Metal, Vulkan or DX12).
463
+ */
403
464
  readonly device: Exclude<Device, "auto">;
465
+ /** The engine build that runs the model (see {@link LoadModelOptions.backend}). */
466
+ readonly runtime: Exclude<Backend, "auto">;
467
+ /** Why `backend: "auto"` did not pick the native engine, in Node. */
468
+ readonly runtimeNote?: string;
404
469
  /**
405
- * Human-readable backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"` or
406
- * `"WebGPU (Apple M3)"`.
470
+ * Human-readable backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"`,
471
+ * `"WebGPU (Apple M3)"`, `"CPU (native, neon-i8mm, 10 threads)"` or
472
+ * `"GPU (native, Apple M5, Metal)"`.
407
473
  */
408
474
  readonly backend: string;
409
475
  /** How the CPU backend runs, when the model runs on it. */
@@ -434,6 +500,8 @@ export interface ModelInfo {
434
500
  readonly files: readonly LoadedFile[];
435
501
  /** Whether every file came from the local cache (no download). */
436
502
  readonly fromCache: boolean;
503
+ /** What the load did with the converted-weight cache ({@link LoadModelOptions.weightCache}). */
504
+ readonly weightCache: WeightCacheInfo;
437
505
  /** Milliseconds spent downloading and loading. */
438
506
  readonly loadTimeMs: number;
439
507
  }
@@ -0,0 +1,47 @@
1
+ {
2
+ "version": "0.4.1",
3
+ "assets": {
4
+ "darwin-arm64": {
5
+ "file": "webslm-node-0.4.1-darwin-arm64.node.gz",
6
+ "size": 4528290,
7
+ "sha256": "fef370b0bc05f3190cd91c963bec7d05a48e1c32528ee394c2a38fe599af1e02",
8
+ "nodeSha256": "11c00c4af4394be95076c45cb14a39bf6486cd22c59e93a0c6745bc1c0f8fa6c"
9
+ },
10
+ "darwin-x64": {
11
+ "file": "webslm-node-0.4.1-darwin-x64.node.gz",
12
+ "size": 4781839,
13
+ "sha256": "b1e11294b083e8b7f7db9f3100193d2aa9642796e9791feb7582803ac2831b03",
14
+ "nodeSha256": "25b7f086532e91f0c3fca8ad709f7c4a7000eaff00d9a93970d808b13ba0b923"
15
+ },
16
+ "linux-x64-gnu": {
17
+ "file": "webslm-node-0.4.1-linux-x64-gnu.node.gz",
18
+ "size": 4811944,
19
+ "sha256": "147528671faa5e52485eb409207b72b5bc225175713194e99c783c7da2b70d4a",
20
+ "nodeSha256": "80a1cbcc204ed65d8799c13d2c8a5248646a66f72f0ea18aaa7f629f37e1f695"
21
+ },
22
+ "linux-arm64-gnu": {
23
+ "file": "webslm-node-0.4.1-linux-arm64-gnu.node.gz",
24
+ "size": 4531590,
25
+ "sha256": "cc9bb90288fc968f92f462f31dd7929054243d39fc03401525ad0ddc04b1f505",
26
+ "nodeSha256": "3f5189ce553fb76f7439568dc492ce464849e11f31f82da865fa3079e5176407"
27
+ },
28
+ "linux-x64-musl": {
29
+ "file": "webslm-node-0.4.1-linux-x64-musl.node.gz",
30
+ "size": 5174150,
31
+ "sha256": "dfced45eaaccaaaf90ceb7b3685198d137181dda270956164a462af847ebc341",
32
+ "nodeSha256": "bf54d6bf59c205f2f03ce4da64e5a015ccf510b92013fc1a6bc7a5c33cd752d1"
33
+ },
34
+ "linux-arm64-musl": {
35
+ "file": "webslm-node-0.4.1-linux-arm64-musl.node.gz",
36
+ "size": 5012588,
37
+ "sha256": "e4293a066377971e4e900256fcb182a12371b3907c9f2b6dbe5bc7a01a3f7053",
38
+ "nodeSha256": "e6dd20315c5354a8c21ffebb59476bdc8c993ae21e9a3c00d573ae8a0adc7928"
39
+ },
40
+ "win32-x64-msvc": {
41
+ "file": "webslm-node-0.4.1-win32-x64-msvc.node.gz",
42
+ "size": 5247323,
43
+ "sha256": "570e537e95223ccc2a25c650ae7cd96f2999ce5f08b059add1e98846074a506d",
44
+ "nodeSha256": "a1cd8bf4a3c77f01bdc848f783daa1aeae7786d1aa28f8d7a262915d7f6b3152"
45
+ }
46
+ }
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webslm",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Run small language models in the browser and in Node, straight from their original Hugging Face checkpoints: a Rust engine compiled to WebAssembly, in a worker, with an offline cache.",
5
5
  "license": "MIT",
6
6
  "author": "Maxime Golfier",
@@ -50,6 +50,7 @@
50
50
  },
51
51
  "files": [
52
52
  "dist",
53
+ "native-manifest.json",
53
54
  "wasm/simd/webslm_wasm.js",
54
55
  "wasm/simd/webslm_wasm.d.ts",
55
56
  "wasm/simd/webslm_wasm_bg.wasm",
@@ -17,6 +17,21 @@ export class JsSource {
17
17
  constructor(read: Function, list?: Function | null);
18
18
  }
19
19
 
20
+ /**
21
+ * The converted-weight file of one model load (see the module docs).
22
+ */
23
+ export class JsWeightCache {
24
+ free(): void;
25
+ [Symbol.dispose](): void;
26
+ /**
27
+ * `key` names the converted checkpoint (`"org/name@sha"`; the load
28
+ * format is appended). `read(start, end)` resolves to bytes
29
+ * `[start, end)` of the stored file of `size` bytes (`0`: none);
30
+ * `write(chunk)` appends to the new file and may return a promise.
31
+ */
32
+ constructor(key: string, size: number, read: Function, write: Function);
33
+ }
34
+
20
35
  /**
21
36
  * Incremental SHA-256.
22
37
  */
@@ -92,8 +107,13 @@ export class WasmModel {
92
107
  * (default 1), in `adapterMode` (default `"unmerged"`: its delta is
93
108
  * added in f32 beside the weights; `"merged"` merges it into the
94
109
  * weights as they load).
110
+ *
111
+ * `weightCache`, when given, keeps the converted (block-quantized)
112
+ * weights: a valid stored file serves them instead of converting the
113
+ * checkpoint, else they are written to it as they are converted;
114
+ * `info().weightCache` says which (see [`WeightCacheOutcome`]).
95
115
  */
96
- static load(source: JsSource, options_json: string, lora?: JsSource | null): Promise<WasmModel>;
116
+ static load(source: JsSource, options_json: string, lora?: JsSource | null, weight_cache?: JsWeightCache | null): Promise<WasmModel>;
97
117
  /**
98
118
  * Removes the adapter, restoring the base weights exactly. Resolves to
99
119
  * the description of the adapter removed, or `null` when there was
@@ -251,11 +271,13 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
251
271
  export interface InitOutput {
252
272
  readonly memory: WebAssembly.Memory;
253
273
  readonly __wbg_jssource_free: (a: number, b: number) => void;
274
+ readonly __wbg_jsweightcache_free: (a: number, b: number) => void;
254
275
  readonly __wbg_sha256hasher_free: (a: number, b: number) => void;
255
276
  readonly __wbg_wasmmodel_free: (a: number, b: number) => void;
256
277
  readonly __wbg_wasmsession_free: (a: number, b: number) => void;
257
278
  readonly buildInfo: () => [number, number, number];
258
279
  readonly jssource_new: (a: any, b: number) => number;
280
+ readonly jsweightcache_new: (a: number, b: number, c: number, d: any, e: any) => number;
259
281
  readonly parseSafetensorsHeader: (a: number, b: number) => [number, number, number];
260
282
  readonly sha256hasher_finish: (a: number) => [number, number];
261
283
  readonly sha256hasher_new: () => number;
@@ -268,7 +290,7 @@ export interface InitOutput {
268
290
  readonly wasmmodel_detokenize: (a: number, b: number, c: number, d: number) => [number, number, number, number];
269
291
  readonly wasmmodel_generate: (a: number, b: number, c: number, d: number, e: number, f: any, g: number) => any;
270
292
  readonly wasmmodel_info: (a: number) => [number, number, number];
271
- readonly wasmmodel_load: (a: number, b: number, c: number, d: number) => any;
293
+ readonly wasmmodel_load: (a: number, b: number, c: number, d: number, e: number) => any;
272
294
  readonly wasmmodel_removeAdapter: (a: number) => any;
273
295
  readonly wasmmodel_renderChat: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
274
296
  readonly wasmmodel_reset: (a: number) => [number, number];
@@ -289,10 +311,10 @@ export interface InitOutput {
289
311
  readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___js_sys_56365fc49d784db6___Function_fn_wasm_bindgen_8cf186fa7724d16d___JsValue_____wasm_bindgen_8cf186fa7724d16d___sys__Undefined___js_sys_56365fc49d784db6___Function_fn_wasm_bindgen_8cf186fa7724d16d___JsValue_____wasm_bindgen_8cf186fa7724d16d___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
290
312
  readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wasm_bindgen_8cf186fa7724d16d___JsValue__core_608f92abc48d28da___result__Result_____wasm_bindgen_8cf186fa7724d16d___JsError___true_: (a: number, b: number, c: any) => [number, number];
291
313
  readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wasm_bindgen_8cf186fa7724d16d___sys__JsNullable_wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_608f92abc48d28da___result__Result_____wasm_bindgen_8cf186fa7724d16d___JsError___true_: (a: number, b: number, c: any) => [number, number];
292
- readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wasm_bindgen_8cf186fa7724d16d___sys__JsNullable_wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_608f92abc48d28da___result__Result_____wasm_bindgen_8cf186fa7724d16d___JsError___true__37: (a: number, b: number, c: any) => [number, number];
293
314
  readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wasm_bindgen_8cf186fa7724d16d___sys__JsNullable_wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_608f92abc48d28da___result__Result_____wasm_bindgen_8cf186fa7724d16d___JsError___true__38: (a: number, b: number, c: any) => [number, number];
315
+ readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wasm_bindgen_8cf186fa7724d16d___sys__JsNullable_wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_608f92abc48d28da___result__Result_____wasm_bindgen_8cf186fa7724d16d___JsError___true__39: (a: number, b: number, c: any) => [number, number];
294
316
  readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuDeviceLostInfo__GpuDeviceLostInfo______true_: (a: number, b: number, c: any) => void;
295
- readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuDeviceLostInfo__GpuDeviceLostInfo______true__36: (a: number, b: number, c: any) => void;
317
+ readonly wasm_bindgen_8cf186fa7724d16d___convert__closures_____invoke___wgpu_54917290532eaf6b___backend__webgpu__webgpu_sys__gen_GpuDeviceLostInfo__GpuDeviceLostInfo______true__37: (a: number, b: number, c: any) => void;
296
318
  readonly __wbindgen_malloc: (a: number, b: number) => number;
297
319
  readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
298
320
  readonly __wbindgen_exn_store: (a: number) => void;