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.
- package/README.md +64 -12
- package/dist/ai-sdk/index.d.ts +1 -1
- package/dist/ai-sdk/index.js +1 -1
- package/dist/cache/models.d.ts +32 -3
- package/dist/cache/models.js +106 -11
- package/dist/cache/node-fs.d.ts +26 -3
- package/dist/cache/node-fs.js +43 -9
- package/dist/cache-management.d.ts +1 -1
- package/dist/curated.d.ts +31 -1
- package/dist/curated.js +49 -5
- package/dist/download.d.ts +4 -0
- package/dist/download.js +29 -4
- package/dist/engine.d.ts +33 -4
- package/dist/engine.js +451 -44
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/models.d.ts +26 -6
- package/dist/models.js +63 -7
- package/dist/native.d.ts +165 -0
- package/dist/native.js +243 -0
- package/dist/protocol.d.ts +12 -2
- package/dist/recommended-sampling.d.ts +54 -0
- package/dist/recommended-sampling.js +73 -0
- package/dist/simple.d.ts +22 -8
- package/dist/simple.js +35 -9
- package/dist/types.d.ts +85 -17
- package/native-manifest.json +47 -0
- package/package.json +2 -1
- package/wasm/relaxed/webslm_wasm.d.ts +26 -4
- package/wasm/relaxed/webslm_wasm.js +70 -17
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
- package/wasm/simd/webslm_wasm.d.ts +26 -4
- package/wasm/simd/webslm_wasm.js +70 -17
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
- package/wasm/threads/webslm_wasm.d.ts +26 -4
- package/wasm/threads/webslm_wasm.js +75 -22
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +5 -3
package/dist/index.d.ts
CHANGED
|
@@ -18,9 +18,9 @@ import type { SafetensorsHeader } from "./safetensors.js";
|
|
|
18
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
19
|
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
20
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
21
|
-
export type { Activations, AdapterMode, 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";
|
|
21
|
+
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
22
22
|
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
23
|
-
export { CURATED_MODELS, type CuratedModel } from "./curated.js";
|
|
23
|
+
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
|
|
24
24
|
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
25
25
|
export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
|
|
26
26
|
export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
|
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
|
|
|
19
19
|
export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
20
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
|
|
21
21
|
export { WebslmError } from "./errors.js";
|
|
22
|
-
export { CURATED_MODELS } from "./curated.js";
|
|
22
|
+
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "./curated.js";
|
|
23
23
|
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
24
24
|
export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
|
|
25
25
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
|
package/dist/models.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
|
|
2
2
|
import { EngineClient } from "./client.js";
|
|
3
|
-
import
|
|
3
|
+
import { type CheckpointTraits } from "./curated.js";
|
|
4
|
+
import type { AdapterSource, Backend, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
|
|
4
5
|
/**
|
|
5
6
|
* An engine (a worker, or the calling thread) that several models can share
|
|
6
7
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -31,11 +32,16 @@ export declare function createEngine(options?: {
|
|
|
31
32
|
}): Promise<EngineHandle>;
|
|
32
33
|
/**
|
|
33
34
|
* Validates `device` (default `"auto"`). The engine decides what actually
|
|
34
|
-
* runs: `"auto"` is
|
|
35
|
-
* is available, the CPU otherwise; `"webgpu"`
|
|
36
|
-
* {@link
|
|
35
|
+
* runs: `"auto"` is the GPU for models above ~100M parameters when an adapter
|
|
36
|
+
* is available, the CPU otherwise; `"gpu"` (or `"webgpu"`) asks for the GPU
|
|
37
|
+
* (see {@link LoadModelOptions.device}).
|
|
37
38
|
*/
|
|
38
39
|
export declare function resolveDevice(device: Device | undefined): Device;
|
|
40
|
+
/**
|
|
41
|
+
* Validates `backend`. Its default is `WEBSLM_BACKEND` in Node (to pin a
|
|
42
|
+
* deployment to one engine without changing code), else `"auto"`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function resolveBackend(backend: Backend | undefined, env?: Readonly<Record<string, string | undefined>> | undefined): Backend;
|
|
39
45
|
/** Normalized form of a {@link ModelSource}. */
|
|
40
46
|
export type NormalizedSource = {
|
|
41
47
|
readonly kind: "hub";
|
|
@@ -68,8 +74,9 @@ export declare function normalizeAdapterSource(source: AdapterSource, revision?:
|
|
|
68
74
|
* for await (const delta of model.chat([{ role: "user", content: "Hi!" }])) console.log(delta);
|
|
69
75
|
* ```
|
|
70
76
|
*
|
|
71
|
-
* Hub checkpoints are downloaded once into the cache (OPFS in browsers,
|
|
72
|
-
*
|
|
77
|
+
* Hub checkpoints are downloaded once into the cache (OPFS in browsers, the
|
|
78
|
+
* command-line tool's cache directory in Node) and read from it afterwards,
|
|
79
|
+
* without network.
|
|
73
80
|
*/
|
|
74
81
|
export declare function loadModel(source: string | ModelSource, options?: LoadModelOptions): Promise<Model>;
|
|
75
82
|
/**
|
|
@@ -82,6 +89,15 @@ export declare function resolveAutoQuant(source: NormalizedSource, options: Load
|
|
|
82
89
|
quant: Quant;
|
|
83
90
|
note?: string;
|
|
84
91
|
}>;
|
|
92
|
+
/**
|
|
93
|
+
* `options` with the sampling fields it leaves unset taken from the model
|
|
94
|
+
* card of a curated repository ({@link recommendedSampling}), for the
|
|
95
|
+
* thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
|
|
96
|
+
* other repositories, and with `temperature: 0` (greedy decoding).
|
|
97
|
+
*
|
|
98
|
+
* @internal
|
|
99
|
+
*/
|
|
100
|
+
export declare function withRecommendedSampling<T extends GenerateOptions>(options: T, checkpoint: string | CheckpointTraits | undefined): T;
|
|
85
101
|
/** Operations shared by {@link Model} (its default session) and {@link Session}. */
|
|
86
102
|
declare abstract class Conversation {
|
|
87
103
|
#private;
|
|
@@ -89,6 +105,8 @@ declare abstract class Conversation {
|
|
|
89
105
|
protected readonly modelId: number;
|
|
90
106
|
protected abstract readonly sessionId: number | undefined;
|
|
91
107
|
protected abstract readonly hasChatTemplate: boolean;
|
|
108
|
+
/** What picks the model's recommended sampling. */
|
|
109
|
+
protected abstract readonly checkpoint: CheckpointTraits;
|
|
92
110
|
protected abstract onLength(length: number): void;
|
|
93
111
|
constructor(client: EngineClient, modelId: number);
|
|
94
112
|
/**
|
|
@@ -133,6 +151,7 @@ export declare class Model extends Conversation {
|
|
|
133
151
|
readonly cacheDir?: string;
|
|
134
152
|
}, ownsEngine?: boolean);
|
|
135
153
|
protected get hasChatTemplate(): boolean;
|
|
154
|
+
protected get checkpoint(): CheckpointTraits;
|
|
136
155
|
protected onLength(): void;
|
|
137
156
|
/** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
|
|
138
157
|
info(): ModelInfo;
|
|
@@ -185,6 +204,7 @@ export declare class Session extends Conversation {
|
|
|
185
204
|
/** @internal */
|
|
186
205
|
constructor(client: EngineClient, modelId: number, sessionId: number, info: ModelInfo, onDispose: () => void);
|
|
187
206
|
protected get hasChatTemplate(): boolean;
|
|
207
|
+
protected get checkpoint(): CheckpointTraits;
|
|
188
208
|
protected onLength(length: number): void;
|
|
189
209
|
/** Positions in the cache (as of the last completed call). */
|
|
190
210
|
get length(): number;
|
package/dist/models.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
|
|
2
2
|
import { AsyncQueue } from "./async-queue.js";
|
|
3
3
|
import { EngineClient } from "./client.js";
|
|
4
|
+
import { recommendedSampling } from "./curated.js";
|
|
4
5
|
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
5
6
|
import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
|
|
6
7
|
import { checkModel } from "./hub.js";
|
|
@@ -44,9 +45,9 @@ export async function createEngine(options = {}) {
|
|
|
44
45
|
}
|
|
45
46
|
/**
|
|
46
47
|
* Validates `device` (default `"auto"`). The engine decides what actually
|
|
47
|
-
* runs: `"auto"` is
|
|
48
|
-
* is available, the CPU otherwise; `"webgpu"`
|
|
49
|
-
* {@link
|
|
48
|
+
* runs: `"auto"` is the GPU for models above ~100M parameters when an adapter
|
|
49
|
+
* is available, the CPU otherwise; `"gpu"` (or `"webgpu"`) asks for the GPU
|
|
50
|
+
* (see {@link LoadModelOptions.device}).
|
|
50
51
|
*/
|
|
51
52
|
export function resolveDevice(device) {
|
|
52
53
|
switch (device ?? "auto") {
|
|
@@ -54,12 +55,28 @@ export function resolveDevice(device) {
|
|
|
54
55
|
return "auto";
|
|
55
56
|
case "cpu":
|
|
56
57
|
return "cpu";
|
|
58
|
+
case "gpu":
|
|
59
|
+
return "gpu";
|
|
57
60
|
case "webgpu":
|
|
58
61
|
return "webgpu";
|
|
59
62
|
default:
|
|
60
63
|
throw new WebslmError("INVALID_ARGUMENT", `unknown device "${String(device)}"`);
|
|
61
64
|
}
|
|
62
65
|
}
|
|
66
|
+
const BACKENDS = ["auto", "native", "wasm"];
|
|
67
|
+
/**
|
|
68
|
+
* Validates `backend`. Its default is `WEBSLM_BACKEND` in Node (to pin a
|
|
69
|
+
* deployment to one engine without changing code), else `"auto"`.
|
|
70
|
+
*/
|
|
71
|
+
export function resolveBackend(backend, env = globalThis.process?.env) {
|
|
72
|
+
const fromEnv = env?.["WEBSLM_BACKEND"]?.trim();
|
|
73
|
+
const value = backend ?? (fromEnv === undefined || fromEnv === "" ? "auto" : fromEnv);
|
|
74
|
+
if (!BACKENDS.includes(value)) {
|
|
75
|
+
const where = backend === undefined ? `WEBSLM_BACKEND (${String(fromEnv)})` : "backend";
|
|
76
|
+
throw new WebslmError("INVALID_ARGUMENT", `${where} must be one of ${BACKENDS.join(", ")}`);
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
63
80
|
/** Checks a source and turns a repository id string into a hub source. */
|
|
64
81
|
export function normalizeSource(source, revision) {
|
|
65
82
|
if (typeof source === "string") {
|
|
@@ -169,11 +186,13 @@ function requestPersistentStorage() {
|
|
|
169
186
|
* for await (const delta of model.chat([{ role: "user", content: "Hi!" }])) console.log(delta);
|
|
170
187
|
* ```
|
|
171
188
|
*
|
|
172
|
-
* Hub checkpoints are downloaded once into the cache (OPFS in browsers,
|
|
173
|
-
*
|
|
189
|
+
* Hub checkpoints are downloaded once into the cache (OPFS in browsers, the
|
|
190
|
+
* command-line tool's cache directory in Node) and read from it afterwards,
|
|
191
|
+
* without network.
|
|
174
192
|
*/
|
|
175
193
|
export async function loadModel(source, options = {}) {
|
|
176
194
|
const device = resolveDevice(options.device);
|
|
195
|
+
const backend = resolveBackend(options.backend);
|
|
177
196
|
const requested = options.quant ?? "q8";
|
|
178
197
|
if (requested !== "auto" && !QUANTS.includes(requested)) {
|
|
179
198
|
throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
|
|
@@ -202,11 +221,14 @@ export async function loadModel(source, options = {}) {
|
|
|
202
221
|
...(adapter === undefined ? {} : { adapter: toWire(adapter, options.token) }),
|
|
203
222
|
options: {
|
|
204
223
|
quant,
|
|
224
|
+
...(requested === "auto" ? { autoQuant: true } : {}),
|
|
205
225
|
device,
|
|
226
|
+
...(backend === "auto" ? {} : { backend }),
|
|
206
227
|
...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
|
|
207
228
|
...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
|
|
208
229
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
209
230
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
231
|
+
...(options.weightCache === false ? { weightCache: false } : {}),
|
|
210
232
|
...(options.deterministic === true ? { deterministic: true } : {}),
|
|
211
233
|
...(options.activations === undefined ? {} : { activations: options.activations }),
|
|
212
234
|
...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
|
|
@@ -218,7 +240,9 @@ export async function loadModel(source, options = {}) {
|
|
|
218
240
|
...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
|
|
219
241
|
...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
|
|
220
242
|
});
|
|
221
|
-
|
|
243
|
+
// The native engine chose the format again, from the machine's memory
|
|
244
|
+
// (its own note says why when it did not load q8).
|
|
245
|
+
const info = quantNote === undefined || result.info.runtime === "native" ? result.info : { ...result.info, quantNote };
|
|
222
246
|
return new Model(client, result.model, info, {
|
|
223
247
|
...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
|
|
224
248
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
@@ -332,6 +356,32 @@ function wireOptions(options) {
|
|
|
332
356
|
out.contextShift = options.contextShift;
|
|
333
357
|
return out;
|
|
334
358
|
}
|
|
359
|
+
/**
|
|
360
|
+
* `options` with the sampling fields it leaves unset taken from the model
|
|
361
|
+
* card of a curated repository ({@link recommendedSampling}), for the
|
|
362
|
+
* thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
|
|
363
|
+
* other repositories, and with `temperature: 0` (greedy decoding).
|
|
364
|
+
*
|
|
365
|
+
* @internal
|
|
366
|
+
*/
|
|
367
|
+
export function withRecommendedSampling(options, checkpoint) {
|
|
368
|
+
if (options.temperature === 0)
|
|
369
|
+
return options;
|
|
370
|
+
const think = options.templateKwargs?.["enable_thinking"];
|
|
371
|
+
const recommended = recommendedSampling(checkpoint, typeof think === "boolean" ? think : undefined);
|
|
372
|
+
if (recommended === undefined)
|
|
373
|
+
return options;
|
|
374
|
+
const out = { ...options };
|
|
375
|
+
for (const key of Object.keys(recommended)) {
|
|
376
|
+
if (out[key] === undefined)
|
|
377
|
+
out[key] = recommended[key];
|
|
378
|
+
}
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
/** What picks a loaded model's recommended sampling. */
|
|
382
|
+
function checkpointTraits(info) {
|
|
383
|
+
return { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
|
|
384
|
+
}
|
|
335
385
|
/** A `delta` message as a {@link GeneratedToken}. */
|
|
336
386
|
function generatedToken(delta) {
|
|
337
387
|
return {
|
|
@@ -464,7 +514,7 @@ class Conversation {
|
|
|
464
514
|
return text;
|
|
465
515
|
}
|
|
466
516
|
#stream(body, generateOptions) {
|
|
467
|
-
const options = wireOptions(generateOptions);
|
|
517
|
+
const options = wireOptions(withRecommendedSampling(generateOptions, this.checkpoint));
|
|
468
518
|
const { onPrefill } = generateOptions;
|
|
469
519
|
const session = this.sessionId === undefined ? {} : { session: this.sessionId };
|
|
470
520
|
// Stopping aborts the request; the engine then ends the generation
|
|
@@ -534,6 +584,9 @@ export class Model extends Conversation {
|
|
|
534
584
|
get hasChatTemplate() {
|
|
535
585
|
return this.#info.hasChatTemplate;
|
|
536
586
|
}
|
|
587
|
+
get checkpoint() {
|
|
588
|
+
return checkpointTraits(this.#info);
|
|
589
|
+
}
|
|
537
590
|
onLength() { }
|
|
538
591
|
/** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
|
|
539
592
|
info() {
|
|
@@ -642,6 +695,9 @@ export class Session extends Conversation {
|
|
|
642
695
|
get hasChatTemplate() {
|
|
643
696
|
return this.#info.hasChatTemplate;
|
|
644
697
|
}
|
|
698
|
+
get checkpoint() {
|
|
699
|
+
return checkpointTraits(this.#info);
|
|
700
|
+
}
|
|
645
701
|
onLength(length) {
|
|
646
702
|
this.#length = length;
|
|
647
703
|
}
|
package/dist/native.d.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The native engine in Node: a Node-API addon built from the same Rust
|
|
3
|
+
* engine (`crates/webslm-node`). Each release attaches it to its GitHub
|
|
4
|
+
* Release for every platform (`webslm-node-<version>-<platform>.node.gz`),
|
|
5
|
+
* and the published package carries their SHA-256 (`native-manifest.json`).
|
|
6
|
+
* On first use the addon of this platform is downloaded into the cache
|
|
7
|
+
* directory, checked against the manifest and loaded; later runs load it
|
|
8
|
+
* from the cache, without network. When it cannot be (no build for this
|
|
9
|
+
* platform, offline, a failed download, a checksum that does not match) the
|
|
10
|
+
* WebAssembly engine runs instead. No install script runs.
|
|
11
|
+
*
|
|
12
|
+
* The addon runs the native CPU kernels (NEON, AVX2, AVX-512 VNNI) on every
|
|
13
|
+
* core and the GPU through `wgpu` (Metal on macOS, Vulkan or DX12 on Linux
|
|
14
|
+
* and Windows), with the device rules of the command-line tool.
|
|
15
|
+
*
|
|
16
|
+
* Node-only: the engine imports this module only in Node; browser bundles
|
|
17
|
+
* never download or load the addon.
|
|
18
|
+
*/
|
|
19
|
+
/** What `info()` of a native model reports (the WebAssembly fields, `device` added). */
|
|
20
|
+
export interface NativeModelInfo {
|
|
21
|
+
readonly device: "gpu" | "cpu";
|
|
22
|
+
readonly [key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
/** Stops a native call (see `CancelToken` in `crates/webslm-node`). */
|
|
25
|
+
export interface NativeCancelToken {
|
|
26
|
+
cancel(): void;
|
|
27
|
+
readonly cancelled: boolean;
|
|
28
|
+
}
|
|
29
|
+
export type NativeDeltaCallback = (text: string, token: number, info: {
|
|
30
|
+
logprob?: number;
|
|
31
|
+
topLogprobs?: [number, number][];
|
|
32
|
+
forced?: boolean;
|
|
33
|
+
} | null) => void;
|
|
34
|
+
export type NativePrefillCallback = (done: number, total: number) => void;
|
|
35
|
+
/** A session of a native model; every call resolves on the model's thread. */
|
|
36
|
+
export interface NativeSession {
|
|
37
|
+
chat(messagesJson: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
|
|
38
|
+
generate(prompt: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
|
|
39
|
+
fork(): Promise<NativeSession>;
|
|
40
|
+
scoreContinuations(prefix: Uint32Array, continuationsJson: string): Promise<Float32Array[]>;
|
|
41
|
+
shiftContext(keep: number, drop: number): Promise<number>;
|
|
42
|
+
score(ids: Uint32Array, optionsJson: string): Promise<unknown>;
|
|
43
|
+
step(id: number, optionsJson: string): Promise<unknown>;
|
|
44
|
+
truncate(length: number): Promise<number>;
|
|
45
|
+
reset(): Promise<void>;
|
|
46
|
+
readonly length: number;
|
|
47
|
+
free(): void;
|
|
48
|
+
}
|
|
49
|
+
/** Settings of a load that only the native engine takes. */
|
|
50
|
+
export interface NativeLoadArgs {
|
|
51
|
+
readonly adapterDir?: string;
|
|
52
|
+
readonly weightCacheDir?: string;
|
|
53
|
+
readonly weightCacheKey?: string;
|
|
54
|
+
readonly threads?: number;
|
|
55
|
+
}
|
|
56
|
+
/** A model loaded by the native engine. */
|
|
57
|
+
export interface NativeModel {
|
|
58
|
+
info(): NativeModelInfo;
|
|
59
|
+
applyAdapter(dir: string, optionsJson: string): Promise<unknown>;
|
|
60
|
+
removeAdapter(): Promise<unknown>;
|
|
61
|
+
createSession(): Promise<NativeSession>;
|
|
62
|
+
chat: NativeSession["chat"];
|
|
63
|
+
generate: NativeSession["generate"];
|
|
64
|
+
reset(): Promise<void>;
|
|
65
|
+
tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
|
|
66
|
+
detokenize(ids: Uint32Array, skipSpecialTokens: boolean): Promise<string>;
|
|
67
|
+
renderChat(messagesJson: string, kwargsJson: string): Promise<string>;
|
|
68
|
+
free(): void;
|
|
69
|
+
}
|
|
70
|
+
/** The exports of the addon. */
|
|
71
|
+
export interface NativeAddon {
|
|
72
|
+
version(): string;
|
|
73
|
+
supportedModelTypes(): string[];
|
|
74
|
+
buildInfo(): {
|
|
75
|
+
version: string;
|
|
76
|
+
target: string;
|
|
77
|
+
kernels: string;
|
|
78
|
+
threads: number;
|
|
79
|
+
};
|
|
80
|
+
readonly NativeModel: {
|
|
81
|
+
load(dir: string, optionsJson: string, args?: NativeLoadArgs | null): Promise<NativeModel>;
|
|
82
|
+
};
|
|
83
|
+
readonly CancelToken: new () => NativeCancelToken;
|
|
84
|
+
}
|
|
85
|
+
/** Where the addon came from, or why it could not load. */
|
|
86
|
+
export type NativeAvailability = {
|
|
87
|
+
readonly addon: NativeAddon;
|
|
88
|
+
readonly source: string;
|
|
89
|
+
} | {
|
|
90
|
+
readonly addon?: undefined;
|
|
91
|
+
readonly reason: string;
|
|
92
|
+
};
|
|
93
|
+
/** What {@link nativePlatform} reads; `process` by default. */
|
|
94
|
+
export interface PlatformInfo {
|
|
95
|
+
readonly platform: string;
|
|
96
|
+
readonly arch: string;
|
|
97
|
+
/** Linux only: whether the C library is musl (Alpine) rather than glibc. */
|
|
98
|
+
readonly musl?: boolean;
|
|
99
|
+
}
|
|
100
|
+
/** The platforms the native engine is released for. */
|
|
101
|
+
export declare const NATIVE_PLATFORMS: readonly ["darwin-arm64", "darwin-x64", "linux-x64-gnu", "linux-arm64-gnu", "linux-x64-musl", "linux-arm64-musl", "win32-x64-msvc"];
|
|
102
|
+
export type NativePlatform = (typeof NATIVE_PLATFORMS)[number];
|
|
103
|
+
/** Where the release assets are downloaded from (`WEBSLM_NATIVE_URL` replaces it: a mirror, or tests). */
|
|
104
|
+
export declare const NATIVE_RELEASES = "https://github.com/maxgfr/webslm/releases/download";
|
|
105
|
+
/** Most milliseconds the download of the addon may take before WebAssembly runs instead. */
|
|
106
|
+
export declare const NATIVE_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
107
|
+
/** The native platform of `info`, when the engine is released for it. */
|
|
108
|
+
export declare function nativePlatform(info: PlatformInfo): NativePlatform | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* `native-manifest.json`, written into the package when it is published
|
|
111
|
+
* (`scripts/release/native-manifest.mjs`): for each platform, the asset on
|
|
112
|
+
* the GitHub Release of the version and the SHA-256 of its bytes and of the
|
|
113
|
+
* addon inside.
|
|
114
|
+
*/
|
|
115
|
+
export interface NativeManifest {
|
|
116
|
+
readonly version: string;
|
|
117
|
+
readonly assets: Readonly<Record<string, {
|
|
118
|
+
readonly file: string;
|
|
119
|
+
readonly size: number;
|
|
120
|
+
readonly sha256: string;
|
|
121
|
+
readonly nodeSha256: string;
|
|
122
|
+
}>>;
|
|
123
|
+
}
|
|
124
|
+
/** Why the native engine cannot run; `auto` falls back to WebAssembly with this reason. */
|
|
125
|
+
export declare class NativeUnavailable extends Error {
|
|
126
|
+
readonly name = "NativeUnavailable";
|
|
127
|
+
}
|
|
128
|
+
/** What {@link fetchNativeAddon} needs; tests pass a fake manifest and server. */
|
|
129
|
+
export interface NativeFetchOptions {
|
|
130
|
+
readonly platform: NativePlatform;
|
|
131
|
+
/** The version of this package: the release the asset comes from. */
|
|
132
|
+
readonly version: string;
|
|
133
|
+
/** `undefined` when the package has none (built from source). */
|
|
134
|
+
readonly manifest: NativeManifest | undefined;
|
|
135
|
+
/** The webslm cache directory; the addon goes to `<cacheDir>/native/<version>/`. */
|
|
136
|
+
readonly cacheDir: string;
|
|
137
|
+
/** Default {@link NATIVE_RELEASES}. */
|
|
138
|
+
readonly baseUrl?: string;
|
|
139
|
+
/** Network access forbidden (`WEBSLM_OFFLINE`): only a cached addon is used. */
|
|
140
|
+
readonly offline?: boolean;
|
|
141
|
+
/** Default {@link NATIVE_DOWNLOAD_TIMEOUT_MS}. */
|
|
142
|
+
readonly timeoutMs?: number;
|
|
143
|
+
readonly fetch?: typeof fetch;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The path of a verified copy of the addon for `options.platform`: the one
|
|
147
|
+
* in the cache when its SHA-256 matches the manifest, else the release asset,
|
|
148
|
+
* downloaded, checked (compressed and uncompressed), and stored in the cache.
|
|
149
|
+
* Throws {@link NativeUnavailable} with the reason otherwise.
|
|
150
|
+
*/
|
|
151
|
+
export declare function fetchNativeAddon(options: NativeFetchOptions): Promise<string>;
|
|
152
|
+
/** Whether `auto` may pick the native engine in this runtime. */
|
|
153
|
+
export declare function nativeAutoAllowed(process: {
|
|
154
|
+
versions: Record<string, string | undefined>;
|
|
155
|
+
}): boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Loads the addon once per thread: `WEBSLM_NATIVE_PATH` (a `.node` file, for
|
|
158
|
+
* local builds) when set, else the release asset of this platform and
|
|
159
|
+
* version, from `<cacheDir>/native/<version>/` or downloaded there first and
|
|
160
|
+
* checked against `native-manifest.json` (see {@link fetchNativeAddon}).
|
|
161
|
+
* Resolves with the reason when it cannot be used.
|
|
162
|
+
*/
|
|
163
|
+
export declare function loadNativeAddon(cacheDir?: string): Promise<NativeAvailability>;
|
|
164
|
+
/** @internal Forgets the loaded addon (tests). */
|
|
165
|
+
export declare function resetNativeAddon(): void;
|
package/dist/native.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The native engine in Node: a Node-API addon built from the same Rust
|
|
3
|
+
* engine (`crates/webslm-node`). Each release attaches it to its GitHub
|
|
4
|
+
* Release for every platform (`webslm-node-<version>-<platform>.node.gz`),
|
|
5
|
+
* and the published package carries their SHA-256 (`native-manifest.json`).
|
|
6
|
+
* On first use the addon of this platform is downloaded into the cache
|
|
7
|
+
* directory, checked against the manifest and loaded; later runs load it
|
|
8
|
+
* from the cache, without network. When it cannot be (no build for this
|
|
9
|
+
* platform, offline, a failed download, a checksum that does not match) the
|
|
10
|
+
* WebAssembly engine runs instead. No install script runs.
|
|
11
|
+
*
|
|
12
|
+
* The addon runs the native CPU kernels (NEON, AVX2, AVX-512 VNNI) on every
|
|
13
|
+
* core and the GPU through `wgpu` (Metal on macOS, Vulkan or DX12 on Linux
|
|
14
|
+
* and Windows), with the device rules of the command-line tool.
|
|
15
|
+
*
|
|
16
|
+
* Node-only: the engine imports this module only in Node; browser bundles
|
|
17
|
+
* never download or load the addon.
|
|
18
|
+
*/
|
|
19
|
+
import { importNode } from "./runtime.js";
|
|
20
|
+
/** The platforms the native engine is released for. */
|
|
21
|
+
export const NATIVE_PLATFORMS = [
|
|
22
|
+
"darwin-arm64",
|
|
23
|
+
"darwin-x64",
|
|
24
|
+
"linux-x64-gnu",
|
|
25
|
+
"linux-arm64-gnu",
|
|
26
|
+
"linux-x64-musl",
|
|
27
|
+
"linux-arm64-musl",
|
|
28
|
+
"win32-x64-msvc",
|
|
29
|
+
];
|
|
30
|
+
/** Where the release assets are downloaded from (`WEBSLM_NATIVE_URL` replaces it: a mirror, or tests). */
|
|
31
|
+
export const NATIVE_RELEASES = "https://github.com/maxgfr/webslm/releases/download";
|
|
32
|
+
/** Most milliseconds the download of the addon may take before WebAssembly runs instead. */
|
|
33
|
+
export const NATIVE_DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
34
|
+
/** The native platform of `info`, when the engine is released for it. */
|
|
35
|
+
export function nativePlatform(info) {
|
|
36
|
+
let platform;
|
|
37
|
+
switch (info.platform) {
|
|
38
|
+
case "darwin":
|
|
39
|
+
platform = `darwin-${info.arch}`;
|
|
40
|
+
break;
|
|
41
|
+
case "linux":
|
|
42
|
+
platform = `linux-${info.arch}-${info.musl === true ? "musl" : "gnu"}`;
|
|
43
|
+
break;
|
|
44
|
+
case "win32":
|
|
45
|
+
platform = `win32-${info.arch}-msvc`;
|
|
46
|
+
break;
|
|
47
|
+
default:
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
return NATIVE_PLATFORMS.includes(platform) ? platform : undefined;
|
|
51
|
+
}
|
|
52
|
+
/** Why the native engine cannot run; `auto` falls back to WebAssembly with this reason. */
|
|
53
|
+
export class NativeUnavailable extends Error {
|
|
54
|
+
name = "NativeUnavailable";
|
|
55
|
+
}
|
|
56
|
+
async function sha256Hex(bytes) {
|
|
57
|
+
const crypto = await importNode("crypto");
|
|
58
|
+
return crypto.createHash("sha256").update(bytes).digest("hex");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The path of a verified copy of the addon for `options.platform`: the one
|
|
62
|
+
* in the cache when its SHA-256 matches the manifest, else the release asset,
|
|
63
|
+
* downloaded, checked (compressed and uncompressed), and stored in the cache.
|
|
64
|
+
* Throws {@link NativeUnavailable} with the reason otherwise.
|
|
65
|
+
*/
|
|
66
|
+
export async function fetchNativeAddon(options) {
|
|
67
|
+
const { manifest, version, platform } = options;
|
|
68
|
+
if (manifest === undefined) {
|
|
69
|
+
throw new NativeUnavailable("this build of webslm has no native-manifest.json (built from source: set WEBSLM_NATIVE_PATH)");
|
|
70
|
+
}
|
|
71
|
+
if (manifest.version !== version) {
|
|
72
|
+
throw new NativeUnavailable(`native-manifest.json describes ${manifest.version}, webslm is ${version}`);
|
|
73
|
+
}
|
|
74
|
+
const entry = manifest.assets[platform];
|
|
75
|
+
if (entry === undefined)
|
|
76
|
+
throw new NativeUnavailable(`no native build of ${version} for ${platform}`);
|
|
77
|
+
const fs = await importNode("fs/promises");
|
|
78
|
+
const path = await importNode("path");
|
|
79
|
+
const dir = path.join(options.cacheDir, "native", version);
|
|
80
|
+
const file = path.join(dir, entry.file.replace(/\.gz$/, ""));
|
|
81
|
+
const cached = await fs.readFile(file).catch(() => undefined);
|
|
82
|
+
if (cached !== undefined && (await sha256Hex(cached)) === entry.nodeSha256)
|
|
83
|
+
return file;
|
|
84
|
+
if (options.offline === true) {
|
|
85
|
+
throw new NativeUnavailable(`offline mode is on and the native engine ${version} is not in the cache`);
|
|
86
|
+
}
|
|
87
|
+
const url = `${options.baseUrl ?? NATIVE_RELEASES}/v${version}/${entry.file}`;
|
|
88
|
+
let gzipped;
|
|
89
|
+
try {
|
|
90
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
91
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? NATIVE_DOWNLOAD_TIMEOUT_MS),
|
|
92
|
+
});
|
|
93
|
+
if (!response.ok)
|
|
94
|
+
throw new Error(`HTTP ${response.status}`);
|
|
95
|
+
gzipped = new Uint8Array(await response.arrayBuffer());
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
99
|
+
throw new NativeUnavailable(`cannot download the native engine from ${url} (${message})`);
|
|
100
|
+
}
|
|
101
|
+
if ((await sha256Hex(gzipped)) !== entry.sha256) {
|
|
102
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
|
|
103
|
+
}
|
|
104
|
+
const zlib = await importNode("zlib");
|
|
105
|
+
let addon;
|
|
106
|
+
try {
|
|
107
|
+
addon = zlib.gunzipSync(gzipped);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} is not a gzip file`);
|
|
111
|
+
}
|
|
112
|
+
if ((await sha256Hex(addon)) !== entry.nodeSha256) {
|
|
113
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
|
|
114
|
+
}
|
|
115
|
+
// Written under a temporary name and renamed: concurrent processes never
|
|
116
|
+
// load a partial file.
|
|
117
|
+
await fs.mkdir(dir, { recursive: true });
|
|
118
|
+
const partial = `${file}.${Date.now()}-${Math.random().toString(36).slice(2)}.partial`;
|
|
119
|
+
try {
|
|
120
|
+
await fs.writeFile(partial, addon);
|
|
121
|
+
await fs.rename(partial, file);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
await fs.rm(partial, { force: true }).catch(() => { });
|
|
125
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
126
|
+
throw new NativeUnavailable(`cannot store the native engine in ${dir} (${message})`);
|
|
127
|
+
}
|
|
128
|
+
return file;
|
|
129
|
+
}
|
|
130
|
+
function nodeProcess() {
|
|
131
|
+
return globalThis.process;
|
|
132
|
+
}
|
|
133
|
+
/** Whether Linux runs on musl: glibc reports its version in the process report. */
|
|
134
|
+
async function isMusl(process) {
|
|
135
|
+
try {
|
|
136
|
+
const report = process.report?.getReport();
|
|
137
|
+
if (report?.header !== undefined)
|
|
138
|
+
return report.header.glibcVersionRuntime === undefined;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// Reports can be turned off.
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const fs = await importNode("fs/promises");
|
|
145
|
+
return (await fs.readFile("/usr/bin/ldd", "utf8")).includes("musl");
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Whether `auto` may pick the native engine in this runtime. */
|
|
152
|
+
export function nativeAutoAllowed(process) {
|
|
153
|
+
// Deno runs Node-API addons only with `--allow-ffi`, and would prompt for
|
|
154
|
+
// it: there `backend: "native"` asks for it explicitly.
|
|
155
|
+
return process.versions["deno"] === undefined;
|
|
156
|
+
}
|
|
157
|
+
let availability;
|
|
158
|
+
/**
|
|
159
|
+
* Loads the addon once per thread: `WEBSLM_NATIVE_PATH` (a `.node` file, for
|
|
160
|
+
* local builds) when set, else the release asset of this platform and
|
|
161
|
+
* version, from `<cacheDir>/native/<version>/` or downloaded there first and
|
|
162
|
+
* checked against `native-manifest.json` (see {@link fetchNativeAddon}).
|
|
163
|
+
* Resolves with the reason when it cannot be used.
|
|
164
|
+
*/
|
|
165
|
+
export function loadNativeAddon(cacheDir) {
|
|
166
|
+
availability ??= (async () => {
|
|
167
|
+
const process = nodeProcess();
|
|
168
|
+
if (process === undefined)
|
|
169
|
+
return { reason: "the native engine runs in Node only" };
|
|
170
|
+
const { createRequire } = await importNode("module");
|
|
171
|
+
const base = import.meta.url;
|
|
172
|
+
const loadModule = createRequire(base);
|
|
173
|
+
const version = packageVersion(loadModule);
|
|
174
|
+
const explicit = process.env["WEBSLM_NATIVE_PATH"]?.trim();
|
|
175
|
+
let source;
|
|
176
|
+
if (explicit !== undefined && explicit !== "") {
|
|
177
|
+
source = explicit;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const platform = nativePlatform({
|
|
181
|
+
platform: process.platform,
|
|
182
|
+
arch: process.arch,
|
|
183
|
+
...(process.platform === "linux" ? { musl: await isMusl(process) } : {}),
|
|
184
|
+
});
|
|
185
|
+
if (platform === undefined)
|
|
186
|
+
return { reason: `no native build for ${process.platform}-${process.arch}` };
|
|
187
|
+
if (version === undefined)
|
|
188
|
+
return { reason: "the version of webslm is unknown" };
|
|
189
|
+
const { defaultCacheDir } = await import("./cache/node-fs.js");
|
|
190
|
+
const { offlineMode } = await import("./hub.js");
|
|
191
|
+
const baseUrl = process.env["WEBSLM_NATIVE_URL"]?.trim();
|
|
192
|
+
try {
|
|
193
|
+
source = await fetchNativeAddon({
|
|
194
|
+
platform,
|
|
195
|
+
version,
|
|
196
|
+
manifest: readManifest(loadModule),
|
|
197
|
+
cacheDir: cacheDir ?? (await defaultCacheDir()),
|
|
198
|
+
offline: offlineMode(),
|
|
199
|
+
...(baseUrl === undefined || baseUrl === "" ? {} : { baseUrl }),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
return { reason: error instanceof Error ? error.message : String(error) };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
let addon;
|
|
207
|
+
try {
|
|
208
|
+
addon = loadModule(source);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
|
|
212
|
+
return { reason: `${source} does not load (${message})` };
|
|
213
|
+
}
|
|
214
|
+
const actual = addon.version();
|
|
215
|
+
if (version !== undefined && actual !== version) {
|
|
216
|
+
return { reason: `${source} is version ${actual}, webslm is ${version}` };
|
|
217
|
+
}
|
|
218
|
+
return { addon, source };
|
|
219
|
+
})();
|
|
220
|
+
return availability;
|
|
221
|
+
}
|
|
222
|
+
/** The version of this package, from its `package.json`. */
|
|
223
|
+
function packageVersion(loadModule) {
|
|
224
|
+
try {
|
|
225
|
+
return loadModule("../package.json").version;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** The package's `native-manifest.json`, when it has one (the published package does). */
|
|
232
|
+
function readManifest(loadModule) {
|
|
233
|
+
try {
|
|
234
|
+
return loadModule("../native-manifest.json");
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** @internal Forgets the loaded addon (tests). */
|
|
241
|
+
export function resetNativeAddon() {
|
|
242
|
+
availability = undefined;
|
|
243
|
+
}
|