webslm 0.7.0 → 0.10.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.
Files changed (45) hide show
  1. package/README.md +116 -2
  2. package/dist/ai-sdk/embedding-model.d.ts +52 -0
  3. package/dist/ai-sdk/embedding-model.js +112 -0
  4. package/dist/ai-sdk/image-model.d.ts +53 -0
  5. package/dist/ai-sdk/image-model.js +148 -0
  6. package/dist/ai-sdk/index.d.ts +54 -0
  7. package/dist/ai-sdk/index.js +85 -11
  8. package/dist/ai-sdk/transcription-model.d.ts +48 -0
  9. package/dist/ai-sdk/transcription-model.js +115 -0
  10. package/dist/audio.d.ts +33 -0
  11. package/dist/audio.js +87 -0
  12. package/dist/client.d.ts +6 -0
  13. package/dist/client.js +8 -1
  14. package/dist/download.js +2 -2
  15. package/dist/engine.js +233 -0
  16. package/dist/errors.d.ts +5 -0
  17. package/dist/errors.js +1 -0
  18. package/dist/hub.d.ts +47 -3
  19. package/dist/hub.js +97 -8
  20. package/dist/image.d.ts +201 -0
  21. package/dist/image.js +353 -0
  22. package/dist/index.d.ts +6 -3
  23. package/dist/index.js +5 -2
  24. package/dist/models.d.ts +37 -1
  25. package/dist/models.js +99 -6
  26. package/dist/native.d.ts +34 -0
  27. package/dist/protocol.d.ts +106 -2
  28. package/dist/simple.d.ts +4 -1
  29. package/dist/simple.js +9 -2
  30. package/dist/types.d.ts +107 -1
  31. package/dist/wasm.d.ts +4 -0
  32. package/native-manifest.json +29 -29
  33. package/package.json +1 -1
  34. package/wasm/relaxed/webslm_wasm.d.ts +97 -6
  35. package/wasm/relaxed/webslm_wasm.js +223 -18
  36. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  37. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +13 -3
  38. package/wasm/simd/webslm_wasm.d.ts +97 -6
  39. package/wasm/simd/webslm_wasm.js +223 -18
  40. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  41. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +13 -3
  42. package/wasm/threads/webslm_wasm.d.ts +98 -7
  43. package/wasm/threads/webslm_wasm.js +228 -23
  44. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  45. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +14 -4
