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/README.md
CHANGED
|
@@ -99,7 +99,7 @@ chat.reset();
|
|
|
99
99
|
await llm.unload();
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
`load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized, `"auto"` picks `"q8"` unless the model does not fit this environment's memory, then `"q4"`, see [`fitModel`](#hub-helpers-and-cache); `ModelInfo.quantNote` says why), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `weightCache` (default `true`, see [the converted-weight cache](#converted-weight-cache)), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
|
|
102
|
+
`load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized, `"auto"` picks `"q8"` unless the model does not fit this environment's memory, then `"q4"`, see [`fitModel`](#hub-helpers-and-cache); `ModelInfo.quantNote` says why), `revision`, `token` (gated or private repositories), `contextLength`, `kvCache` (`"f32"` (default) or `"int8"`: keys and values in 8 bits with the most recent `kvResidual` positions (default 128) in f32, about 3 times less KV cache memory at 4096 positions), `kvBudget` (opt-in KV eviction: at most this many positions per full-attention layer, keeping attention sinks, the recent quarter and the most distinct keys; see [KV cache memory](https://github.com/maxgfr/webslm#kv-cache-memory)), `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `weightCache` (default `true`, see [the converted-weight cache](#converted-weight-cache)), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
|
|
103
103
|
|
|
104
104
|
Each chat keeps its own cache in the engine, so a turn only processes the new message; `chat.dispose()` frees it. Calls on one model, and turns of one chat, run one after the other. `llm.model` is the underlying `Model`, for the advanced API.
|
|
105
105
|
|
|
@@ -131,6 +131,39 @@ A `ChatMessage`'s `content` is always a string, so code that renders `message.co
|
|
|
131
131
|
|
|
132
132
|
Images and videos sent to a text-only model are an `INVALID_ARGUMENT` error. The load option `vision: false` loads a vision-language checkpoint as a text-only model, without the memory of its vision encoder (100M parameters for Qwen3.5-0.8B). Memory estimates (`fitModel`, `quant: "auto"`) count the encoder unless `vision: false`. The prefix cache tells images apart by their pixels, so a follow-up about the same image only runs the new tokens.
|
|
133
133
|
|
|
134
|
+
## Image generation
|
|
135
|
+
|
|
136
|
+
Small text-to-image models run from their original `diffusers` checkpoints (`model_index.json` and its component folders), on WebGPU when there is one (the native GPU in Node) and on the CPU otherwise.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { generateImage, loadImageModel } from "webslm";
|
|
140
|
+
|
|
141
|
+
// DEFAULT_IMAGE_MODEL (IDKiro/sdxs-512-dreamshaper: one step, 1.8 GB), loaded once and kept.
|
|
142
|
+
const image = await generateImage("a lighthouse on a cliff at dusk, oil painting", { seed: 42 });
|
|
143
|
+
canvas.getContext("2d")!.putImageData(image.toImageData(), 0, 0);
|
|
144
|
+
|
|
145
|
+
const model = await loadImageModel("IDKiro/sdxs-512-dreamshaper", {
|
|
146
|
+
device: "auto", // the GPU whenever there is one
|
|
147
|
+
quant: "f16", // or "f32", "q8"
|
|
148
|
+
onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
|
|
149
|
+
});
|
|
150
|
+
const fox = await model.generate("a red fox in the snow", {
|
|
151
|
+
size: 512, // or "768x512", or width and height (multiples of info().sizeMultiple)
|
|
152
|
+
steps: 1,
|
|
153
|
+
seed: 7, // random when omitted; fox.seed reports it
|
|
154
|
+
onProgress: (p) => console.log(p.phase, p.step, p.steps), // "encoding", "denoising", "decoding"
|
|
155
|
+
signal, // stops before the next step
|
|
156
|
+
});
|
|
157
|
+
fox.data; // Uint8ClampedArray, RGBA
|
|
158
|
+
await fox.toImageBitmap();
|
|
159
|
+
await fox.toPng(); // Uint8Array, also toBlob()
|
|
160
|
+
await model.unload();
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`loadImageModel(source, options)` takes a Hub id or a `files` / `fetch` [source](#sources), `device`, `backend`, `quant`, `decoder` (a standalone autoencoder replacing the pipeline's own, e.g. `"madebyollin/taesd"`), `revision`, `token`, `cacheDir`, `worker`, `engine`, `signal` and `onProgress`. `generate(prompt, options)` takes `width` / `height` / `size`, `steps` (default 1), `guidance` (classifier-free guidance, default 0; above 1 the model also runs on `negativePrompt`), `seed`, `onProgress` and `signal`; a model runs its generations one after the other. `info()` reports the pipeline and scheduler classes, the decoder (`"tiny"` or `"kl"`), `sizeMultiple`, the device and backend, and the weight format. `generateImage(prompt, { model, ...options })` loads `model` (a repository id, default `DEFAULT_IMAGE_MODEL`, or a loaded `ImageModel`) on first use and keeps it; `unloadAll()` (or `unloadImageModels()`) frees it. `encodePng(width, height, rgba)` encodes pixels as PNG.
|
|
164
|
+
|
|
165
|
+
The AI SDK provider has `webslm.imageModel(id)` for `generateImage` from `ai` (see [AI SDK](#ai-sdk)).
|
|
166
|
+
|
|
134
167
|
## React
|
|
135
168
|
|
|
136
169
|
```tsx
|
|
@@ -190,8 +223,58 @@ await model.unload(); // or webslm.unloadAll()
|
|
|
190
223
|
|
|
191
224
|
Prompts are user and assistant text parts, text documents (`file` parts whose data is text), and images and videos for [vision-language models](#images-and-video): `file` parts of type `image/*` or `video/*` whose data is bytes, base64 or a URL. Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
|
|
192
225
|
|
|
226
|
+
Encoders are AI SDK embedding models (specification v4), behind `embed` and `embedMany`:
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
import { webslm } from "webslm/ai-sdk";
|
|
230
|
+
import { cosineSimilarity, embedMany } from "ai";
|
|
231
|
+
|
|
232
|
+
const { embeddings, usage } = await embedMany({
|
|
233
|
+
model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
|
|
234
|
+
values: ["sunny day at the beach", "rainy afternoon in the city"],
|
|
235
|
+
});
|
|
236
|
+
console.log(cosineSimilarity(embeddings[0], embeddings[1]), usage.tokens);
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`webslm.embeddingModel(modelId, settings)` takes the load options too, and `pooling`, `normalize` (instead of the model's, also per call in `providerOptions.webslm`) and `maxEmbeddingsPerCall` (default 256: `embedMany` splits longer lists). `dimensions` other than the model's own come back as an `unsupported` warning; `usage.tokens` counts the tokens read. A language model id rejects with `UNSUPPORTED_TASK`.
|
|
240
|
+
|
|
241
|
+
Text-to-image models come from `webslm.imageModel(id, settings)` (see [image generation](#image-generation)), an image model of specification v4 for `generateImage` from `ai`:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
import { generateImage } from "ai";
|
|
245
|
+
import { webslm } from "webslm/ai-sdk";
|
|
246
|
+
|
|
247
|
+
const { images, providerMetadata } = await generateImage({
|
|
248
|
+
model: webslm.imageModel("IDKiro/sdxs-512-dreamshaper"),
|
|
249
|
+
prompt: "a red fox in the snow",
|
|
250
|
+
n: 2, // generated one after the other, seeds `seed` and `seed + 1`
|
|
251
|
+
seed: 7,
|
|
252
|
+
size: "512x512", // or aspectRatio: "16:9" (the longer side 512 pixels)
|
|
253
|
+
providerOptions: { webslm: { steps: 1, guidance: 0, negativePrompt: "blur" } },
|
|
254
|
+
});
|
|
255
|
+
images[0].uint8Array; // PNG
|
|
256
|
+
providerMetadata.webslm.images; // [{ seed, width, height, timeMs }, ...]
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
`settings` are the load options of `loadImageModel` and the defaults `steps`, `guidance` and `negativePrompt`; image models of one id and the same load options share the loaded model. Image files and masks (editing) are not supported (an `unsupported` warning). `createWebslm({ imageEngine })` replaces what loads them.
|
|
260
|
+
|
|
193
261
|
`CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, with the sampling their model cards recommend, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
|
|
194
262
|
|
|
263
|
+
## Embeddings
|
|
264
|
+
|
|
265
|
+
Encoders (embedding models) load with `loadModel` like language models, and answer `embed` instead of `chat`: BERT and MiniLM (`sentence-transformers/all-MiniLM-L6-v2`), ModernBERT and its descendants (`jhu-clsp/ettin-encoder-17m`, `jhu-clsp/mmBERT-small`) and model2vec static embeddings (`minishlab/potion-base-2M`).
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
import { loadModel } from "webslm";
|
|
269
|
+
|
|
270
|
+
const model = await loadModel("sentence-transformers/all-MiniLM-L6-v2");
|
|
271
|
+
const { vectors, dimensions, tokens } = await model.embed(["A cat sleeps.", "A kitten naps."]);
|
|
272
|
+
const cosine = vectors[0].reduce((s, v, i) => s + v * vectors[1][i], 0); // normalized: the dot product
|
|
273
|
+
model.info().embedding; // { dimensions: 384, pooling: ["mean"], normalize: true, maxLength: 256 }
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Vectors are pooled and normalized as the checkpoint's sentence-transformers files say (mean pooling and no normalization for a plain checkpoint); `embed(texts, { pooling, normalize })` overrides both for one call (`"cls"`, `"mean"`, `"max"`, `"mean_sqrt_len_tokens"`, `"weightedmean"`, `"lasttoken"`). `vectors` are views on one `Float32Array` (`data`), and `tokens` counts the tokens read from each text: texts longer than `maxLength` are cut. Without `quant`, an encoder loads in f32 (`quant: "q8"` moves the vectors by about 1e-3), on the CPU under `device: "auto"`. The embeddings match sentence-transformers and model2vec within 1.3e-6 of the largest value, in the WebAssembly engine, natively and on the GPU (see the [repository README](../../README.md#embeddings)). `chat`, `generate`, sessions and adapters reject on an encoder with `UNSUPPORTED_TASK`, and `embed` on a language model; `searchModels` and `checkModel` mark embedding models with `embedding: true` (supported when their `model_type` is one of `ENCODER_MODEL_TYPES`).
|
|
277
|
+
|
|
195
278
|
## Advanced API
|
|
196
279
|
|
|
197
280
|
The simple API above is built on `loadModel`, `Model` and `Session`, which expose every option.
|
|
@@ -458,11 +541,11 @@ export default defineConfig({
|
|
|
458
541
|
});
|
|
459
542
|
```
|
|
460
543
|
|
|
461
|
-
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.
|
|
544
|
+
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.9.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
|
|
462
545
|
|
|
463
546
|
## Errors
|
|
464
547
|
|
|
465
|
-
Every error is a `WebslmError` with a stable `code`: `ABORTED`, `NOT_FOUND`, `UNAUTHORIZED` (gated repository), `NETWORK`, `UNSUPPORTED_MODEL`, `UNSUPPORTED_DEVICE`, `INVALID_CHECKPOINT`, `INVALID_ADAPTER`, `NO_CHAT_TEMPLATE`, `INVALID_STATE`, `INVALID_ARGUMENT`, `BUSY`, `DISPOSED`, `READ_FAILED`, `INTEGRITY`, `CACHE`, `WORKER`, `GPU_OUT_OF_MEMORY`, `GPU_DEVICE_LOST`, `GPU_ERROR`, `ENGINE`.
|
|
548
|
+
Every error is a `WebslmError` with a stable `code`: `ABORTED`, `NOT_FOUND`, `UNAUTHORIZED` (gated repository), `NETWORK`, `UNSUPPORTED_MODEL`, `UNSUPPORTED_TASK` (generating with an encoder, or `embed` on a language model), `UNSUPPORTED_DEVICE`, `INVALID_CHECKPOINT`, `INVALID_ADAPTER`, `NO_CHAT_TEMPLATE`, `INVALID_STATE`, `INVALID_ARGUMENT`, `BUSY`, `DISPOSED`, `READ_FAILED`, `INTEGRITY`, `CACHE`, `WORKER`, `GPU_OUT_OF_MEMORY`, `GPU_DEVICE_LOST`, `GPU_ERROR`, `ENGINE`.
|
|
466
549
|
|
|
467
550
|
WebGPU reports failures asynchronously; webslm checks the device's error scopes, its uncaptured errors and its lost callback, so a model that does not fit fails instead of producing zeros. Before uploading anything, the weights and KV cache are estimated against the adapter's `maxBufferSize` and `maxStorageBufferBindingSize`: a model that cannot fit rejects with `GPU_OUT_OF_MEMORY` (on `device: "webgpu"`) or loads on the CPU (on `"auto"`, with `deviceNote`). An allocation the device refuses while loading or running rejects with `GPU_OUT_OF_MEMORY`, a lost device (driver reset, GPU removed) with `GPU_DEVICE_LOST`: load the model again.
|
|
468
551
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** The AI SDK embedding model (specification v4) over a webslm encoder. */
|
|
2
|
+
import type { EmbeddingModelV4, EmbeddingModelV4CallOptions, EmbeddingModelV4Result } from "@ai-sdk/provider";
|
|
3
|
+
import type { LoadModelOptions, ModelInfo, Pooling } from "../types.js";
|
|
4
|
+
import { type ModelSlot } from "./loader.js";
|
|
5
|
+
import type { WebslmPreloadOptions } from "./language-model.js";
|
|
6
|
+
/** Defaults of every `embed` call; a call's `providerOptions.webslm` takes precedence. */
|
|
7
|
+
export interface WebslmEmbeddingCallSettings {
|
|
8
|
+
/** Pooling instead of the model's own (sentence-transformers' `1_Pooling`, else mean). */
|
|
9
|
+
readonly pooling?: Pooling;
|
|
10
|
+
/** L2-normalize the vectors, or not, instead of the model's setting. */
|
|
11
|
+
readonly normalize?: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** Settings of `webslm.embeddingModel(modelId, settings)`: how to load the encoder, and call defaults. */
|
|
14
|
+
export interface WebslmEmbeddingSettings extends Omit<LoadModelOptions, "signal">, WebslmEmbeddingCallSettings {
|
|
15
|
+
/** Most texts in one `doEmbed` call (default 256; `embedMany` splits larger lists). */
|
|
16
|
+
readonly maxEmbeddingsPerCall?: number;
|
|
17
|
+
}
|
|
18
|
+
/** The fields of {@link WebslmEmbeddingSettings} that are not load options. */
|
|
19
|
+
export declare const EMBEDDING_SETTING_KEYS: readonly ["pooling", "normalize", "maxEmbeddingsPerCall"];
|
|
20
|
+
/**
|
|
21
|
+
* An AI SDK embedding model backed by a webslm encoder (BERT, ModernBERT,
|
|
22
|
+
* model2vec), loaded on the first call and shared by every embedding
|
|
23
|
+
* model of the provider with the same id and load options. Calls run one
|
|
24
|
+
* at a time.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
28
|
+
* import { embedMany, cosineSimilarity } from "ai";
|
|
29
|
+
*
|
|
30
|
+
* const { embeddings } = await embedMany({
|
|
31
|
+
* model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
|
|
32
|
+
* values: ["A cat sleeps.", "A kitten naps."],
|
|
33
|
+
* });
|
|
34
|
+
* console.log(cosineSimilarity(embeddings[0], embeddings[1]));
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare class WebslmEmbeddingModel implements EmbeddingModelV4 {
|
|
38
|
+
#private;
|
|
39
|
+
readonly specificationVersion: "v4";
|
|
40
|
+
readonly provider = "webslm";
|
|
41
|
+
readonly modelId: string;
|
|
42
|
+
readonly maxEmbeddingsPerCall: number;
|
|
43
|
+
/** Calls queue on the one model: nothing to gain in parallel. */
|
|
44
|
+
readonly supportsParallelCalls = false;
|
|
45
|
+
/** @internal Built by the provider (`webslm.embeddingModel(id)`). */
|
|
46
|
+
constructor(modelId: string, slot: ModelSlot, settings?: WebslmEmbeddingSettings);
|
|
47
|
+
/** Downloads and loads the encoder now instead of at the first call; resolves to its description. */
|
|
48
|
+
load(options?: WebslmPreloadOptions): Promise<ModelInfo>;
|
|
49
|
+
/** Frees the encoder (once the call in progress ends); the next call loads it again. */
|
|
50
|
+
unload(): Promise<void>;
|
|
51
|
+
doEmbed(options: EmbeddingModelV4CallOptions): Promise<EmbeddingModelV4Result>;
|
|
52
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** The AI SDK embedding model (specification v4) over a webslm encoder. */
|
|
2
|
+
import { WebslmError, toWebslmError } from "../errors.js";
|
|
3
|
+
import { abortReason, raceAbort } from "./loader.js";
|
|
4
|
+
const PROVIDER = "webslm";
|
|
5
|
+
const POOLINGS = ["cls", "mean", "max", "mean_sqrt_len_tokens", "weightedmean", "lasttoken"];
|
|
6
|
+
/** The fields of {@link WebslmEmbeddingSettings} that are not load options. */
|
|
7
|
+
export const EMBEDDING_SETTING_KEYS = ["pooling", "normalize", "maxEmbeddingsPerCall"];
|
|
8
|
+
/** `providerOptions.webslm` of a call, read leniently (unknown keys and wrong types are ignored). */
|
|
9
|
+
function callSettings(options) {
|
|
10
|
+
const raw = options.providerOptions?.[PROVIDER];
|
|
11
|
+
if (raw === undefined)
|
|
12
|
+
return {};
|
|
13
|
+
const out = {};
|
|
14
|
+
if (typeof raw.pooling === "string" && POOLINGS.includes(raw.pooling)) {
|
|
15
|
+
out.pooling = raw.pooling;
|
|
16
|
+
}
|
|
17
|
+
if (typeof raw.normalize === "boolean")
|
|
18
|
+
out.normalize = raw.normalize;
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* An AI SDK embedding model backed by a webslm encoder (BERT, ModernBERT,
|
|
23
|
+
* model2vec), loaded on the first call and shared by every embedding
|
|
24
|
+
* model of the provider with the same id and load options. Calls run one
|
|
25
|
+
* at a time.
|
|
26
|
+
*
|
|
27
|
+
* ```ts
|
|
28
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
29
|
+
* import { embedMany, cosineSimilarity } from "ai";
|
|
30
|
+
*
|
|
31
|
+
* const { embeddings } = await embedMany({
|
|
32
|
+
* model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
|
|
33
|
+
* values: ["A cat sleeps.", "A kitten naps."],
|
|
34
|
+
* });
|
|
35
|
+
* console.log(cosineSimilarity(embeddings[0], embeddings[1]));
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export class WebslmEmbeddingModel {
|
|
39
|
+
specificationVersion = "v4";
|
|
40
|
+
provider = PROVIDER;
|
|
41
|
+
modelId;
|
|
42
|
+
maxEmbeddingsPerCall;
|
|
43
|
+
/** Calls queue on the one model: nothing to gain in parallel. */
|
|
44
|
+
supportsParallelCalls = false;
|
|
45
|
+
#slot;
|
|
46
|
+
#settings;
|
|
47
|
+
/** @internal Built by the provider (`webslm.embeddingModel(id)`). */
|
|
48
|
+
constructor(modelId, slot, settings = {}) {
|
|
49
|
+
this.modelId = modelId;
|
|
50
|
+
this.#slot = slot;
|
|
51
|
+
this.#settings = settings;
|
|
52
|
+
const max = settings.maxEmbeddingsPerCall ?? 256;
|
|
53
|
+
if (!Number.isInteger(max) || max < 1) {
|
|
54
|
+
throw new WebslmError("INVALID_ARGUMENT", "maxEmbeddingsPerCall must be a positive integer");
|
|
55
|
+
}
|
|
56
|
+
this.maxEmbeddingsPerCall = max;
|
|
57
|
+
}
|
|
58
|
+
/** Downloads and loads the encoder now instead of at the first call; resolves to its description. */
|
|
59
|
+
async load(options = {}) {
|
|
60
|
+
const loaded = await this.#slot.acquire(options.signal, [this.#settings.onProgress, options.onProgress]);
|
|
61
|
+
return loaded.model.info();
|
|
62
|
+
}
|
|
63
|
+
/** Frees the encoder (once the call in progress ends); the next call loads it again. */
|
|
64
|
+
unload() {
|
|
65
|
+
return this.#slot.unload();
|
|
66
|
+
}
|
|
67
|
+
async doEmbed(options) {
|
|
68
|
+
const signal = options.abortSignal;
|
|
69
|
+
try {
|
|
70
|
+
const loaded = await this.#slot.acquire(signal, [this.#settings.onProgress]);
|
|
71
|
+
const info = loaded.model.info().embedding;
|
|
72
|
+
if (info === undefined) {
|
|
73
|
+
throw new WebslmError("UNSUPPORTED_TASK", `${this.modelId} is a language model; use webslm(id) for it, and an encoder for embeddings`);
|
|
74
|
+
}
|
|
75
|
+
const warnings = [];
|
|
76
|
+
if (options.dimensions !== undefined && options.dimensions !== info.dimensions) {
|
|
77
|
+
warnings.push({
|
|
78
|
+
type: "unsupported",
|
|
79
|
+
feature: "dimensions",
|
|
80
|
+
details: `${this.modelId} returns ${info.dimensions} dimensions`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const call = { ...pickCallSettings(this.#settings), ...callSettings(options) };
|
|
84
|
+
const result = await raceAbort(loaded.lock.run(async () => {
|
|
85
|
+
if (signal?.aborted === true)
|
|
86
|
+
throw abortReason(signal);
|
|
87
|
+
return loaded.model.embed(options.values, {
|
|
88
|
+
...call,
|
|
89
|
+
...(signal === undefined ? {} : { signal }),
|
|
90
|
+
});
|
|
91
|
+
}), signal);
|
|
92
|
+
return {
|
|
93
|
+
embeddings: result.vectors.map((v) => Array.from(v)),
|
|
94
|
+
usage: { tokens: result.tokens.reduce((a, b) => a + b, 0) },
|
|
95
|
+
warnings,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (signal?.aborted === true)
|
|
100
|
+
throw abortReason(signal);
|
|
101
|
+
if (error instanceof DOMException)
|
|
102
|
+
throw error;
|
|
103
|
+
throw toWebslmError(error);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function pickCallSettings(settings) {
|
|
108
|
+
return {
|
|
109
|
+
...(settings.pooling === undefined ? {} : { pooling: settings.pooling }),
|
|
110
|
+
...(settings.normalize === undefined ? {} : { normalize: settings.normalize }),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** webslm text-to-image models behind the AI SDK's `ImageModelV4` interface. */
|
|
2
|
+
import type { ImageModelV4, ImageModelV4CallOptions, ImageModelV4Result } from "@ai-sdk/provider";
|
|
3
|
+
import { type ImageModel, type LoadImageModelOptions } from "../image.js";
|
|
4
|
+
/** Most images one `doGenerate` call makes (they are generated one after the other). */
|
|
5
|
+
export declare const MAX_IMAGES_PER_CALL = 4;
|
|
6
|
+
/** Load options of an image model (not callbacks). */
|
|
7
|
+
export type WebslmImageLoadOptions = Omit<LoadImageModelOptions, "signal" | "onProgress">;
|
|
8
|
+
/** Settings of a webslm image model: load options and generation defaults. */
|
|
9
|
+
export interface WebslmImageModelSettings extends WebslmImageLoadOptions {
|
|
10
|
+
/** Denoising steps (default 1). `providerOptions.webslm.steps` overrides it. */
|
|
11
|
+
readonly steps?: number;
|
|
12
|
+
/** Classifier-free guidance scale (default 0). */
|
|
13
|
+
readonly guidance?: number;
|
|
14
|
+
readonly negativePrompt?: string;
|
|
15
|
+
/** Progress of the first load. */
|
|
16
|
+
readonly onProgress?: LoadImageModelOptions["onProgress"];
|
|
17
|
+
}
|
|
18
|
+
/** What loads image models (webslm's `loadImageModel` by default). */
|
|
19
|
+
export interface WebslmImageEngine {
|
|
20
|
+
loadImageModel(source: string, options: LoadImageModelOptions): Promise<ImageModel>;
|
|
21
|
+
}
|
|
22
|
+
/** One loaded image model, shared by the image models of a provider with the same id and options. */
|
|
23
|
+
export declare class ImageModelSlot {
|
|
24
|
+
#private;
|
|
25
|
+
constructor(engine: WebslmImageEngine, modelId: string, options: LoadImageModelOptions);
|
|
26
|
+
/** The model, loaded on first use; a failed load is retried by the next call. */
|
|
27
|
+
get(signal?: AbortSignal): Promise<ImageModel>;
|
|
28
|
+
unload(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The size of an `aspectRatio` (`"16:9"`): the longer side is `base`
|
|
32
|
+
* pixels, both sides multiples of `multiple`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function sizeOfAspectRatio(aspectRatio: string, base: number, multiple: number): {
|
|
35
|
+
width: number;
|
|
36
|
+
height: number;
|
|
37
|
+
} | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* A webslm text-to-image model for the AI SDK's `generateImage`. Images are
|
|
40
|
+
* PNG files; `n` images get seeds `seed`, `seed + 1`... (a random `seed`
|
|
41
|
+
* when none is given), reported in `providerMetadata.webslm.images`.
|
|
42
|
+
*/
|
|
43
|
+
export declare class WebslmImageModel implements ImageModelV4 {
|
|
44
|
+
#private;
|
|
45
|
+
readonly specificationVersion = "v4";
|
|
46
|
+
readonly provider = "webslm";
|
|
47
|
+
readonly modelId: string;
|
|
48
|
+
readonly maxImagesPerCall = 4;
|
|
49
|
+
readonly supportsFileInputs = false;
|
|
50
|
+
readonly supportsMaskInputs = false;
|
|
51
|
+
constructor(modelId: string, slot: ImageModelSlot, settings?: WebslmImageModelSettings);
|
|
52
|
+
doGenerate(options: ImageModelV4CallOptions): Promise<ImageModelV4Result>;
|
|
53
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/** webslm text-to-image models behind the AI SDK's `ImageModelV4` interface. */
|
|
2
|
+
import { toWebslmError } from "../errors.js";
|
|
3
|
+
import { loadImageModel } from "../image.js";
|
|
4
|
+
import { raceAbort } from "./loader.js";
|
|
5
|
+
const PROVIDER = "webslm";
|
|
6
|
+
/** Most images one `doGenerate` call makes (they are generated one after the other). */
|
|
7
|
+
export const MAX_IMAGES_PER_CALL = 4;
|
|
8
|
+
/** One loaded image model, shared by the image models of a provider with the same id and options. */
|
|
9
|
+
export class ImageModelSlot {
|
|
10
|
+
#engine;
|
|
11
|
+
#modelId;
|
|
12
|
+
#options;
|
|
13
|
+
#loading;
|
|
14
|
+
constructor(engine, modelId, options) {
|
|
15
|
+
this.#engine = engine;
|
|
16
|
+
this.#modelId = modelId;
|
|
17
|
+
this.#options = options;
|
|
18
|
+
}
|
|
19
|
+
/** The model, loaded on first use; a failed load is retried by the next call. */
|
|
20
|
+
get(signal) {
|
|
21
|
+
if (this.#loading === undefined) {
|
|
22
|
+
const loading = this.#engine.loadImageModel(this.#modelId, this.#options);
|
|
23
|
+
loading.catch(() => {
|
|
24
|
+
if (this.#loading === loading)
|
|
25
|
+
this.#loading = undefined;
|
|
26
|
+
});
|
|
27
|
+
this.#loading = loading;
|
|
28
|
+
}
|
|
29
|
+
return raceAbort(this.#loading, signal);
|
|
30
|
+
}
|
|
31
|
+
async unload() {
|
|
32
|
+
const loading = this.#loading;
|
|
33
|
+
this.#loading = undefined;
|
|
34
|
+
await loading?.then((model) => model.unload(), () => { });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** `providerOptions.webslm` of a call, read leniently. */
|
|
38
|
+
function callSettings(options) {
|
|
39
|
+
const raw = options.providerOptions?.[PROVIDER];
|
|
40
|
+
if (raw === undefined || raw === null || typeof raw !== "object")
|
|
41
|
+
return {};
|
|
42
|
+
const out = {};
|
|
43
|
+
if (typeof raw["steps"] === "number")
|
|
44
|
+
out.steps = raw["steps"];
|
|
45
|
+
if (typeof raw["guidance"] === "number")
|
|
46
|
+
out.guidance = raw["guidance"];
|
|
47
|
+
if (typeof raw["negativePrompt"] === "string")
|
|
48
|
+
out.negativePrompt = raw["negativePrompt"];
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/** Rounds `value` to a positive multiple of `multiple`. */
|
|
52
|
+
function roundTo(value, multiple) {
|
|
53
|
+
return Math.max(multiple, Math.round(value / multiple) * multiple);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The size of an `aspectRatio` (`"16:9"`): the longer side is `base`
|
|
57
|
+
* pixels, both sides multiples of `multiple`.
|
|
58
|
+
*/
|
|
59
|
+
export function sizeOfAspectRatio(aspectRatio, base, multiple) {
|
|
60
|
+
const match = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspectRatio);
|
|
61
|
+
if (match === null)
|
|
62
|
+
return undefined;
|
|
63
|
+
const w = Number(match[1]);
|
|
64
|
+
const h = Number(match[2]);
|
|
65
|
+
if (!(w > 0 && h > 0))
|
|
66
|
+
return undefined;
|
|
67
|
+
return w >= h
|
|
68
|
+
? { width: roundTo(base, multiple), height: roundTo((base * h) / w, multiple) }
|
|
69
|
+
: { width: roundTo((base * w) / h, multiple), height: roundTo(base, multiple) };
|
|
70
|
+
}
|
|
71
|
+
/** Default side of the images, in pixels. */
|
|
72
|
+
const DEFAULT_SIDE = 512;
|
|
73
|
+
/**
|
|
74
|
+
* A webslm text-to-image model for the AI SDK's `generateImage`. Images are
|
|
75
|
+
* PNG files; `n` images get seeds `seed`, `seed + 1`... (a random `seed`
|
|
76
|
+
* when none is given), reported in `providerMetadata.webslm.images`.
|
|
77
|
+
*/
|
|
78
|
+
export class WebslmImageModel {
|
|
79
|
+
specificationVersion = "v4";
|
|
80
|
+
provider = PROVIDER;
|
|
81
|
+
modelId;
|
|
82
|
+
maxImagesPerCall = MAX_IMAGES_PER_CALL;
|
|
83
|
+
supportsFileInputs = false;
|
|
84
|
+
supportsMaskInputs = false;
|
|
85
|
+
#slot;
|
|
86
|
+
#settings;
|
|
87
|
+
constructor(modelId, slot, settings = {}) {
|
|
88
|
+
this.modelId = modelId;
|
|
89
|
+
this.#slot = slot;
|
|
90
|
+
this.#settings = settings;
|
|
91
|
+
}
|
|
92
|
+
async doGenerate(options) {
|
|
93
|
+
const timestamp = new Date();
|
|
94
|
+
const warnings = [];
|
|
95
|
+
if (options.files !== undefined && options.files.length > 0) {
|
|
96
|
+
warnings.push({ type: "unsupported", feature: "files", details: "webslm generates images from text only" });
|
|
97
|
+
}
|
|
98
|
+
if (options.mask !== undefined) {
|
|
99
|
+
warnings.push({ type: "unsupported", feature: "mask", details: "webslm generates images from text only" });
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
const model = await this.#slot.get(options.abortSignal);
|
|
103
|
+
const multiple = model.info().sizeMultiple;
|
|
104
|
+
let size;
|
|
105
|
+
if (options.size !== undefined) {
|
|
106
|
+
const [w, h] = options.size.split("x").map(Number);
|
|
107
|
+
size = { width: w, height: h };
|
|
108
|
+
if (options.aspectRatio !== undefined) {
|
|
109
|
+
warnings.push({ type: "unsupported", feature: "aspectRatio", details: "size takes precedence" });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else if (options.aspectRatio !== undefined) {
|
|
113
|
+
size = sizeOfAspectRatio(options.aspectRatio, DEFAULT_SIDE, multiple);
|
|
114
|
+
if (size === undefined) {
|
|
115
|
+
warnings.push({ type: "unsupported", feature: "aspectRatio", details: `invalid ${options.aspectRatio}` });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const call = { ...this.#settings, ...callSettings(options) };
|
|
119
|
+
const n = Math.max(1, options.n);
|
|
120
|
+
const first = options.seed ?? Math.floor(Math.random() * 2 ** 31);
|
|
121
|
+
const images = [];
|
|
122
|
+
const metadata = [];
|
|
123
|
+
for (let i = 0; i < n; i++) {
|
|
124
|
+
const image = await model.generate(options.prompt ?? "", {
|
|
125
|
+
...size,
|
|
126
|
+
seed: first + i,
|
|
127
|
+
...(call.steps === undefined ? {} : { steps: call.steps }),
|
|
128
|
+
...(call.guidance === undefined ? {} : { guidance: call.guidance }),
|
|
129
|
+
...(call.negativePrompt === undefined ? {} : { negativePrompt: call.negativePrompt }),
|
|
130
|
+
...(options.abortSignal === undefined ? {} : { signal: options.abortSignal }),
|
|
131
|
+
});
|
|
132
|
+
images.push(await image.toPng());
|
|
133
|
+
metadata.push({ seed: image.seed, width: image.width, height: image.height, timeMs: image.timeMs });
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
images,
|
|
137
|
+
warnings,
|
|
138
|
+
providerMetadata: { [PROVIDER]: { images: metadata } },
|
|
139
|
+
response: { timestamp, modelId: this.modelId, headers: undefined },
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (options.abortSignal?.aborted === true)
|
|
144
|
+
throw error;
|
|
145
|
+
throw toWebslmError(error);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
package/dist/ai-sdk/index.d.ts
CHANGED
|
@@ -13,12 +13,39 @@
|
|
|
13
13
|
* });
|
|
14
14
|
* ```
|
|
15
15
|
*
|
|
16
|
+
* Encoders (BERT, ModernBERT, model2vec) are embedding models, behind
|
|
17
|
+
* `embed` and `embedMany`:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { embedMany } from "ai";
|
|
21
|
+
*
|
|
22
|
+
* const { embeddings } = await embedMany({
|
|
23
|
+
* model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
|
|
24
|
+
* values: ["sunny day at the beach", "rainy afternoon in the city"],
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Text-to-image models come from `webslm.imageModel(id)`, for the AI SDK's
|
|
29
|
+
* `generateImage`:
|
|
30
|
+
*
|
|
31
|
+
* ```ts
|
|
32
|
+
* import { generateImage } from "ai";
|
|
33
|
+
*
|
|
34
|
+
* const { image } = await generateImage({
|
|
35
|
+
* model: webslm.imageModel("IDKiro/sdxs-512-dreamshaper"),
|
|
36
|
+
* prompt: "a lighthouse at dusk",
|
|
37
|
+
* seed: 42,
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
16
41
|
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
17
42
|
* `webslm`: install them to use this entry point.
|
|
18
43
|
*
|
|
19
44
|
* @packageDocumentation
|
|
20
45
|
*/
|
|
21
46
|
import type { ProviderV4 } from "@ai-sdk/provider";
|
|
47
|
+
import { WebslmEmbeddingModel, type WebslmEmbeddingSettings } from "./embedding-model.js";
|
|
48
|
+
import { WebslmImageModel, type WebslmImageEngine, type WebslmImageModelSettings } from "./image-model.js";
|
|
22
49
|
import { WebslmLanguageModel, type WebslmModelSettings } from "./language-model.js";
|
|
23
50
|
import { type WebslmEngine, type WebslmLoadOptions } from "./loader.js";
|
|
24
51
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "../curated.js";
|
|
@@ -26,7 +53,10 @@ export { searchModels, type HubModel, type SearchModelsOptions } from "../hub.js
|
|
|
26
53
|
export { DEFAULT_MODEL } from "../simple.js";
|
|
27
54
|
export type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
|
|
28
55
|
export { WebslmLanguageModel, type WebslmCallSettings, type WebslmModelSettings, type WebslmPreloadOptions, } from "./language-model.js";
|
|
56
|
+
export { WebslmEmbeddingModel, type WebslmEmbeddingCallSettings, type WebslmEmbeddingSettings, } from "./embedding-model.js";
|
|
29
57
|
export type { WebslmEngine, WebslmLoadOptions } from "./loader.js";
|
|
58
|
+
export { MAX_IMAGES_PER_CALL, WebslmImageModel, type WebslmImageEngine, type WebslmImageLoadOptions, type WebslmImageModelSettings, } from "./image-model.js";
|
|
59
|
+
export { DEFAULT_IMAGE_MODEL } from "../image.js";
|
|
30
60
|
/** Options of {@link createWebslm}. */
|
|
31
61
|
export interface WebslmProviderSettings {
|
|
32
62
|
/**
|
|
@@ -36,6 +66,8 @@ export interface WebslmProviderSettings {
|
|
|
36
66
|
readonly loadOptions?: WebslmLoadOptions;
|
|
37
67
|
/** What loads the models (defaults to webslm's `loadModel`). */
|
|
38
68
|
readonly engine?: WebslmEngine;
|
|
69
|
+
/** What loads the image models (defaults to webslm's `loadImageModel`). */
|
|
70
|
+
readonly imageEngine?: WebslmImageEngine;
|
|
39
71
|
}
|
|
40
72
|
/**
|
|
41
73
|
* An AI SDK provider of webslm models. Call it with a Hugging Face
|
|
@@ -45,6 +77,13 @@ export interface WebslmProviderSettings {
|
|
|
45
77
|
export interface WebslmProvider extends ProviderV4 {
|
|
46
78
|
(modelId: string, settings?: WebslmModelSettings): WebslmLanguageModel;
|
|
47
79
|
languageModel(modelId: string, settings?: WebslmModelSettings): WebslmLanguageModel;
|
|
80
|
+
/** An encoder (BERT, ModernBERT, model2vec) as an embedding model, for `embed` and `embedMany`. */
|
|
81
|
+
embeddingModel(modelId: string, settings?: WebslmEmbeddingSettings): WebslmEmbeddingModel;
|
|
82
|
+
/**
|
|
83
|
+
* A text-to-image model (a `diffusers` pipeline repository); the image
|
|
84
|
+
* models of one id and the same load options share one loaded model.
|
|
85
|
+
*/
|
|
86
|
+
imageModel(modelId: string, settings?: WebslmImageModelSettings): WebslmImageModel;
|
|
48
87
|
/** Frees every model this provider loaded (each loads again on its next call). */
|
|
49
88
|
unloadAll(): Promise<void>;
|
|
50
89
|
}
|