webslm 0.7.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 +85 -2
- 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 +181 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +1 -0
- 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 +5 -3
- package/dist/index.js +4 -2
- package/dist/models.d.ts +19 -1
- package/dist/models.js +45 -6
- package/dist/native.d.ts +28 -0
- package/dist/protocol.d.ts +75 -2
- package/dist/simple.d.ts +4 -1
- package/dist/simple.js +9 -2
- package/dist/types.d.ts +39 -1
- 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 +70 -6
- package/wasm/relaxed/webslm_wasm.js +163 -18
- 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 +70 -6
- package/wasm/simd/webslm_wasm.js +163 -18
- 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 +71 -7
- package/wasm/threads/webslm_wasm.js +168 -23
- 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,18 +10,20 @@
|
|
|
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, ModelMemory, 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";
|
package/dist/index.js
CHANGED
|
@@ -10,17 +10,19 @@
|
|
|
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";
|
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
|
/**
|
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 {
|
|
@@ -271,6 +271,7 @@ export async function loadModel(source, options = {}) {
|
|
|
271
271
|
options: {
|
|
272
272
|
quant,
|
|
273
273
|
...(requested === "auto" ? { autoQuant: true } : {}),
|
|
274
|
+
...(options.quant === undefined ? { defaultQuant: true } : {}),
|
|
274
275
|
device,
|
|
275
276
|
...(backend === "auto" ? {} : { backend }),
|
|
276
277
|
...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
|
|
@@ -294,8 +295,11 @@ export async function loadModel(source, options = {}) {
|
|
|
294
295
|
...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
|
|
295
296
|
});
|
|
296
297
|
// The native engine chose the format again, from the machine's memory
|
|
297
|
-
// (its own note says why when it did not load q8)
|
|
298
|
-
|
|
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 };
|
|
299
303
|
return new Model(client, result.model, info, {
|
|
300
304
|
...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
|
|
301
305
|
...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
|
|
@@ -749,6 +753,41 @@ export class Model extends Conversation {
|
|
|
749
753
|
this.#info = info;
|
|
750
754
|
return removed ?? undefined;
|
|
751
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
|
+
}
|
|
752
791
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
753
792
|
async session() {
|
|
754
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. */
|