@@ -0,0 +1,201 @@
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 { EngineHandle } from "./models.js";
12
+ import type { WireImageOptions } from "./protocol.js";
13
+ import type { Backend, Device, LoadProgress, ModelSource } from "./types.js";
14
+ import type { WasmFlavour } from "./wasm-flavour.js";
15
+ /**
16
+ * A one-step distilled Stable Diffusion model (SDXS, 512×512, a tiny
17
+ * autoencoder): what {@link generateImage} loads by default.
18
+ */
19
+ export declare const DEFAULT_IMAGE_MODEL = "IDKiro/sdxs-512-dreamshaper";
20
+ /**
21
+ * How the pipeline's weights are stored once loaded: half precision (the
22
+ * default) halves the memory of f32 checkpoints for a negligible change in
23
+ * the image.
24
+ */
25
+ export type ImageQuant = "f16" | "f32" | "q8";
26
+ /** Where a generation is. */
27
+ export type ImagePhase = "encoding" | "denoising" | "decoding";
28
+ /** Progress of {@link ImageModel.generate}. */
29
+ export interface ImageProgress {
30
+ readonly phase: ImagePhase;
31
+ /** Denoising steps done. */
32
+ readonly step: number;
33
+ readonly steps: number;
34
+ }
35
+ /** What {@link ImageModel.info} reports. */
36
+ export interface ImageModelInfo {
37
+ /** The pipeline class, e.g. `"StableDiffusionPipeline"`. */
38
+ readonly pipeline: string;
39
+ /** `"tiny"` (TAESD) or `"kl"` (the full VAE). */
40
+ readonly decoder: "tiny" | "kl";
41
+ /** The scheduler class, e.g. `"EulerDiscreteScheduler"`. */
42
+ readonly scheduler: string;
43
+ /** Width and height must be multiples of it. */
44
+ readonly sizeMultiple: number;
45
+ /** `"webgpu"` (WebAssembly engine), `"gpu"` (native engine) or `"cpu"`. */
46
+ readonly device: "webgpu" | "gpu" | "cpu";
47
+ /** What runs it, e.g. `"WebGPU (apple)"`. */
48
+ readonly backend: string;
49
+ /** `"wasm"` or `"native"` (Node). */
50
+ readonly runtime: "wasm" | "native";
51
+ /** The storage format of the weights. */
52
+ readonly quant: string;
53
+ readonly repo?: string;
54
+ readonly revision?: string;
55
+ /** Why the requested device was not used, when it was not. */
56
+ readonly deviceNote?: string;
57
+ /** Why the native engine was not used, when it was not. */
58
+ readonly runtimeNote?: string;
59
+ readonly fromCache: boolean;
60
+ readonly loadTimeMs: number;
61
+ }
62
+ /** Options of {@link loadImageModel}. */
63
+ export interface LoadImageModelOptions {
64
+ /** Defaults to `"f16"`. */
65
+ readonly quant?: ImageQuant;
66
+ /**
67
+ * Defaults to `"auto"`: the GPU whenever one is available (image models are
68
+ * compute-bound), the CPU otherwise.
69
+ */
70
+ readonly device?: Device;
71
+ /** The engine build in Node (see {@link Backend}). */
72
+ readonly backend?: Backend;
73
+ /**
74
+ * A standalone autoencoder replacing the pipeline's decoder, e.g.
75
+ * `"madebyollin/taesd"` (a tiny decoder: fast previews of a Stable
76
+ * Diffusion 1.x or 2.x pipeline).
77
+ */
78
+ readonly decoder?: string | ModelSource;
79
+ readonly revision?: string;
80
+ /** Hugging Face token for gated or private repositories. */
81
+ readonly token?: string;
82
+ /** Node: the cache directory (defaults to the command-line tool's). */
83
+ readonly cacheDir?: string;
84
+ readonly onProgress?: (progress: LoadProgress) => void;
85
+ readonly signal?: AbortSignal;
86
+ /** Run the engine on the calling thread instead of a worker. */
87
+ readonly worker?: boolean;
88
+ /** An engine shared with other models (see `createEngine`). */
89
+ readonly engine?: EngineHandle;
90
+ readonly wasmFlavour?: WasmFlavour;
91
+ readonly threads?: number;
92
+ }
93
+ /** Options of {@link ImageModel.generate}. */
94
+ export interface ImageGenerationOptions {
95
+ /** Width in pixels (default 512), a multiple of {@link ImageModelInfo.sizeMultiple}. */
96
+ readonly width?: number;
97
+ /** Height in pixels (default 512). */
98
+ readonly height?: number;
99
+ /** Both sides: `512`, or `"768x512"` (width × height). */
100
+ readonly size?: number | `${number}x${number}`;
101
+ /** Denoising steps (default 1: one-step models such as SDXS). */
102
+ readonly steps?: number;
103
+ /**
104
+ * Classifier-free guidance scale (default 0: none, as distilled models
105
+ * expect). Above 1, the model also runs on `negativePrompt`.
106
+ */
107
+ readonly guidance?: number;
108
+ /** Seed of the initial noise: the same seed gives the same image. Random when omitted. */
109
+ readonly seed?: number;
110
+ /** What the image should not show (with `guidance` above 1). */
111
+ readonly negativePrompt?: string;
112
+ readonly onProgress?: (progress: ImageProgress) => void;
113
+ readonly signal?: AbortSignal;
114
+ }
115
+ /** A generated image: 8-bit RGBA pixels, row-major. */
116
+ export declare class GeneratedImage {
117
+ readonly width: number;
118
+ readonly height: number;
119
+ /** The seed it was generated with. */
120
+ readonly seed: number;
121
+ /** `width * height * 4` bytes, as `ImageData` holds them. */
122
+ readonly data: Uint8ClampedArray<ArrayBuffer>;
123
+ /** Time the generation took, in milliseconds. */
124
+ readonly timeMs: number;
125
+ /** @internal */
126
+ constructor(width: number, height: number, seed: number, data: Uint8ClampedArray<ArrayBuffer>, timeMs?: number);
127
+ /** The pixels as an `ImageData`, for `CanvasRenderingContext2D.putImageData`. */
128
+ toImageData(): ImageData;
129
+ /** The image as an `ImageBitmap`, to draw on a canvas or transfer to a worker. */
130
+ toImageBitmap(): Promise<ImageBitmap>;
131
+ /** The image as a PNG file. */
132
+ toPng(): Promise<Uint8Array<ArrayBuffer>>;
133
+ /** The image as a PNG `Blob`, e.g. for `URL.createObjectURL`. */
134
+ toBlob(): Promise<Blob>;
135
+ }
136
+ /** The image options sent to the engine (a random seed when none is given). */
137
+ export declare function wireImageOptions(options: ImageGenerationOptions): WireImageOptions;
138
+ /** A loaded text-to-image pipeline. */
139
+ export declare class ImageModel {
140
+ #private;
141
+ /** @internal */
142
+ constructor(client: EngineClient, modelId: number, info: ImageModelInfo, ownsEngine?: boolean);
143
+ /** The pipeline, the device it runs on and the weight format. */
144
+ info(): ImageModelInfo;
145
+ /**
146
+ * Generates an image of `prompt`. Generations of one model run one after
147
+ * the other. `signal` stops one before its next step (it rejects with
148
+ * `ABORTED`).
149
+ *
150
+ * ```ts
151
+ * const image = await model.generate("a lighthouse at dusk, oil painting", { seed: 42 });
152
+ * canvas.getContext("2d")!.putImageData(image.toImageData(), 0, 0);
153
+ * ```
154
+ */
155
+ generate(prompt: string, options?: ImageGenerationOptions): Promise<GeneratedImage>;
156
+ /** Frees the model and stops its worker (unless it runs in a shared engine). */
157
+ unload(): Promise<void>;
158
+ }
159
+ /**
160
+ * Loads a text-to-image pipeline from the Hugging Face Hub (or local files,
161
+ * or a custom store), downloaded once into the cache like language models.
162
+ *
163
+ * ```ts
164
+ * import { loadImageModel } from "webslm";
165
+ *
166
+ * const model = await loadImageModel("IDKiro/sdxs-512-dreamshaper");
167
+ * const image = await model.generate("a red fox in the snow", { seed: 7 });
168
+ * document.body.append(Object.assign(document.createElement("img"), {
169
+ * src: URL.createObjectURL(await image.toBlob()),
170
+ * }));
171
+ * ```
172
+ */
173
+ export declare function loadImageModel(source?: string | ModelSource, options?: LoadImageModelOptions): Promise<ImageModel>;
174
+ /** Options of {@link generateImage}. */
175
+ export interface GenerateImageOptions extends ImageGenerationOptions {
176
+ /**
177
+ * A repository id (default {@link DEFAULT_IMAGE_MODEL}), loaded on first
178
+ * use with the default options and kept for later calls (see
179
+ * {@link unloadImageModels}), or a loaded {@link ImageModel}.
180
+ */
181
+ readonly model?: string | ImageModel;
182
+ }
183
+ /**
184
+ * Generates an image of `prompt` with a model loaded on first use and kept
185
+ * for later calls.
186
+ *
187
+ * ```ts
188
+ * import { generateImage } from "webslm";
189
+ *
190
+ * const image = await generateImage("a watercolor of a fox", { seed: 42 });
191
+ * const bitmap = await image.toImageBitmap();
192
+ * ```
193
+ */
194
+ export declare function generateImage(prompt: string, options?: GenerateImageOptions): Promise<GeneratedImage>;
195
+ /** Unloads every model loaded by {@link generateImage}. */
196
+ export declare function unloadImageModels(): Promise<void>;
197
+ /**
198
+ * Encodes 8-bit RGBA pixels (row-major, `width * height * 4` bytes) as a
199
+ * PNG file.
200
+ */
201
+ export declare function encodePng(width: number, height: number, rgba: ArrayLike<number>): Promise<Uint8Array<ArrayBuffer>>;
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,21 @@
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, AudioInput, 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, SpeechInfo, StepOptions, TranscribeOptions, Transcription, TranscriptionSegment, } from "./types.js";
24
+ export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
22
25
  export { WebslmError, type WebslmErrorCode } from "./errors.js";
