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/image.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text-to-image models: {@link loadImageModel}, {@link ImageModel},
|
|
3
|
+
* {@link generateImage} and the {@link GeneratedImage} they return.
|
|
4
|
+
*
|
|
5
|
+
* They run `diffusers` pipelines (a `model_index.json` and its `unet/`,
|
|
6
|
+
* `text_encoder/`, `vae/`, `tokenizer/` and `scheduler/` folders) from their
|
|
7
|
+
* original checkpoints, on WebGPU when there is one (the native GPU in Node)
|
|
8
|
+
* and on the CPU otherwise.
|
|
9
|
+
*/
|
|
10
|
+
import { EngineClient } from "./client.js";
|
|
11
|
+
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
12
|
+
import { EngineHandle, normalizeSource, resolveBackend, resolveDevice, toWire } from "./models.js";
|
|
13
|
+
/**
|
|
14
|
+
* A one-step distilled Stable Diffusion model (SDXS, 512×512, a tiny
|
|
15
|
+
* autoencoder): what {@link generateImage} loads by default.
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_IMAGE_MODEL = "IDKiro/sdxs-512-dreamshaper";
|
|
18
|
+
const IMAGE_QUANTS = ["f16", "f32", "q8"];
|
|
19
|
+
/** A generated image: 8-bit RGBA pixels, row-major. */
|
|
20
|
+
export class GeneratedImage {
|
|
21
|
+
width;
|
|
22
|
+
height;
|
|
23
|
+
/** The seed it was generated with. */
|
|
24
|
+
seed;
|
|
25
|
+
/** `width * height * 4` bytes, as `ImageData` holds them. */
|
|
26
|
+
data;
|
|
27
|
+
/** Time the generation took, in milliseconds. */
|
|
28
|
+
timeMs;
|
|
29
|
+
/** @internal */
|
|
30
|
+
constructor(width, height, seed, data, timeMs = 0) {
|
|
31
|
+
if (data.length !== width * height * 4) {
|
|
32
|
+
throw new WebslmError("INVALID_ARGUMENT", `${data.length} bytes are not ${width}x${height} RGBA pixels`);
|
|
33
|
+
}
|
|
34
|
+
this.width = width;
|
|
35
|
+
this.height = height;
|
|
36
|
+
this.seed = seed;
|
|
37
|
+
this.data = data;
|
|
38
|
+
this.timeMs = timeMs;
|
|
39
|
+
}
|
|
40
|
+
/** The pixels as an `ImageData`, for `CanvasRenderingContext2D.putImageData`. */
|
|
41
|
+
toImageData() {
|
|
42
|
+
if (typeof ImageData === "undefined") {
|
|
43
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", "ImageData is not available here; use `data` or `toPng()`");
|
|
44
|
+
}
|
|
45
|
+
return new ImageData(this.data, this.width, this.height);
|
|
46
|
+
}
|
|
47
|
+
/** The image as an `ImageBitmap`, to draw on a canvas or transfer to a worker. */
|
|
48
|
+
toImageBitmap() {
|
|
49
|
+
if (typeof createImageBitmap === "undefined") {
|
|
50
|
+
return Promise.reject(new WebslmError("UNSUPPORTED_DEVICE", "createImageBitmap is not available here; use `data` or `toPng()`"));
|
|
51
|
+
}
|
|
52
|
+
return createImageBitmap(this.toImageData());
|
|
53
|
+
}
|
|
54
|
+
/** The image as a PNG file. */
|
|
55
|
+
toPng() {
|
|
56
|
+
return encodePng(this.width, this.height, this.data);
|
|
57
|
+
}
|
|
58
|
+
/** The image as a PNG `Blob`, e.g. for `URL.createObjectURL`. */
|
|
59
|
+
async toBlob() {
|
|
60
|
+
return new Blob([await this.toPng()], { type: "image/png" });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Largest seed: seeds are integers below 2^53. */
|
|
64
|
+
const MAX_SEED = Number.MAX_SAFE_INTEGER;
|
|
65
|
+
function randomSeed() {
|
|
66
|
+
const words = new Uint32Array(2);
|
|
67
|
+
globalThis.crypto.getRandomValues(words);
|
|
68
|
+
// 53 random bits.
|
|
69
|
+
return (words[0] >>> 11) * 2 ** 32 + words[1];
|
|
70
|
+
}
|
|
71
|
+
function checkPositiveInteger(name, value) {
|
|
72
|
+
if (value !== undefined && !(Number.isInteger(value) && value > 0)) {
|
|
73
|
+
throw new WebslmError("INVALID_ARGUMENT", `${name} must be a positive integer`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** The image options sent to the engine (a random seed when none is given). */
|
|
77
|
+
export function wireImageOptions(options) {
|
|
78
|
+
let { width, height } = options;
|
|
79
|
+
if (options.size !== undefined) {
|
|
80
|
+
if (width !== undefined || height !== undefined) {
|
|
81
|
+
throw new WebslmError("INVALID_ARGUMENT", "give either size or width and height");
|
|
82
|
+
}
|
|
83
|
+
if (typeof options.size === "number") {
|
|
84
|
+
width = options.size;
|
|
85
|
+
height = options.size;
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
const match = /^(\d+)x(\d+)$/.exec(String(options.size));
|
|
89
|
+
if (match === null)
|
|
90
|
+
throw new WebslmError("INVALID_ARGUMENT", 'size must be a number or "<width>x<height>"');
|
|
91
|
+
width = Number(match[1]);
|
|
92
|
+
height = Number(match[2]);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
checkPositiveInteger("width", width);
|
|
96
|
+
checkPositiveInteger("height", height);
|
|
97
|
+
checkPositiveInteger("steps", options.steps);
|
|
98
|
+
const { guidance } = options;
|
|
99
|
+
if (guidance !== undefined && !(Number.isFinite(guidance) && guidance >= 0)) {
|
|
100
|
+
throw new WebslmError("INVALID_ARGUMENT", "guidance must be a finite number of at least 0");
|
|
101
|
+
}
|
|
102
|
+
const seed = options.seed ?? randomSeed();
|
|
103
|
+
if (!(Number.isInteger(seed) && seed >= 0 && seed <= MAX_SEED)) {
|
|
104
|
+
throw new WebslmError("INVALID_ARGUMENT", "seed must be an integer from 0 to 2^53 - 1");
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
...(width === undefined ? {} : { width }),
|
|
108
|
+
...(height === undefined ? {} : { height }),
|
|
109
|
+
...(options.steps === undefined ? {} : { steps: options.steps }),
|
|
110
|
+
...(guidance === undefined ? {} : { guidance }),
|
|
111
|
+
seed,
|
|
112
|
+
...(options.negativePrompt === undefined ? {} : { negativePrompt: options.negativePrompt }),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** A loaded text-to-image pipeline. */
|
|
116
|
+
export class ImageModel {
|
|
117
|
+
#client;
|
|
118
|
+
#modelId;
|
|
119
|
+
#info;
|
|
120
|
+
#ownsEngine;
|
|
121
|
+
#unloaded = false;
|
|
122
|
+
/** @internal */
|
|
123
|
+
constructor(client, modelId, info, ownsEngine = true) {
|
|
124
|
+
this.#client = client;
|
|
125
|
+
this.#modelId = modelId;
|
|
126
|
+
this.#info = info;
|
|
127
|
+
this.#ownsEngine = ownsEngine;
|
|
128
|
+
}
|
|
129
|
+
/** The pipeline, the device it runs on and the weight format. */
|
|
130
|
+
info() {
|
|
131
|
+
return this.#info;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Generates an image of `prompt`. Generations of one model run one after
|
|
135
|
+
* the other. `signal` stops one before its next step (it rejects with
|
|
136
|
+
* `ABORTED`).
|
|
137
|
+
*
|
|
138
|
+
* ```ts
|
|
139
|
+
* const image = await model.generate("a lighthouse at dusk, oil painting", { seed: 42 });
|
|
140
|
+
* canvas.getContext("2d")!.putImageData(image.toImageData(), 0, 0);
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
async generate(prompt, options = {}) {
|
|
144
|
+
if (typeof prompt !== "string")
|
|
145
|
+
throw new WebslmError("INVALID_ARGUMENT", "the prompt must be a string");
|
|
146
|
+
if (this.#unloaded)
|
|
147
|
+
throw new WebslmError("DISPOSED", "this image model was unloaded");
|
|
148
|
+
const wire = wireImageOptions(options);
|
|
149
|
+
const { onProgress } = options;
|
|
150
|
+
try {
|
|
151
|
+
const result = await this.#client.request({ type: "generateImage", model: this.#modelId, prompt, options: wire }, {
|
|
152
|
+
...(onProgress === undefined
|
|
153
|
+
? {}
|
|
154
|
+
: { onImageProgress: (p) => onProgress({ phase: p.phase, step: p.step, steps: p.steps }) }),
|
|
155
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
156
|
+
});
|
|
157
|
+
const rgba = result.rgba;
|
|
158
|
+
const data = new Uint8ClampedArray(rgba.buffer, rgba.byteOffset, rgba.byteLength);
|
|
159
|
+
return new GeneratedImage(result.width, result.height, result.seed, data, result.timeMs);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (isAborted(options.signal))
|
|
163
|
+
throw abortError(options.signal);
|
|
164
|
+
throw toWebslmError(error);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Frees the model and stops its worker (unless it runs in a shared engine). */
|
|
168
|
+
async unload() {
|
|
169
|
+
if (this.#unloaded)
|
|
170
|
+
return;
|
|
171
|
+
this.#unloaded = true;
|
|
172
|
+
try {
|
|
173
|
+
await this.#client.request({ type: "unload", model: this.#modelId });
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// The worker may already be gone.
|
|
177
|
+
}
|
|
178
|
+
if (this.#ownsEngine)
|
|
179
|
+
await this.#client.terminate();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Loads a text-to-image pipeline from the Hugging Face Hub (or local files,
|
|
184
|
+
* or a custom store), downloaded once into the cache like language models.
|
|
185
|
+
*
|
|
186
|
+
* ```ts
|
|
187
|
+
* import { loadImageModel } from "webslm";
|
|
188
|
+
*
|
|
189
|
+
* const model = await loadImageModel("IDKiro/sdxs-512-dreamshaper");
|
|
190
|
+
* const image = await model.generate("a red fox in the snow", { seed: 7 });
|
|
191
|
+
* document.body.append(Object.assign(document.createElement("img"), {
|
|
192
|
+
* src: URL.createObjectURL(await image.toBlob()),
|
|
193
|
+
* }));
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
export async function loadImageModel(source = DEFAULT_IMAGE_MODEL, options = {}) {
|
|
197
|
+
const device = resolveDevice(options.device);
|
|
198
|
+
const backend = resolveBackend(options.backend);
|
|
199
|
+
const quant = options.quant ?? "f16";
|
|
200
|
+
if (!IMAGE_QUANTS.includes(quant)) {
|
|
201
|
+
throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${IMAGE_QUANTS.join(", ")}`);
|
|
202
|
+
}
|
|
203
|
+
const normalized = normalizeSource(source, options.revision);
|
|
204
|
+
if (normalized.kind === "hub" && normalized.file !== undefined) {
|
|
205
|
+
throw new WebslmError("INVALID_ARGUMENT", "image models load from diffusers pipelines, not single files");
|
|
206
|
+
}
|
|
207
|
+
const decoder = options.decoder === undefined ? undefined : normalizeSource(options.decoder);
|
|
208
|
+
if (isAborted(options.signal))
|
|
209
|
+
throw abortError(options.signal);
|
|
210
|
+
const shared = options.engine;
|
|
211
|
+
if (shared !== undefined && !(shared instanceof EngineHandle)) {
|
|
212
|
+
throw new WebslmError("INVALID_ARGUMENT", "`engine` must come from createEngine()");
|
|
213
|
+
}
|
|
214
|
+
const client = shared?.client ?? (await EngineClient.start(options.worker === false ? { worker: false } : {}));
|
|
215
|
+
try {
|
|
216
|
+
const result = await client.request({
|
|
217
|
+
type: "loadImage",
|
|
218
|
+
source: toWire(normalized, options.token),
|
|
219
|
+
...(decoder === undefined ? {} : { decoder: toWire(decoder, options.token) }),
|
|
220
|
+
options: {
|
|
221
|
+
quant,
|
|
222
|
+
device,
|
|
223
|
+
...(backend === "auto" ? {} : { backend }),
|
|
224
|
+
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
225
|
+
...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
|
|
226
|
+
...(options.threads === undefined ? {} : { threads: options.threads }),
|
|
227
|
+
},
|
|
228
|
+
}, {
|
|
229
|
+
...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
|
|
230
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
231
|
+
...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
|
|
232
|
+
...(decoder?.kind === "fetch" ? { onDecoderRead: decoder.fetch } : {}),
|
|
233
|
+
});
|
|
234
|
+
return new ImageModel(client, result.model, result.info, shared === undefined);
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
if (shared === undefined)
|
|
238
|
+
await client.terminate().catch(() => { });
|
|
239
|
+
if (isAborted(options.signal))
|
|
240
|
+
throw abortError(options.signal);
|
|
241
|
+
throw toWebslmError(error);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** Models loaded by {@link generateImage}, by repository id. */
|
|
245
|
+
const sharedImageModels = new Map();
|
|
246
|
+
function sharedImageModel(repo) {
|
|
247
|
+
const key = repo.trim();
|
|
248
|
+
let pending = sharedImageModels.get(key);
|
|
249
|
+
if (pending === undefined) {
|
|
250
|
+
const loading = loadImageModel(key);
|
|
251
|
+
// A failed load is retried by the next call.
|
|
252
|
+
loading.catch(() => {
|
|
253
|
+
if (sharedImageModels.get(key) === loading)
|
|
254
|
+
sharedImageModels.delete(key);
|
|
255
|
+
});
|
|
256
|
+
sharedImageModels.set(key, loading);
|
|
257
|
+
pending = loading;
|
|
258
|
+
}
|
|
259
|
+
return pending;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Generates an image of `prompt` with a model loaded on first use and kept
|
|
263
|
+
* for later calls.
|
|
264
|
+
*
|
|
265
|
+
* ```ts
|
|
266
|
+
* import { generateImage } from "webslm";
|
|
267
|
+
*
|
|
268
|
+
* const image = await generateImage("a watercolor of a fox", { seed: 42 });
|
|
269
|
+
* const bitmap = await image.toImageBitmap();
|
|
270
|
+
* ```
|
|
271
|
+
*/
|
|
272
|
+
export async function generateImage(prompt, options = {}) {
|
|
273
|
+
const { model, ...rest } = options;
|
|
274
|
+
const loaded = model instanceof ImageModel ? model : await sharedImageModel(model ?? DEFAULT_IMAGE_MODEL);
|
|
275
|
+
return loaded.generate(prompt, rest);
|
|
276
|
+
}
|
|
277
|
+
/** Unloads every model loaded by {@link generateImage}. */
|
|
278
|
+
export async function unloadImageModels() {
|
|
279
|
+
const pending = [...sharedImageModels.values()];
|
|
280
|
+
sharedImageModels.clear();
|
|
281
|
+
await Promise.all(pending.map((p) => p.then((model) => model.unload(), () => { })));
|
|
282
|
+
}
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
// PNG
|
|
285
|
+
let crcTable;
|
|
286
|
+
function crc32(bytes, crc = 0xffffffff) {
|
|
287
|
+
if (crcTable === undefined) {
|
|
288
|
+
crcTable = new Uint32Array(256);
|
|
289
|
+
for (let n = 0; n < 256; n++) {
|
|
290
|
+
let c = n;
|
|
291
|
+
for (let k = 0; k < 8; k++)
|
|
292
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
293
|
+
crcTable[n] = c >>> 0;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
for (const byte of bytes)
|
|
297
|
+
crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
|
298
|
+
return crc;
|
|
299
|
+
}
|
|
300
|
+
function chunk(type, data) {
|
|
301
|
+
const out = new Uint8Array(12 + data.length);
|
|
302
|
+
const view = new DataView(out.buffer);
|
|
303
|
+
view.setUint32(0, data.length);
|
|
304
|
+
for (let i = 0; i < 4; i++)
|
|
305
|
+
out[4 + i] = type.charCodeAt(i);
|
|
306
|
+
out.set(data, 8);
|
|
307
|
+
view.setUint32(8 + data.length, (crc32(out.subarray(4, 8 + data.length)) ^ 0xffffffff) >>> 0);
|
|
308
|
+
return out;
|
|
309
|
+
}
|
|
310
|
+
async function zlibDeflate(bytes) {
|
|
311
|
+
if (typeof CompressionStream === "undefined") {
|
|
312
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", "PNG encoding needs CompressionStream");
|
|
313
|
+
}
|
|
314
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"));
|
|
315
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Encodes 8-bit RGBA pixels (row-major, `width * height * 4` bytes) as a
|
|
319
|
+
* PNG file.
|
|
320
|
+
*/
|
|
321
|
+
export async function encodePng(width, height, rgba) {
|
|
322
|
+
if (!(Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0)) {
|
|
323
|
+
throw new WebslmError("INVALID_ARGUMENT", `a ${width}x${height} image`);
|
|
324
|
+
}
|
|
325
|
+
if (rgba.length !== width * height * 4) {
|
|
326
|
+
throw new WebslmError("INVALID_ARGUMENT", `${rgba.length} bytes are not ${width}x${height} RGBA pixels`);
|
|
327
|
+
}
|
|
328
|
+
// Each row starts with its filter type (0: none).
|
|
329
|
+
const stride = width * 4;
|
|
330
|
+
const raw = new Uint8Array((stride + 1) * height);
|
|
331
|
+
const pixels = rgba instanceof Uint8Array || rgba instanceof Uint8ClampedArray ? rgba : Uint8Array.from(rgba);
|
|
332
|
+
for (let y = 0; y < height; y++)
|
|
333
|
+
raw.set(pixels.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
|
|
334
|
+
const header = new Uint8Array(13);
|
|
335
|
+
const view = new DataView(header.buffer);
|
|
336
|
+
view.setUint32(0, width);
|
|
337
|
+
view.setUint32(4, height);
|
|
338
|
+
header[8] = 8; // bit depth
|
|
339
|
+
header[9] = 6; // RGBA
|
|
340
|
+
const parts = [
|
|
341
|
+
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
342
|
+
chunk("IHDR", header),
|
|
343
|
+
chunk("IDAT", await zlibDeflate(raw)),
|
|
344
|
+
chunk("IEND", new Uint8Array(0)),
|
|
345
|
+
];
|
|
346
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
347
|
+
let offset = 0;
|
|
348
|
+
for (const part of parts) {
|
|
349
|
+
out.set(part, offset);
|
|
350
|
+
offset += part.length;
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,24 +10,26 @@
|
|
|
10
10
|
*
|
|
11
11
|
* The simple API is {@link load}, {@link ask}, {@link stream} and
|
|
12
12
|
* {@link LLM.chat}; {@link loadModel}, {@link Model} and {@link Session} are
|
|
13
|
-
* the advanced layer it is built on.
|
|
13
|
+
* the advanced layer it is built on. Text-to-image models have
|
|
14
|
+
* {@link generateImage} and {@link loadImageModel}.
|
|
14
15
|
*
|
|
15
16
|
* @packageDocumentation
|
|
16
17
|
*/
|
|
17
18
|
import type { SafetensorsHeader } from "./safetensors.js";
|
|
18
19
|
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";
|
|
20
|
+
export { DEFAULT_IMAGE_MODEL, encodePng, GeneratedImage, generateImage, ImageModel, loadImageModel, unloadImageModels, type GenerateImageOptions, type ImageGenerationOptions, type ImageModelInfo, type ImagePhase, type ImageProgress, type ImageQuant, type LoadImageModelOptions, } from "./image.js";
|
|
19
21
|
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
21
|
-
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
23
|
+
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, EmbedOptions, Embeddings, EmbeddingInfo, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelMemory, ModelSource, Pooling, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
22
24
|
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
23
25
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
|
|
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";
|
|
26
|
+
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
25
27
|
export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
|
|
26
28
|
export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
|
|
27
29
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
|
|
28
30
|
export { loadWasm, type WasmExports, type WasmSource } from "./wasm.js";
|
|
29
31
|
export { classifyFit, fitModel, fitParams, getBrowserResources, AUTO_QUANTS, WASM_MEMORY_LIMIT, type BrowserResources, type DeviceFit, type DeviceLimits, type FitChoice, type FitLevel, type FitModelOptions, type ModelFit, } from "./fit.js";
|
|
30
|
-
export { estimateModelMemory, type EstimateFormat, type EstimateOptions, type KvLayers, type MemoryEstimate, } from "./memory.js";
|
|
32
|
+
export { estimateModelMemory, kvCacheBytes, type EstimateFormat, type EstimateOptions, type KvCacheType, type KvLayers, type MemoryEstimate, } from "./memory.js";
|
|
31
33
|
/** Version of the Rust engine, read from the WebAssembly module. */
|
|
32
34
|
export declare function version(): Promise<string>;
|
|
33
35
|
/**
|
package/dist/index.js
CHANGED
|
@@ -10,22 +10,24 @@
|
|
|
10
10
|
*
|
|
11
11
|
* The simple API is {@link load}, {@link ask}, {@link stream} and
|
|
12
12
|
* {@link LLM.chat}; {@link loadModel}, {@link Model} and {@link Session} are
|
|
13
|
-
* the advanced layer it is built on.
|
|
13
|
+
* the advanced layer it is built on. Text-to-image models have
|
|
14
|
+
* {@link generateImage} and {@link loadImageModel}.
|
|
14
15
|
*
|
|
15
16
|
* @packageDocumentation
|
|
16
17
|
*/
|
|
17
18
|
import { loadWasm } from "./wasm.js";
|
|
18
19
|
export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, } from "./simple.js";
|
|
20
|
+
export { DEFAULT_IMAGE_MODEL, encodePng, GeneratedImage, generateImage, ImageModel, loadImageModel, unloadImageModels, } from "./image.js";
|
|
19
21
|
export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
|
|
21
23
|
export { WebslmError } from "./errors.js";
|
|
22
24
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "./curated.js";
|
|
23
|
-
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
25
|
+
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
24
26
|
export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
|
|
25
27
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
|
|
26
28
|
export { loadWasm } from "./wasm.js";
|
|
27
29
|
export { classifyFit, fitModel, fitParams, getBrowserResources, AUTO_QUANTS, WASM_MEMORY_LIMIT, } from "./fit.js";
|
|
28
|
-
export { estimateModelMemory, } from "./memory.js";
|
|
30
|
+
export { estimateModelMemory, kvCacheBytes, } from "./memory.js";
|
|
29
31
|
/** Version of the Rust engine, read from the WebAssembly module. */
|
|
30
32
|
export async function version() {
|
|
31
33
|
const wasm = await loadWasm();
|
package/dist/memory.d.ts
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
* Memory a model needs, estimated from its `config.json` and safetensors
|
|
3
3
|
* headers before downloading it: a port of the Rust estimate
|
|
4
4
|
* (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
|
|
5
|
-
* KV cache layer by layer (full attention grows with the context,
|
|
6
|
-
*
|
|
7
|
-
* convolution and linear-attention layers a
|
|
8
|
-
* activations of a 512-token prefill. Both
|
|
9
|
-
* against the same cases
|
|
5
|
+
* KV cache layer by layer (full attention grows with the context, in f32
|
|
6
|
+
* or int8, up to the KV eviction budget; sliding-window layers keep a ring
|
|
7
|
+
* of `2 × window - 1` positions, convolution and linear-attention layers a
|
|
8
|
+
* fixed state) and the activations of a 512-token prefill. Both
|
|
9
|
+
* implementations are checked against the same cases
|
|
10
|
+
* (`fixtures/memory/estimates.json`).
|
|
10
11
|
*/
|
|
11
12
|
import type { HeaderTensors } from "./hub.js";
|
|
12
13
|
import type { Quant } from "./types.js";
|
|
@@ -24,11 +25,11 @@ export interface MemoryEstimate {
|
|
|
24
25
|
readonly weights: number;
|
|
25
26
|
/** KV caches and recurrent states of one sequence at `contextLength`. */
|
|
26
27
|
readonly kvCache: number;
|
|
27
|
-
/** What one more position adds to the KV cache. */
|
|
28
|
+
/** What one more position adds to the KV cache (0 once KV eviction caps it below the context). */
|
|
28
29
|
readonly kvPerToken: number;
|
|
29
30
|
/** Activations of a prefill batch. */
|
|
30
31
|
readonly activations: number;
|
|
31
|
-
/** The largest single buffer (
|
|
32
|
+
/** The largest single buffer: the widest activation (KV caches are paged below the device's limit). */
|
|
32
33
|
readonly largestBuffer: number;
|
|
33
34
|
/** Positions the estimate assumes. */
|
|
34
35
|
readonly contextLength: number;
|
|
@@ -47,6 +48,8 @@ export interface MemoryEstimate {
|
|
|
47
48
|
readonly linearAttention: KvLayers;
|
|
48
49
|
};
|
|
49
50
|
}
|
|
51
|
+
/** How full-attention layers store keys and values (`kvCache` load option). */
|
|
52
|
+
export type KvCacheType = "f32" | "int8";
|
|
50
53
|
export interface EstimateOptions {
|
|
51
54
|
/** Weight format (default `"q8"`). */
|
|
52
55
|
readonly quant?: EstimateFormat;
|
|
@@ -57,7 +60,21 @@ export interface EstimateOptions {
|
|
|
57
60
|
* (default `true`, as the load option `vision`).
|
|
58
61
|
*/
|
|
59
62
|
readonly vision?: boolean;
|
|
63
|
+
/** KV cache storage of full-attention layers (default `"f32"`). */
|
|
64
|
+
readonly kvCache?: KvCacheType;
|
|
65
|
+
/** Int8 KV cache: the most recent positions kept in f32 (default 128). */
|
|
66
|
+
readonly kvResidual?: number;
|
|
67
|
+
/** KV eviction: most positions a full-attention layer holds. */
|
|
68
|
+
readonly kvBudget?: number;
|
|
60
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Bytes of one full-attention cache holding `positions` positions: f32, or
|
|
72
|
+
* int8 in the KIVI layout (8-bit codes, a minimum and scale per channel
|
|
73
|
+
* and group of 32 positions for keys, per position and head for values,
|
|
74
|
+
* and an f32 ring of `residual + 32` positions). `KvCacheOptions::bytes`
|
|
75
|
+
* in Rust.
|
|
76
|
+
*/
|
|
77
|
+
export declare function kvCacheBytes(kvHeads: number, headDim: number, positions: number, type?: KvCacheType, residual?: number): number;
|
|
61
78
|
export type LayerType = "full" | "sliding" | "conv" | "linear";
|
|
62
79
|
/** The text decoder hyperparameters the estimate reads (see `TextConfig` in Rust). */
|
|
63
80
|
export interface TextConfig {
|
package/dist/memory.js
CHANGED
|
@@ -2,13 +2,39 @@
|
|
|
2
2
|
* Memory a model needs, estimated from its `config.json` and safetensors
|
|
3
3
|
* headers before downloading it: a port of the Rust estimate
|
|
4
4
|
* (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
|
|
5
|
-
* KV cache layer by layer (full attention grows with the context,
|
|
6
|
-
*
|
|
7
|
-
* convolution and linear-attention layers a
|
|
8
|
-
* activations of a 512-token prefill. Both
|
|
9
|
-
* against the same cases
|
|
5
|
+
* KV cache layer by layer (full attention grows with the context, in f32
|
|
6
|
+
* or int8, up to the KV eviction budget; sliding-window layers keep a ring
|
|
7
|
+
* of `2 × window - 1` positions, convolution and linear-attention layers a
|
|
8
|
+
* fixed state) and the activations of a 512-token prefill. Both
|
|
9
|
+
* implementations are checked against the same cases
|
|
10
|
+
* (`fixtures/memory/estimates.json`).
|
|
10
11
|
*/
|
|
11
12
|
import { WebslmError } from "./errors.js";
|
|
13
|
+
/** Positions an int8 KV cache quantizes together. */
|
|
14
|
+
const KV_GROUP = 32;
|
|
15
|
+
/** Most recent positions an int8 KV cache keeps in f32 by default. */
|
|
16
|
+
const DEFAULT_KV_RESIDUAL = 128;
|
|
17
|
+
/**
|
|
18
|
+
* Bytes of one full-attention cache holding `positions` positions: f32, or
|
|
19
|
+
* int8 in the KIVI layout (8-bit codes, a minimum and scale per channel
|
|
20
|
+
* and group of 32 positions for keys, per position and head for values,
|
|
21
|
+
* and an f32 ring of `residual + 32` positions). `KvCacheOptions::bytes`
|
|
22
|
+
* in Rust.
|
|
23
|
+
*/
|
|
24
|
+
export function kvCacheBytes(kvHeads, headDim, positions, type = "f32", residual = DEFAULT_KV_RESIDUAL) {
|
|
25
|
+
const f32Position = 2 * kvHeads * headDim * 4;
|
|
26
|
+
if (type === "f32")
|
|
27
|
+
return positions * f32Position;
|
|
28
|
+
const residualPositions = Math.ceil(residual / KV_GROUP) * KV_GROUP;
|
|
29
|
+
const quantized = Math.floor(Math.max(positions - residualPositions, 0) / KV_GROUP) * KV_GROUP;
|
|
30
|
+
const ring = Math.min(residualPositions + KV_GROUP, positions);
|
|
31
|
+
return Math.ceil(int8BytesPerPosition(kvHeads, headDim) * quantized) + ring * f32Position;
|
|
32
|
+
}
|
|
33
|
+
/** Bytes of one quantized position of an int8 KV cache. */
|
|
34
|
+
function int8BytesPerPosition(kvHeads, headDim) {
|
|
35
|
+
const width = kvHeads * headDim;
|
|
36
|
+
return 2 * width + (width * 8) / KV_GROUP + kvHeads * 8;
|
|
37
|
+
}
|
|
12
38
|
/** Rows of the prefill batch the activation estimate assumes. */
|
|
13
39
|
const PREFILL_ROWS = 512;
|
|
14
40
|
/** Context length when none is given, capped by the model. */
|
|
@@ -229,7 +255,18 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
229
255
|
const context = options.contextLength ?? Math.min(text.maxPositionEmbeddings ?? DEFAULT_CONTEXT, DEFAULT_CONTEXT);
|
|
230
256
|
const kvWidth = text.numKeyValueHeads * text.headDim;
|
|
231
257
|
const hidden = text.hiddenSize;
|
|
232
|
-
const
|
|
258
|
+
const f32PerToken = 2 * kvWidth * 4;
|
|
259
|
+
const kvType = options.kvCache ?? "f32";
|
|
260
|
+
if (kvType !== "f32" && kvType !== "int8") {
|
|
261
|
+
throw new WebslmError("INVALID_ARGUMENT", "kvCache must be f32 or int8");
|
|
262
|
+
}
|
|
263
|
+
const held = options.kvBudget === undefined ? context : Math.min(context, options.kvBudget);
|
|
264
|
+
const fullBytes = kvCacheBytes(text.numKeyValueHeads, text.headDim, held, kvType, options.kvResidual ?? DEFAULT_KV_RESIDUAL);
|
|
265
|
+
const fullPerToken = held < context
|
|
266
|
+
? 0
|
|
267
|
+
: kvType === "f32"
|
|
268
|
+
? f32PerToken
|
|
269
|
+
: Math.ceil(int8BytesPerPosition(text.numKeyValueHeads, text.headDim));
|
|
233
270
|
const kv = {
|
|
234
271
|
fullAttention: { layers: 0, bytes: 0 },
|
|
235
272
|
slidingAttention: { layers: 0, bytes: 0 },
|
|
@@ -242,7 +279,7 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
242
279
|
case "sliding": {
|
|
243
280
|
const window = text.slidingWindow ?? context;
|
|
244
281
|
kv.slidingAttention.layers += 1;
|
|
245
|
-
kv.slidingAttention.bytes +=
|
|
282
|
+
kv.slidingAttention.bytes += f32PerToken * Math.min(Math.max(2 * window - 1, 0), context);
|
|
246
283
|
break;
|
|
247
284
|
}
|
|
248
285
|
case "conv":
|
|
@@ -259,7 +296,7 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
259
296
|
case "full":
|
|
260
297
|
kvPerToken += fullPerToken;
|
|
261
298
|
kv.fullAttention.layers += 1;
|
|
262
|
-
kv.fullAttention.bytes +=
|
|
299
|
+
kv.fullAttention.bytes += fullBytes;
|
|
263
300
|
break;
|
|
264
301
|
}
|
|
265
302
|
}
|
|
@@ -268,9 +305,10 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
268
305
|
const vocab = text.vocabSize ?? 0;
|
|
269
306
|
const rows = Math.min(PREFILL_ROWS, Math.max(context, 1));
|
|
270
307
|
const activations = rows * (6 * hidden + 3 * intermediate) * 4 + vocab * 4;
|
|
271
|
-
const largestBuffer = Math.max(
|
|
272
|
-
// The
|
|
273
|
-
|
|
308
|
+
const largestBuffer = Math.max(rows * 2 * intermediate * 4, rows * Math.max(widestMatrix, hidden) * 4);
|
|
309
|
+
// The full-attention caches at half the context, on average; the vision
|
|
310
|
+
// encoder is not read to decode a token.
|
|
311
|
+
const decodeBytes = weights - inputEmbedding + kvCache - Math.floor(kv.fullAttention.bytes / 2);
|
|
274
312
|
const allWeights = weights + visionWeights;
|
|
275
313
|
return {
|
|
276
314
|
quant,
|
package/dist/models.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
|
|
2
2
|
import { EngineClient } from "./client.js";
|
|
3
3
|
import { type CheckpointTraits } from "./curated.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type { WireSource } from "./protocol.js";
|
|
5
|
+
import type { AdapterSource, Backend, ApplyAdapterOptions, ChatInputMessage, ChatStream, CompletionOptions, Device, EmbedOptions, Embeddings, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
|
|
5
6
|
/**
|
|
6
7
|
* An engine (a worker, or the calling thread) that several models can share
|
|
7
8
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -69,6 +70,8 @@ export declare function normalizeSource(source: string | ModelSource, revision?:
|
|
|
69
70
|
* must hold `adapter_config.json` and `adapter_model.safetensors`.
|
|
70
71
|
*/
|
|
71
72
|
export declare function normalizeAdapterSource(source: AdapterSource, revision?: string): NormalizedSource;
|
|
73
|
+
/** @internal The form of a normalized source posted to the engine. */
|
|
74
|
+
export declare function toWire(normalized: NormalizedSource, token?: string): WireSource;
|
|
72
75
|
/**
|
|
73
76
|
* Loads a model from the Hugging Face Hub, local files or a custom store.
|
|
74
77
|
*
|
|
@@ -193,6 +196,21 @@ export declare class Model extends Conversation {
|
|
|
193
196
|
removeAdapter(options?: {
|
|
194
197
|
readonly signal?: AbortSignal;
|
|
195
198
|
}): Promise<LoraInfo | undefined>;
|
|
199
|
+
/**
|
|
200
|
+
* Embeds texts with an encoder (an embedding model: BERT, ModernBERT,
|
|
201
|
+
* model2vec; see {@link ModelInfo.embedding}): one vector per text,
|
|
202
|
+
* pooled and normalized as the checkpoint's sentence-transformers
|
|
203
|
+
* settings say unless `options` say otherwise. Texts longer than the
|
|
204
|
+
* model's limit are cut. Rejects with `UNSUPPORTED_TASK` on a language
|
|
205
|
+
* model.
|
|
206
|
+
*
|
|
207
|
+
* ```ts
|
|
208
|
+
* const model = await loadModel("sentence-transformers/all-MiniLM-L6-v2");
|
|
209
|
+
* const { vectors } = await model.embed(["A cat sleeps.", "A kitten naps."]);
|
|
210
|
+
* const cosine = vectors[0].reduce((s, v, i) => s + v * vectors[1][i], 0);
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
embed(texts: string | readonly string[], options?: EmbedOptions): Promise<Embeddings>;
|
|
196
214
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
197
215
|
session(): Promise<Session>;
|
|
198
216
|
/**
|