webslm 0.6.0 → 0.9.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 +86 -3
- package/dist/ai-sdk/embedding-model.d.ts +52 -0
- package/dist/ai-sdk/embedding-model.js +112 -0
- package/dist/ai-sdk/image-model.d.ts +53 -0
- package/dist/ai-sdk/image-model.js +148 -0
- package/dist/ai-sdk/index.d.ts +39 -0
- package/dist/ai-sdk/index.js +66 -11
- package/dist/client.d.ts +6 -0
- package/dist/client.js +8 -1
- package/dist/download.js +2 -2
- package/dist/engine.js +187 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +1 -0
- package/dist/fit.d.ts +2 -2
- package/dist/fit.js +5 -2
- package/dist/hub.d.ts +38 -3
- package/dist/hub.js +87 -8
- package/dist/image.d.ts +201 -0
- package/dist/image.js +353 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +5 -3
- package/dist/memory.d.ts +24 -7
- package/dist/memory.js +49 -11
- package/dist/models.d.ts +19 -1
- package/dist/models.js +64 -7
- package/dist/native.d.ts +28 -0
- package/dist/protocol.d.ts +79 -2
- package/dist/simple.d.ts +4 -1
- package/dist/simple.js +9 -2
- package/dist/types.d.ts +87 -0
- package/dist/wasm.d.ts +2 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +72 -7
- package/wasm/relaxed/webslm_wasm.js +165 -19
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +10 -3
- package/wasm/simd/webslm_wasm.d.ts +72 -7
- package/wasm/simd/webslm_wasm.js +165 -19
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +10 -3
- package/wasm/threads/webslm_wasm.d.ts +73 -8
- package/wasm/threads/webslm_wasm.js +171 -25
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +11 -4
package/dist/models.js
CHANGED
|
@@ -139,8 +139,8 @@ export function normalizeSource(source, revision) {
|
|
|
139
139
|
if (file !== undefined && !(file in files)) {
|
|
140
140
|
throw new WebslmError("INVALID_ARGUMENT", `\`files\` has no "${file}"`);
|
|
141
141
|
}
|
|
142
|
-
// A GGUF file carries its configuration.
|
|
143
|
-
if (!("config.json" in files) && !Object.keys(files).some(isGgufFile)) {
|
|
142
|
+
// A GGUF file carries its configuration; a text-to-image pipeline has a model_index.json.
|
|
143
|
+
if (!("config.json" in files) && !("model_index.json" in files) && !Object.keys(files).some(isGgufFile)) {
|
|
144
144
|
throw new WebslmError("INVALID_ARGUMENT", "`files` must include config.json or a .gguf file");
|
|
145
145
|
}
|
|
146
146
|
return { kind: "files", files, ...withFile };
|
|
@@ -170,8 +170,8 @@ export function normalizeAdapterSource(source, revision) {
|
|
|
170
170
|
}
|
|
171
171
|
return normalizeSource(source, revision);
|
|
172
172
|
}
|
|
173
|
-
/** The form of a normalized source posted to the engine. */
|
|
174
|
-
function toWire(normalized, token) {
|
|
173
|
+
/** @internal The form of a normalized source posted to the engine. */
|
|
174
|
+
export function toWire(normalized, token) {
|
|
175
175
|
switch (normalized.kind) {
|
|
176
176
|
case "hub":
|
|
177
177
|
return {
|
|
@@ -193,6 +193,20 @@ function checkScale(scale) {
|
|
|
193
193
|
throw new WebslmError("INVALID_ARGUMENT", "the adapter scale must be a finite number");
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
|
+
const KV_CACHE_TYPES = ["f32", "int8"];
|
|
197
|
+
/** Smallest `kvBudget` (`MIN_KV_BUDGET` in Rust). */
|
|
198
|
+
const MIN_KV_BUDGET = 16;
|
|
199
|
+
function checkKvOptions(options) {
|
|
200
|
+
if (options.kvCache !== undefined && !KV_CACHE_TYPES.includes(options.kvCache)) {
|
|
201
|
+
throw new WebslmError("INVALID_ARGUMENT", `kvCache must be one of ${KV_CACHE_TYPES.join(", ")}`);
|
|
202
|
+
}
|
|
203
|
+
if (options.kvResidual !== undefined && !(Number.isInteger(options.kvResidual) && options.kvResidual >= 0)) {
|
|
204
|
+
throw new WebslmError("INVALID_ARGUMENT", "kvResidual must be a non-negative integer");
|
|
205
|
+
}
|
|
206
|
+
if (options.kvBudget !== undefined && !(Number.isInteger(options.kvBudget) && options.kvBudget >= MIN_KV_BUDGET)) {
|
|
207
|
+
throw new WebslmError("INVALID_ARGUMENT", `kvBudget must be an integer of at least ${MIN_KV_BUDGET}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
196
210
|
let persistRequested = false;
|
|
197
211
|
/** Asks the browser to keep the cache under storage pressure (once per page). */
|
|
198
212
|
function requestPersistentStorage() {
|
|
@@ -232,6 +246,7 @@ export async function loadModel(source, options = {}) {
|
|
|
232
246
|
if (options.adapterMode !== undefined && !ADAPTER_MODES.includes(options.adapterMode)) {
|
|
233
247
|
throw new WebslmError("INVALID_ARGUMENT", `adapterMode must be one of ${ADAPTER_MODES.join(", ")}`);
|
|
234
248
|
}
|
|
249
|
+
checkKvOptions(options);
|
|
235
250
|
if (isAborted(options.signal))
|
|
236
251
|
throw abortError(options.signal);
|
|
237
252
|
if (normalized.kind === "hub" && !isNode())
|
|
@@ -256,11 +271,15 @@ export async function loadModel(source, options = {}) {
|
|
|
256
271
|
options: {
|
|
257
272
|
quant,
|
|
258
273
|
...(requested === "auto" ? { autoQuant: true } : {}),
|
|
274
|
+
...(options.quant === undefined ? { defaultQuant: true } : {}),
|
|
259
275
|
device,
|
|
260
276
|
...(backend === "auto" ? {} : { backend }),
|
|
261
277
|
...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
|
|
262
278
|
...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
|
|
263
279
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
280
|
+
...(options.kvCache === undefined ? {} : { kvCache: options.kvCache }),
|
|
281
|
+
...(options.kvResidual === undefined ? {} : { kvResidual: options.kvResidual }),
|
|
282
|
+
...(options.kvBudget === undefined ? {} : { kvBudget: options.kvBudget }),
|
|
264
283
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
265
284
|
...(options.weightCache === false ? { weightCache: false } : {}),
|
|
266
285
|
...(options.deterministic === true ? { deterministic: true } : {}),
|
|
@@ -276,8 +295,11 @@ export async function loadModel(source, options = {}) {
|
|
|
276
295
|
...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
|
|
277
296
|
});
|
|
278
297
|
// The native engine chose the format again, from the machine's memory
|
|
279
|
-
// (its own note says why when it did not load q8)
|
|
280
|
-
|
|
298
|
+
// (its own note says why when it did not load q8); an encoder loads in
|
|
299
|
+
// f32 under `auto`.
|
|
300
|
+
const info = quantNote === undefined || result.info.runtime === "native" || result.info.embedding !== undefined
|
|
301
|
+
? result.info
|
|
302
|
+
: { ...result.info, quantNote };
|
|
281
303
|
return new Model(client, result.model, info, {
|
|
282
304
|
...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
|
|
283
305
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
@@ -316,7 +338,7 @@ export async function resolveAutoQuant(source, options) {
|
|
|
316
338
|
else {
|
|
317
339
|
shapes = await readCheckpointShapes(checkpointReader(source));
|
|
318
340
|
}
|
|
319
|
-
return autoQuant(shapes, resources, options.contextLength, options.vision);
|
|
341
|
+
return autoQuant(shapes, resources, options.contextLength, options.vision, options);
|
|
320
342
|
}
|
|
321
343
|
catch (error) {
|
|
322
344
|
if (isAborted(options.signal))
|
|
@@ -731,6 +753,41 @@ export class Model extends Conversation {
|
|
|
731
753
|
this.#info = info;
|
|
732
754
|
return removed ?? undefined;
|
|
733
755
|
}
|
|
756
|
+
/**
|
|
757
|
+
* Embeds texts with an encoder (an embedding model: BERT, ModernBERT,
|
|
758
|
+
* model2vec; see {@link ModelInfo.embedding}): one vector per text,
|
|
759
|
+
* pooled and normalized as the checkpoint's sentence-transformers
|
|
760
|
+
* settings say unless `options` say otherwise. Texts longer than the
|
|
761
|
+
* model's limit are cut. Rejects with `UNSUPPORTED_TASK` on a language
|
|
762
|
+
* model.
|
|
763
|
+
*
|
|
764
|
+
* ```ts
|
|
765
|
+
* const model = await loadModel("sentence-transformers/all-MiniLM-L6-v2");
|
|
766
|
+
* const { vectors } = await model.embed(["A cat sleeps.", "A kitten naps."]);
|
|
767
|
+
* const cosine = vectors[0].reduce((s, v, i) => s + v * vectors[1][i], 0);
|
|
768
|
+
* ```
|
|
769
|
+
*/
|
|
770
|
+
async embed(texts, options = {}) {
|
|
771
|
+
const list = typeof texts === "string" ? [texts] : [...texts];
|
|
772
|
+
if (list.some((t) => typeof t !== "string")) {
|
|
773
|
+
throw new WebslmError("INVALID_ARGUMENT", "embed takes a string or an array of strings");
|
|
774
|
+
}
|
|
775
|
+
if (this.#info.embedding === undefined) {
|
|
776
|
+
throw new WebslmError("UNSUPPORTED_TASK", `${this.#info.repo ?? this.#info.modelType} is a language model; embed needs an embedding model`);
|
|
777
|
+
}
|
|
778
|
+
const result = await this.client.request({
|
|
779
|
+
type: "embed",
|
|
780
|
+
model: this.modelId,
|
|
781
|
+
texts: list,
|
|
782
|
+
options: {
|
|
783
|
+
...(options.pooling === undefined ? {} : { pooling: options.pooling }),
|
|
784
|
+
...(options.normalize === undefined ? {} : { normalize: options.normalize }),
|
|
785
|
+
},
|
|
786
|
+
}, options.signal === undefined ? {} : { signal: options.signal });
|
|
787
|
+
const { data, dimensions } = result;
|
|
788
|
+
const vectors = list.map((_, i) => data.subarray(i * dimensions, (i + 1) * dimensions));
|
|
789
|
+
return { vectors, data, dimensions, tokens: Array.from(result.tokens) };
|
|
790
|
+
}
|
|
734
791
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
735
792
|
async session() {
|
|
736
793
|
const id = await this.client.request({ type: "createSession", model: this.modelId });
|
package/dist/native.d.ts
CHANGED
|
@@ -56,6 +56,23 @@ export interface NativeLoadArgs {
|
|
|
56
56
|
readonly threads?: number;
|
|
57
57
|
}
|
|
58
58
|
/** A model loaded by the native engine. */
|
|
59
|
+
/** Settings of an image model load that only the native engine has. */
|
|
60
|
+
export interface NativeImageLoadArgs {
|
|
61
|
+
/** Directory of a standalone autoencoder replacing the pipeline's decoder. */
|
|
62
|
+
readonly decoderDir?: string;
|
|
63
|
+
readonly threads?: number;
|
|
64
|
+
}
|
|
65
|
+
/** A text-to-image pipeline on the native engine. */
|
|
66
|
+
export interface NativeImageModel {
|
|
67
|
+
info(): Record<string, unknown>;
|
|
68
|
+
generate(prompt: string, optionsJson: string, onProgress?: ((phase: string, step: number, steps: number) => void) | null, cancel?: NativeCancelToken | null): Promise<{
|
|
69
|
+
width: number;
|
|
70
|
+
height: number;
|
|
71
|
+
seed: number;
|
|
72
|
+
rgba: Uint8Array;
|
|
73
|
+
}>;
|
|
74
|
+
free(): void;
|
|
75
|
+
}
|
|
59
76
|
export interface NativeModel {
|
|
60
77
|
info(): NativeModelInfo;
|
|
61
78
|
applyAdapter(dir: string, optionsJson: string): Promise<unknown>;
|
|
@@ -68,12 +85,19 @@ export interface NativeModel {
|
|
|
68
85
|
tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
|
|
69
86
|
detokenize(ids: Uint32Array, skipSpecialTokens: boolean): Promise<string>;
|
|
70
87
|
renderChat(messagesJson: string, kwargsJson: string): Promise<string>;
|
|
88
|
+
/** Encoders only (`UNSUPPORTED_TASK` otherwise). */
|
|
89
|
+
embed(textsJson: string, optionsJson: string): Promise<{
|
|
90
|
+
data: Float32Array;
|
|
91
|
+
dimensions: number;
|
|
92
|
+
tokens: Uint32Array;
|
|
93
|
+
}>;
|
|
71
94
|
free(): void;
|
|
72
95
|
}
|
|
73
96
|
/** The exports of the addon. */
|
|
74
97
|
export interface NativeAddon {
|
|
75
98
|
version(): string;
|
|
76
99
|
supportedModelTypes(): string[];
|
|
100
|
+
supportedEncoderTypes(): string[];
|
|
77
101
|
buildInfo(): {
|
|
78
102
|
version: string;
|
|
79
103
|
target: string;
|
|
@@ -83,6 +107,10 @@ export interface NativeAddon {
|
|
|
83
107
|
readonly NativeModel: {
|
|
84
108
|
load(dir: string, optionsJson: string, args?: NativeLoadArgs | null): Promise<NativeModel>;
|
|
85
109
|
};
|
|
110
|
+
/** Absent from addons older than text-to-image support. */
|
|
111
|
+
readonly NativeImageModel?: {
|
|
112
|
+
load(dir: string, optionsJson: string, args?: NativeImageLoadArgs | null): Promise<NativeImageModel>;
|
|
113
|
+
};
|
|
86
114
|
readonly CancelToken: new () => NativeCancelToken;
|
|
87
115
|
}
|
|
88
116
|
/** Where the addon came from, or why it could not load. */
|
package/dist/protocol.d.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { SerializedError } from "./errors.js";
|
|
9
9
|
import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
|
|
10
|
+
import type { ImageModelInfo, ImagePhase, ImageQuant } from "./image.js";
|
|
11
|
+
import type { KvCacheType } from "./memory.js";
|
|
10
12
|
import type { WasmFlavour } from "./wasm-flavour.js";
|
|
11
13
|
/** A model source in a form that can be posted to a worker. */
|
|
12
14
|
export type WireSource = {
|
|
@@ -35,11 +37,19 @@ export interface WireLoadOptions {
|
|
|
35
37
|
* machine's memory and GPU.
|
|
36
38
|
*/
|
|
37
39
|
readonly autoQuant?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* `quant` is the default, not the caller's choice: an encoder then loads
|
|
42
|
+
* in f32 (small models, embeddings compared across texts).
|
|
43
|
+
*/
|
|
44
|
+
readonly defaultQuant?: boolean;
|
|
38
45
|
/** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`; the engine reports what it used. */
|
|
39
46
|
readonly device?: string;
|
|
40
47
|
/** `"auto"` (default), `"native"` or `"wasm"`. */
|
|
41
48
|
readonly backend?: Backend;
|
|
42
49
|
readonly contextLength?: number;
|
|
50
|
+
readonly kvCache?: KvCacheType;
|
|
51
|
+
readonly kvResidual?: number;
|
|
52
|
+
readonly kvBudget?: number;
|
|
43
53
|
/** Scale of the adapter of a `load` request. */
|
|
44
54
|
readonly adapterScale?: number;
|
|
45
55
|
readonly adapterMode?: AdapterMode;
|
|
@@ -52,6 +62,25 @@ export interface WireLoadOptions {
|
|
|
52
62
|
readonly wasmFlavour?: WasmFlavour;
|
|
53
63
|
readonly threads?: number;
|
|
54
64
|
}
|
|
65
|
+
/** Load options of a text-to-image pipeline. */
|
|
66
|
+
export interface WireImageLoadOptions {
|
|
67
|
+
readonly quant: ImageQuant;
|
|
68
|
+
/** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`. */
|
|
69
|
+
readonly device?: string;
|
|
70
|
+
readonly backend?: Backend;
|
|
71
|
+
readonly cacheDir?: string;
|
|
72
|
+
readonly wasmFlavour?: WasmFlavour;
|
|
73
|
+
readonly threads?: number;
|
|
74
|
+
}
|
|
75
|
+
/** Image options as sent to the engine (no signal). */
|
|
76
|
+
export interface WireImageOptions {
|
|
77
|
+
readonly width?: number;
|
|
78
|
+
readonly height?: number;
|
|
79
|
+
readonly steps?: number;
|
|
80
|
+
readonly guidance?: number;
|
|
81
|
+
readonly seed?: number;
|
|
82
|
+
readonly negativePrompt?: string;
|
|
83
|
+
}
|
|
55
84
|
/** Generation options as sent to the engine (no signal). */
|
|
56
85
|
export interface WireGenerateOptions {
|
|
57
86
|
readonly maxTokens?: number;
|
|
@@ -205,6 +234,25 @@ export type Request = WithId<{
|
|
|
205
234
|
readonly model: number;
|
|
206
235
|
readonly messages: readonly WireMessage[];
|
|
207
236
|
readonly templateKwargs: Readonly<Record<string, unknown>>;
|
|
237
|
+
} | {
|
|
238
|
+
readonly type: "embed";
|
|
239
|
+
readonly model: number;
|
|
240
|
+
readonly texts: readonly string[];
|
|
241
|
+
readonly options: {
|
|
242
|
+
readonly pooling?: string;
|
|
243
|
+
readonly normalize?: boolean;
|
|
244
|
+
};
|
|
245
|
+
} | {
|
|
246
|
+
readonly type: "loadImage";
|
|
247
|
+
readonly source: WireSource;
|
|
248
|
+
/** A standalone autoencoder replacing the pipeline's decoder. */
|
|
249
|
+
readonly decoder?: WireSource;
|
|
250
|
+
readonly options: WireImageLoadOptions;
|
|
251
|
+
} | {
|
|
252
|
+
readonly type: "generateImage";
|
|
253
|
+
readonly model: number;
|
|
254
|
+
readonly prompt: string;
|
|
255
|
+
readonly options: WireImageOptions;
|
|
208
256
|
} | {
|
|
209
257
|
readonly type: "unload";
|
|
210
258
|
readonly model: number;
|
|
@@ -244,6 +292,12 @@ export type Response = {
|
|
|
244
292
|
readonly id: number;
|
|
245
293
|
readonly done: number;
|
|
246
294
|
readonly total: number;
|
|
295
|
+
} | {
|
|
296
|
+
readonly type: "imageProgress";
|
|
297
|
+
readonly id: number;
|
|
298
|
+
readonly phase: ImagePhase;
|
|
299
|
+
readonly step: number;
|
|
300
|
+
readonly steps: number;
|
|
247
301
|
} | {
|
|
248
302
|
readonly type: "read";
|
|
249
303
|
readonly id: number;
|
|
@@ -251,16 +305,39 @@ export type Response = {
|
|
|
251
305
|
readonly path: string;
|
|
252
306
|
readonly start?: number;
|
|
253
307
|
readonly end?: number;
|
|
254
|
-
/**
|
|
255
|
-
|
|
308
|
+
/**
|
|
309
|
+
* `"adapter"` for files of the LoRA adapter, `"decoder"` for those of
|
|
310
|
+
* an image model's standalone decoder, absent for the model's own.
|
|
311
|
+
*/
|
|
312
|
+
readonly target?: "adapter" | "decoder";
|
|
256
313
|
};
|
|
257
314
|
/** Value of an `applyAdapter` result (`removeAdapter` resolves to it or `null`). */
|
|
258
315
|
export type WireLoraResult = LoraInfo;
|
|
316
|
+
/** Value of an `embed` result. */
|
|
317
|
+
export interface WireEmbedResult {
|
|
318
|
+
readonly data: Float32Array;
|
|
319
|
+
readonly dimensions: number;
|
|
320
|
+
readonly tokens: Uint32Array;
|
|
321
|
+
}
|
|
259
322
|
/** Value of a `load` result. */
|
|
260
323
|
export interface LoadResult {
|
|
261
324
|
readonly model: number;
|
|
262
325
|
readonly info: ModelInfo;
|
|
263
326
|
}
|
|
327
|
+
/** Value of a `loadImage` result. */
|
|
328
|
+
export interface ImageLoadResult {
|
|
329
|
+
readonly model: number;
|
|
330
|
+
readonly info: ImageModelInfo;
|
|
331
|
+
}
|
|
332
|
+
/** Value of a `generateImage` result. */
|
|
333
|
+
export interface WireImageResult {
|
|
334
|
+
readonly width: number;
|
|
335
|
+
readonly height: number;
|
|
336
|
+
readonly seed: number;
|
|
337
|
+
/** Row-major 8-bit RGBA pixels. */
|
|
338
|
+
readonly rgba: Uint8Array;
|
|
339
|
+
readonly timeMs: number;
|
|
340
|
+
}
|
|
264
341
|
/** Value of a `chat` or `generate` result. */
|
|
265
342
|
export interface WireGenerationResult {
|
|
266
343
|
readonly text: string;
|
package/dist/simple.d.ts
CHANGED
|
@@ -329,5 +329,8 @@ export declare function ask(prompt: string, options?: SharedAskOptions): Promise
|
|
|
329
329
|
* ```
|
|
330
330
|
*/
|
|
331
331
|
export declare function stream(prompt: string, options?: SharedStreamOptions): TextStream;
|
|
332
|
-
/**
|
|
332
|
+
/**
|
|
333
|
+
* Unloads every model loaded by the module-level {@link ask} and
|
|
334
|
+
* {@link stream} (and by `generateImage`).
|
|
335
|
+
*/
|
|
333
336
|
export declare function unloadAll(): Promise<void>;
|
package/dist/simple.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { AsyncQueue } from "./async-queue.js";
|
|
7
7
|
import { recommendedSampling } from "./curated.js";
|
|
8
8
|
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
9
|
+
import { unloadImageModels } from "./image.js";
|
|
9
10
|
import { loadModel } from "./models.js";
|
|
10
11
|
/**
|
|
11
12
|
* The model {@link load}, {@link ask} and {@link stream} use when none is
|
|
@@ -580,9 +581,15 @@ export function stream(prompt, options = {}) {
|
|
|
580
581
|
await llm.runPrompt(context, prompt, rest);
|
|
581
582
|
}, rest);
|
|
582
583
|
}
|
|
583
|
-
/**
|
|
584
|
+
/**
|
|
585
|
+
* Unloads every model loaded by the module-level {@link ask} and
|
|
586
|
+
* {@link stream} (and by `generateImage`).
|
|
587
|
+
*/
|
|
584
588
|
export async function unloadAll() {
|
|
585
589
|
const pending = [...shared.values()];
|
|
586
590
|
shared.clear();
|
|
587
|
-
await Promise.all(
|
|
591
|
+
await Promise.all([
|
|
592
|
+
...pending.map((p) => p.then((llm) => llm.unload(), () => { })),
|
|
593
|
+
unloadImageModels(),
|
|
594
|
+
]);
|
|
588
595
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Public types of the webslm API. */
|
|
2
|
+
import type { KvCacheType } from "./memory.js";
|
|
2
3
|
import type { EngineHandle } from "./models.js";
|
|
3
4
|
import type { WasmFlavour } from "./wasm-flavour.js";
|
|
4
5
|
/**
|
|
@@ -177,6 +178,28 @@ export interface LoadModelOptions {
|
|
|
177
178
|
readonly token?: string;
|
|
178
179
|
/** Largest number of positions a session holds. Defaults to min(4096, model maximum). */
|
|
179
180
|
readonly contextLength?: number;
|
|
181
|
+
/**
|
|
182
|
+
* How full-attention layers store keys and values (default `"f32"`).
|
|
183
|
+
* `"int8"` quantizes them in the KIVI layout (keys per channel, values
|
|
184
|
+
* per token, the most recent {@link LoadModelOptions.kvResidual} positions
|
|
185
|
+
* kept in f32): about 3 times less memory at 4096 positions, on the CPU
|
|
186
|
+
* and WebGPU, at a small cost in accuracy. Sliding-window and recurrent
|
|
187
|
+
* layers keep their own small states. Encoders (embedding models) have
|
|
188
|
+
* no KV cache and ignore this and the other KV options.
|
|
189
|
+
*/
|
|
190
|
+
readonly kvCache?: KvCacheType;
|
|
191
|
+
/** Int8 KV cache: the most recent positions kept in f32 (default 128, rounded up to a multiple of 32). */
|
|
192
|
+
readonly kvResidual?: number;
|
|
193
|
+
/**
|
|
194
|
+
* Opt-in KV eviction: most positions a full-attention layer keeps (at
|
|
195
|
+
* least 16). Past it, the cache drops positions instead of growing: it
|
|
196
|
+
* keeps the first 4 (attention sinks), the most recent quarter of the
|
|
197
|
+
* budget, and the keys least similar to their head's mean key (KeyDiff),
|
|
198
|
+
* so generation goes on past the budget in bounded memory. Off by
|
|
199
|
+
* default; deterministic. Answers that need a detail from the middle of a
|
|
200
|
+
* long prompt may lose it.
|
|
201
|
+
*/
|
|
202
|
+
readonly kvBudget?: number;
|
|
180
203
|
/**
|
|
181
204
|
* A PEFT LoRA adapter applied at load, in {@link LoadModelOptions.adapterMode}.
|
|
182
205
|
* It can be swapped or removed later with {@link Model.applyAdapter} and
|
|
@@ -548,7 +571,64 @@ export interface WeightCacheInfo {
|
|
|
548
571
|
/** Bytes read from the cache, or stored in it. */
|
|
549
572
|
readonly bytes: number;
|
|
550
573
|
}
|
|
574
|
+
/** Memory of a loaded model ({@link ModelInfo.memory}), in bytes. */
|
|
575
|
+
export interface ModelMemory {
|
|
576
|
+
/** Weights in their stored formats. */
|
|
577
|
+
readonly weights: number;
|
|
578
|
+
/** KV caches and recurrent states of one session at {@link ModelMemory.contextLength} positions. */
|
|
579
|
+
readonly kvCache: number;
|
|
580
|
+
/** What one more position adds to the KV cache (0 once {@link LoadModelOptions.kvBudget} caps it). */
|
|
581
|
+
readonly kvPerToken: number;
|
|
582
|
+
/** How full-attention layers store keys and values ({@link LoadModelOptions.kvCache}). */
|
|
583
|
+
readonly kvCacheType: KvCacheType;
|
|
584
|
+
/** Positions an int8 KV cache keeps in f32. */
|
|
585
|
+
readonly kvResidual?: number;
|
|
586
|
+
/** The KV eviction budget ({@link LoadModelOptions.kvBudget}), when on. */
|
|
587
|
+
readonly kvBudget?: number;
|
|
588
|
+
/** Activations of a prefill batch. */
|
|
589
|
+
readonly scratch: number;
|
|
590
|
+
/** Weights, KV cache and scratch together. */
|
|
591
|
+
readonly total: number;
|
|
592
|
+
/** Positions {@link ModelMemory.kvCache} is sized for. */
|
|
593
|
+
readonly contextLength: number;
|
|
594
|
+
/** Bytes the device holds with good performance, when known. */
|
|
595
|
+
readonly deviceBudget?: number;
|
|
596
|
+
/** Largest single buffer the device allocates, when limited (KV caches are paged below it). */
|
|
597
|
+
readonly maxBuffer?: number;
|
|
598
|
+
}
|
|
551
599
|
/** Description of a loaded model. */
|
|
600
|
+
/** Pooling of the token vectors of a text into one embedding (sentence-transformers' modes). */
|
|
601
|
+
export type Pooling = "cls" | "mean" | "max" | "mean_sqrt_len_tokens" | "weightedmean" | "lasttoken";
|
|
602
|
+
/** The embeddings of an encoder, in {@link ModelInfo.embedding}. */
|
|
603
|
+
export interface EmbeddingInfo {
|
|
604
|
+
/** Length of an embedding. */
|
|
605
|
+
readonly dimensions: number;
|
|
606
|
+
/** Pooling modes, concatenated in this order (`1_Pooling/config.json`; mean for a plain checkpoint). */
|
|
607
|
+
readonly pooling: readonly Pooling[];
|
|
608
|
+
/** Whether vectors are L2-normalized (a `Normalize` module, or model2vec's `normalize`). */
|
|
609
|
+
readonly normalize: boolean;
|
|
610
|
+
/** Largest number of tokens read from a text; longer texts are cut. */
|
|
611
|
+
readonly maxLength?: number;
|
|
612
|
+
}
|
|
613
|
+
/** Options of {@link Model.embed}. */
|
|
614
|
+
export interface EmbedOptions {
|
|
615
|
+
/** Pooling instead of the model's (static models pool by mean only). */
|
|
616
|
+
readonly pooling?: Pooling;
|
|
617
|
+
/** L2-normalize the vectors, or not, instead of the model's setting. */
|
|
618
|
+
readonly normalize?: boolean;
|
|
619
|
+
readonly signal?: AbortSignal;
|
|
620
|
+
}
|
|
621
|
+
/** What {@link Model.embed} returns. */
|
|
622
|
+
export interface Embeddings {
|
|
623
|
+
/** One vector per text, in order (views on {@link Embeddings.data}). */
|
|
624
|
+
readonly vectors: readonly Float32Array[];
|
|
625
|
+
/** The vectors one after the other. */
|
|
626
|
+
readonly data: Float32Array;
|
|
627
|
+
/** Length of each vector. */
|
|
628
|
+
readonly dimensions: number;
|
|
629
|
+
/** Tokens read from each text (texts longer than the model's limit are cut). */
|
|
630
|
+
readonly tokens: readonly number[];
|
|
631
|
+
}
|
|
552
632
|
export interface ModelInfo {
|
|
553
633
|
/** Hub repository id, when loaded from the hub. */
|
|
554
634
|
readonly repo?: string;
|
|
@@ -597,6 +677,11 @@ export interface ModelInfo {
|
|
|
597
677
|
readonly images: boolean;
|
|
598
678
|
readonly videos: boolean;
|
|
599
679
|
};
|
|
680
|
+
/**
|
|
681
|
+
* What `embed` returns by default, for an encoder (an embedding model:
|
|
682
|
+
* BERT, ModernBERT, model2vec); absent for language models.
|
|
683
|
+
*/
|
|
684
|
+
readonly embedding?: EmbeddingInfo;
|
|
600
685
|
readonly stopTokens: readonly number[];
|
|
601
686
|
readonly tokenizer: {
|
|
602
687
|
readonly vocabSize: number;
|
|
@@ -609,6 +694,8 @@ export interface ModelInfo {
|
|
|
609
694
|
readonly fromCache: boolean;
|
|
610
695
|
/** What the load did with the converted-weight cache ({@link LoadModelOptions.weightCache}). */
|
|
611
696
|
readonly weightCache: WeightCacheInfo;
|
|
697
|
+
/** Memory of the model, estimated at load: weights, KV cache and scratch, against the device's limits. */
|
|
698
|
+
readonly memory: ModelMemory;
|
|
612
699
|
/** Milliseconds spent downloading and loading. */
|
|
613
700
|
readonly loadTimeMs: number;
|
|
614
701
|
}
|
package/dist/wasm.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface WasmExports {
|
|
|
11
11
|
version(): string;
|
|
12
12
|
/** `model_type` values the engine runs. */
|
|
13
13
|
supportedModelTypes(): string[];
|
|
14
|
+
/** `model_type` values of the encoders the engine embeds with. */
|
|
15
|
+
supportedEncoderTypes(): string[];
|
|
14
16
|
/** Parses a safetensors header (see `parseSafetensorsHeader`). */
|
|
15
17
|
parseSafetensorsHeader(bytes: Uint8Array): unknown;
|
|
16
18
|
/** Incremental SHA-256 (`finish()` returns the hex digest and resets). */
|
package/native-manifest.json
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.
|
|
2
|
+
"version": "0.9.0",
|
|
3
3
|
"assets": {
|
|
4
4
|
"darwin-arm64": {
|
|
5
|
-
"file": "webslm-node-0.
|
|
6
|
-
"size":
|
|
7
|
-
"sha256": "
|
|
8
|
-
"nodeSha256": "
|
|
5
|
+
"file": "webslm-node-0.9.0-darwin-arm64.node.gz",
|
|
6
|
+
"size": 5591852,
|
|
7
|
+
"sha256": "cea8e35516345ba1f80999eb22d3dd52cffc1efae0392a2329ac1bb4fab3df20",
|
|
8
|
+
"nodeSha256": "d7a753a468e097bf55488b3377e5c7988fd00174beafba171d0d98155bfb4f8b"
|
|
9
9
|
},
|
|
10
10
|
"darwin-x64": {
|
|
11
|
-
"file": "webslm-node-0.
|
|
12
|
-
"size":
|
|
13
|
-
"sha256": "
|
|
14
|
-
"nodeSha256": "
|
|
11
|
+
"file": "webslm-node-0.9.0-darwin-x64.node.gz",
|
|
12
|
+
"size": 5888899,
|
|
13
|
+
"sha256": "258e2d3682207281ad01e432d8d5cc67b4acde1a5135f94bfdecf9c0cc3addcb",
|
|
14
|
+
"nodeSha256": "d475186c607d38b94f16bf5b907c793052c4930eb8fb1da66fcaf4d56f4eaa95"
|
|
15
15
|
},
|
|
16
16
|
"linux-x64-gnu": {
|
|
17
|
-
"file": "webslm-node-0.
|
|
18
|
-
"size":
|
|
19
|
-
"sha256": "
|
|
20
|
-
"nodeSha256": "
|
|
17
|
+
"file": "webslm-node-0.9.0-linux-x64-gnu.node.gz",
|
|
18
|
+
"size": 5918558,
|
|
19
|
+
"sha256": "e54006e5b99eec6b6b5c3ad3151b17b2b1c5fec82bbc752b10ed3042c5ebc504",
|
|
20
|
+
"nodeSha256": "bc889da6b28d8b6a5c67e0f27afd35c83e5140577eabb6b9dfe507a16676cd6d"
|
|
21
21
|
},
|
|
22
22
|
"linux-arm64-gnu": {
|
|
23
|
-
"file": "webslm-node-0.
|
|
24
|
-
"size":
|
|
25
|
-
"sha256": "
|
|
26
|
-
"nodeSha256": "
|
|
23
|
+
"file": "webslm-node-0.9.0-linux-arm64-gnu.node.gz",
|
|
24
|
+
"size": 5558757,
|
|
25
|
+
"sha256": "a905db5284c04c1be6c2c19f4c13955a0886e34764512a0dbdfb7ee74afb5ef9",
|
|
26
|
+
"nodeSha256": "b139332668606acd944db2d70ece7f02a3e2810047bece5e0e828932aa40bbd6"
|
|
27
27
|
},
|
|
28
28
|
"linux-x64-musl": {
|
|
29
|
-
"file": "webslm-node-0.
|
|
30
|
-
"size":
|
|
31
|
-
"sha256": "
|
|
32
|
-
"nodeSha256": "
|
|
29
|
+
"file": "webslm-node-0.9.0-linux-x64-musl.node.gz",
|
|
30
|
+
"size": 6321849,
|
|
31
|
+
"sha256": "118396973e958c1ed99e8a248abff85d3543e6bc34b54585fb0bd97ccb86b9c6",
|
|
32
|
+
"nodeSha256": "d637858c3b43c2da944600bb781652ba3550d059f02a36407c529d237ea670e2"
|
|
33
33
|
},
|
|
34
34
|
"linux-arm64-musl": {
|
|
35
|
-
"file": "webslm-node-0.
|
|
36
|
-
"size":
|
|
37
|
-
"sha256": "
|
|
38
|
-
"nodeSha256": "
|
|
35
|
+
"file": "webslm-node-0.9.0-linux-arm64-musl.node.gz",
|
|
36
|
+
"size": 6087963,
|
|
37
|
+
"sha256": "362cb975bc640c7822f80a3bb4407bc6218b39513560b52e37533a968422ee4a",
|
|
38
|
+
"nodeSha256": "af0b29f7688457466ad47788ad870783252ef4035efb0ee9dd537a73ed817615"
|
|
39
39
|
},
|
|
40
40
|
"win32-x64-msvc": {
|
|
41
|
-
"file": "webslm-node-0.
|
|
42
|
-
"size":
|
|
43
|
-
"sha256": "
|
|
44
|
-
"nodeSha256": "
|
|
41
|
+
"file": "webslm-node-0.9.0-win32-x64-msvc.node.gz",
|
|
42
|
+
"size": 6407894,
|
|
43
|
+
"sha256": "d0b1860d23e77fcbab0d4646189ac2ee44c0f683f312469c11f3d7289cf825da",
|
|
44
|
+
"nodeSha256": "2cbb741f1704cf540e311d5c21730e98102c54f6fd720df1c919611e95060ada"
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webslm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
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",
|