webslm 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -15
- package/dist/ai-sdk/index.d.ts +1 -1
- package/dist/ai-sdk/index.js +1 -1
- package/dist/cache/models.d.ts +6 -0
- package/dist/cache/models.js +11 -0
- package/dist/curated.d.ts +31 -1
- package/dist/curated.js +49 -5
- package/dist/engine.d.ts +33 -4
- package/dist/engine.js +451 -43
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/models.d.ts +30 -9
- package/dist/models.js +72 -10
- package/dist/native.d.ts +165 -0
- package/dist/native.js +243 -0
- package/dist/protocol.d.ts +14 -3
- package/dist/recommended-sampling.d.ts +54 -0
- package/dist/recommended-sampling.js +73 -0
- package/dist/simple.d.ts +20 -6
- package/dist/simple.js +33 -7
- package/dist/types.d.ts +106 -20
- package/native-manifest.json +47 -0
- package/package.json +2 -1
- package/wasm/relaxed/webslm_wasm.d.ts +34 -9
- package/wasm/relaxed/webslm_wasm.js +78 -22
- 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 +34 -9
- package/wasm/simd/webslm_wasm.js +78 -22
- 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 +34 -9
- package/wasm/threads/webslm_wasm.js +83 -27
- 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, 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";
|
|
@@ -82,6 +88,15 @@ export declare function resolveAutoQuant(source: NormalizedSource, options: Load
|
|
|
82
88
|
quant: Quant;
|
|
83
89
|
note?: string;
|
|
84
90
|
}>;
|
|
91
|
+
/**
|
|
92
|
+
* `options` with the sampling fields it leaves unset taken from the model
|
|
93
|
+
* card of a curated repository ({@link recommendedSampling}), for the
|
|
94
|
+
* thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
|
|
95
|
+
* other repositories, and with `temperature: 0` (greedy decoding).
|
|
96
|
+
*
|
|
97
|
+
* @internal
|
|
98
|
+
*/
|
|
99
|
+
export declare function withRecommendedSampling<T extends GenerateOptions>(options: T, checkpoint: string | CheckpointTraits | undefined): T;
|
|
85
100
|
/** Operations shared by {@link Model} (its default session) and {@link Session}. */
|
|
86
101
|
declare abstract class Conversation {
|
|
87
102
|
#private;
|
|
@@ -89,6 +104,8 @@ declare abstract class Conversation {
|
|
|
89
104
|
protected readonly modelId: number;
|
|
90
105
|
protected abstract readonly sessionId: number | undefined;
|
|
91
106
|
protected abstract readonly hasChatTemplate: boolean;
|
|
107
|
+
/** What picks the model's recommended sampling. */
|
|
108
|
+
protected abstract readonly checkpoint: CheckpointTraits;
|
|
92
109
|
protected abstract onLength(length: number): void;
|
|
93
110
|
constructor(client: EngineClient, modelId: number);
|
|
94
111
|
/**
|
|
@@ -133,17 +150,20 @@ export declare class Model extends Conversation {
|
|
|
133
150
|
readonly cacheDir?: string;
|
|
134
151
|
}, ownsEngine?: boolean);
|
|
135
152
|
protected get hasChatTemplate(): boolean;
|
|
153
|
+
protected get checkpoint(): CheckpointTraits;
|
|
136
154
|
protected onLength(): void;
|
|
137
155
|
/** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
|
|
138
156
|
info(): ModelInfo;
|
|
139
157
|
/** Clears the default session's cache. */
|
|
140
158
|
reset(): Promise<void>;
|
|
141
159
|
/**
|
|
142
|
-
*
|
|
143
|
-
* `adapter_model.safetensors`, as published on the Hub)
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
160
|
+
* Applies a PEFT LoRA adapter (`adapter_config.json` and
|
|
161
|
+
* `adapter_model.safetensors`, as published on the Hub), replacing the
|
|
162
|
+
* adapter applied before, if any, in the model's `adapterMode` (see
|
|
163
|
+
* {@link AdapterMode}): unmerged (the default), its small f32 factors are
|
|
164
|
+
* uploaded beside the weights; merged, the affected base matrices are
|
|
165
|
+
* read again from the model's source and merged in f32 before
|
|
166
|
+
* quantization.
|
|
147
167
|
*
|
|
148
168
|
* Rejects with `INVALID_ADAPTER`, leaving the model unchanged, when the
|
|
149
169
|
* adapter does not fit the model (a module it does not have, other
|
|
@@ -183,6 +203,7 @@ export declare class Session extends Conversation {
|
|
|
183
203
|
/** @internal */
|
|
184
204
|
constructor(client: EngineClient, modelId: number, sessionId: number, info: ModelInfo, onDispose: () => void);
|
|
185
205
|
protected get hasChatTemplate(): boolean;
|
|
206
|
+
protected get checkpoint(): CheckpointTraits;
|
|
186
207
|
protected onLength(length: number): void;
|
|
187
208
|
/** Positions in the cache (as of the last completed call). */
|
|
188
209
|
get length(): number;
|
package/dist/models.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
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";
|
|
7
8
|
import { isNode } from "./runtime.js";
|
|
8
9
|
const QUANTS = ["q8", "q4", "f32"];
|
|
10
|
+
const ADAPTER_MODES = ["unmerged", "merged"];
|
|
9
11
|
/**
|
|
10
12
|
* An engine (a worker, or the calling thread) that several models can share
|
|
11
13
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -43,9 +45,9 @@ export async function createEngine(options = {}) {
|
|
|
43
45
|
}
|
|
44
46
|
/**
|
|
45
47
|
* Validates `device` (default `"auto"`). The engine decides what actually
|
|
46
|
-
* runs: `"auto"` is
|
|
47
|
-
* is available, the CPU otherwise; `"webgpu"`
|
|
48
|
-
* {@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}).
|
|
49
51
|
*/
|
|
50
52
|
export function resolveDevice(device) {
|
|
51
53
|
switch (device ?? "auto") {
|
|
@@ -53,12 +55,28 @@ export function resolveDevice(device) {
|
|
|
53
55
|
return "auto";
|
|
54
56
|
case "cpu":
|
|
55
57
|
return "cpu";
|
|
58
|
+
case "gpu":
|
|
59
|
+
return "gpu";
|
|
56
60
|
case "webgpu":
|
|
57
61
|
return "webgpu";
|
|
58
62
|
default:
|
|
59
63
|
throw new WebslmError("INVALID_ARGUMENT", `unknown device "${String(device)}"`);
|
|
60
64
|
}
|
|
61
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
|
+
}
|
|
62
80
|
/** Checks a source and turns a repository id string into a hub source. */
|
|
63
81
|
export function normalizeSource(source, revision) {
|
|
64
82
|
if (typeof source === "string") {
|
|
@@ -173,6 +191,7 @@ function requestPersistentStorage() {
|
|
|
173
191
|
*/
|
|
174
192
|
export async function loadModel(source, options = {}) {
|
|
175
193
|
const device = resolveDevice(options.device);
|
|
194
|
+
const backend = resolveBackend(options.backend);
|
|
176
195
|
const requested = options.quant ?? "q8";
|
|
177
196
|
if (requested !== "auto" && !QUANTS.includes(requested)) {
|
|
178
197
|
throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
|
|
@@ -180,6 +199,9 @@ export async function loadModel(source, options = {}) {
|
|
|
180
199
|
const normalized = normalizeSource(source, options.revision);
|
|
181
200
|
const adapter = options.adapter === undefined ? undefined : normalizeAdapterSource(options.adapter);
|
|
182
201
|
checkScale(options.adapterScale);
|
|
202
|
+
if (options.adapterMode !== undefined && !ADAPTER_MODES.includes(options.adapterMode)) {
|
|
203
|
+
throw new WebslmError("INVALID_ARGUMENT", `adapterMode must be one of ${ADAPTER_MODES.join(", ")}`);
|
|
204
|
+
}
|
|
183
205
|
if (isAborted(options.signal))
|
|
184
206
|
throw abortError(options.signal);
|
|
185
207
|
if (normalized.kind === "hub" && !isNode())
|
|
@@ -198,10 +220,14 @@ export async function loadModel(source, options = {}) {
|
|
|
198
220
|
...(adapter === undefined ? {} : { adapter: toWire(adapter, options.token) }),
|
|
199
221
|
options: {
|
|
200
222
|
quant,
|
|
223
|
+
...(requested === "auto" ? { autoQuant: true } : {}),
|
|
201
224
|
device,
|
|
225
|
+
...(backend === "auto" ? {} : { backend }),
|
|
202
226
|
...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
|
|
227
|
+
...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
|
|
203
228
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
204
229
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
230
|
+
...(options.weightCache === false ? { weightCache: false } : {}),
|
|
205
231
|
...(options.deterministic === true ? { deterministic: true } : {}),
|
|
206
232
|
...(options.activations === undefined ? {} : { activations: options.activations }),
|
|
207
233
|
...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
|
|
@@ -213,7 +239,9 @@ export async function loadModel(source, options = {}) {
|
|
|
213
239
|
...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
|
|
214
240
|
...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
|
|
215
241
|
});
|
|
216
|
-
|
|
242
|
+
// The native engine chose the format again, from the machine's memory
|
|
243
|
+
// (its own note says why when it did not load q8).
|
|
244
|
+
const info = quantNote === undefined || result.info.runtime === "native" ? result.info : { ...result.info, quantNote };
|
|
217
245
|
return new Model(client, result.model, info, {
|
|
218
246
|
...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
|
|
219
247
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
@@ -327,6 +355,32 @@ function wireOptions(options) {
|
|
|
327
355
|
out.contextShift = options.contextShift;
|
|
328
356
|
return out;
|
|
329
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* `options` with the sampling fields it leaves unset taken from the model
|
|
360
|
+
* card of a curated repository ({@link recommendedSampling}), for the
|
|
361
|
+
* thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
|
|
362
|
+
* other repositories, and with `temperature: 0` (greedy decoding).
|
|
363
|
+
*
|
|
364
|
+
* @internal
|
|
365
|
+
*/
|
|
366
|
+
export function withRecommendedSampling(options, checkpoint) {
|
|
367
|
+
if (options.temperature === 0)
|
|
368
|
+
return options;
|
|
369
|
+
const think = options.templateKwargs?.["enable_thinking"];
|
|
370
|
+
const recommended = recommendedSampling(checkpoint, typeof think === "boolean" ? think : undefined);
|
|
371
|
+
if (recommended === undefined)
|
|
372
|
+
return options;
|
|
373
|
+
const out = { ...options };
|
|
374
|
+
for (const key of Object.keys(recommended)) {
|
|
375
|
+
if (out[key] === undefined)
|
|
376
|
+
out[key] = recommended[key];
|
|
377
|
+
}
|
|
378
|
+
return out;
|
|
379
|
+
}
|
|
380
|
+
/** What picks a loaded model's recommended sampling. */
|
|
381
|
+
function checkpointTraits(info) {
|
|
382
|
+
return { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
|
|
383
|
+
}
|
|
330
384
|
/** A `delta` message as a {@link GeneratedToken}. */
|
|
331
385
|
function generatedToken(delta) {
|
|
332
386
|
return {
|
|
@@ -459,7 +513,7 @@ class Conversation {
|
|
|
459
513
|
return text;
|
|
460
514
|
}
|
|
461
515
|
#stream(body, generateOptions) {
|
|
462
|
-
const options = wireOptions(generateOptions);
|
|
516
|
+
const options = wireOptions(withRecommendedSampling(generateOptions, this.checkpoint));
|
|
463
517
|
const { onPrefill } = generateOptions;
|
|
464
518
|
const session = this.sessionId === undefined ? {} : { session: this.sessionId };
|
|
465
519
|
// Stopping aborts the request; the engine then ends the generation
|
|
@@ -529,6 +583,9 @@ export class Model extends Conversation {
|
|
|
529
583
|
get hasChatTemplate() {
|
|
530
584
|
return this.#info.hasChatTemplate;
|
|
531
585
|
}
|
|
586
|
+
get checkpoint() {
|
|
587
|
+
return checkpointTraits(this.#info);
|
|
588
|
+
}
|
|
532
589
|
onLength() { }
|
|
533
590
|
/** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
|
|
534
591
|
info() {
|
|
@@ -539,11 +596,13 @@ export class Model extends Conversation {
|
|
|
539
596
|
await this.client.request({ type: "reset", model: this.modelId });
|
|
540
597
|
}
|
|
541
598
|
/**
|
|
542
|
-
*
|
|
543
|
-
* `adapter_model.safetensors`, as published on the Hub)
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
599
|
+
* Applies a PEFT LoRA adapter (`adapter_config.json` and
|
|
600
|
+
* `adapter_model.safetensors`, as published on the Hub), replacing the
|
|
601
|
+
* adapter applied before, if any, in the model's `adapterMode` (see
|
|
602
|
+
* {@link AdapterMode}): unmerged (the default), its small f32 factors are
|
|
603
|
+
* uploaded beside the weights; merged, the affected base matrices are
|
|
604
|
+
* read again from the model's source and merged in f32 before
|
|
605
|
+
* quantization.
|
|
547
606
|
*
|
|
548
607
|
* Rejects with `INVALID_ADAPTER`, leaving the model unchanged, when the
|
|
549
608
|
* adapter does not fit the model (a module it does not have, other
|
|
@@ -635,6 +694,9 @@ export class Session extends Conversation {
|
|
|
635
694
|
get hasChatTemplate() {
|
|
636
695
|
return this.#info.hasChatTemplate;
|
|
637
696
|
}
|
|
697
|
+
get checkpoint() {
|
|
698
|
+
return checkpointTraits(this.#info);
|
|
699
|
+
}
|
|
638
700
|
onLength(length) {
|
|
639
701
|
this.#length = length;
|
|
640
702
|
}
|
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;
|