23
26
  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";
27
+ export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, SPEECH_MODEL_TYPES, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
25
28
  export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
26
29
  export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
27
30
  export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
package/dist/index.js CHANGED
@@ -10,17 +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 { 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";
23
+ export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
21
24
  export { WebslmError } from "./errors.js";
22
25
  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";
26
+ export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, SPEECH_MODEL_TYPES, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
24
27
  export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
25
28
  export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
26
29
  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 { AdapterSource, Backend, ApplyAdapterOptions, ChatInputMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
4
+ import type { WireSource } from "./protocol.js";
5
+ import type { AdapterSource, Backend, ApplyAdapterOptions, AudioInput, ChatInputMessage, ChatStream, CompletionOptions, Device, EmbedOptions, Embeddings, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, TranscribeOptions, Transcription } 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,39 @@ 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>;
214
+ /**
215
+ * Transcribes speech with a speech recognition model (Whisper; see
216
+ * {@link ModelInfo.speech}), 30 s at a time, decoding greedily as
217
+ * `transformers` does. `audio` is mono PCM (`Float32Array`, at
218
+ * `options.sampleRate`, 16 kHz by default) or an audio file: WAV
219
+ * everywhere, any format the browser decodes in a page (see
220
+ * {@link AudioInput}). The language is detected unless given;
221
+ * `task: "translate"` translates into English. Rejects with
222
+ * `UNSUPPORTED_TASK` on other models, and with `ABORTED` when
223
+ * `options.signal` fires.
224
+ *
225
+ * ```ts
226
+ * const model = await loadModel("openai/whisper-tiny");
227
+ * const file = await fetch("/speech.mp3").then((r) => r.blob());
228
+ * const { text, language } = await model.transcribe(file, { onToken: (t) => output.append(t) });
229
+ * ```
230
+ */
231
+ transcribe(audio: AudioInput, options?: TranscribeOptions): Promise<Transcription>;
196
232
  /** Starts an independent session (its own KV cache) for low-level use. */
197
233
  session(): Promise<Session>;
198
234
  /**