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.
Files changed (45) hide show
  1. package/README.md +86 -3
  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 +39 -0
  7. package/dist/ai-sdk/index.js +66 -11
  8. package/dist/client.d.ts +6 -0
  9. package/dist/client.js +8 -1
  10. package/dist/download.js +2 -2
  11. package/dist/engine.js +187 -0
  12. package/dist/errors.d.ts +5 -0
  13. package/dist/errors.js +1 -0
  14. package/dist/fit.d.ts +2 -2
  15. package/dist/fit.js +5 -2
  16. package/dist/hub.d.ts +38 -3
  17. package/dist/hub.js +87 -8
  18. package/dist/image.d.ts +201 -0
  19. package/dist/image.js +353 -0
  20. package/dist/index.d.ts +6 -4
  21. package/dist/index.js +5 -3
  22. package/dist/memory.d.ts +24 -7
  23. package/dist/memory.js +49 -11
  24. package/dist/models.d.ts +19 -1
  25. package/dist/models.js +64 -7
  26. package/dist/native.d.ts +28 -0
  27. package/dist/protocol.d.ts +79 -2
  28. package/dist/simple.d.ts +4 -1
  29. package/dist/simple.js +9 -2
  30. package/dist/types.d.ts +87 -0
  31. package/dist/wasm.d.ts +2 -0
  32. package/native-manifest.json +29 -29
  33. package/package.json +1 -1
  34. package/wasm/relaxed/webslm_wasm.d.ts +72 -7
  35. package/wasm/relaxed/webslm_wasm.js +165 -19
  36. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  37. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +10 -3
  38. package/wasm/simd/webslm_wasm.d.ts +72 -7
  39. package/wasm/simd/webslm_wasm.js +165 -19
  40. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  41. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +10 -3
  42. package/wasm/threads/webslm_wasm.d.ts +73 -8
  43. package/wasm/threads/webslm_wasm.js +171 -25
  44. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  45. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +11 -4
package/dist/hub.js CHANGED
@@ -24,6 +24,11 @@ export const SUPPORTED_MODEL_TYPES = [
24
24
  "smolvlm",
25
25
  "lfm2_vl",
26
26
  ];
27
+ /**
28
+ * `model_type` values of the encoders the engine embeds with (BERT and
29
+ * MiniLM, ModernBERT and its descendants, model2vec static embeddings).
30
+ */
31
+ export const ENCODER_MODEL_TYPES = ["bert", "modernbert", "model2vec"];
27
32
  /** Files read besides the weights, when the repository has them. */
28
33
  export const CHECKPOINT_SIDE_FILES = [
29
34
  "config.json",
@@ -37,6 +42,12 @@ export const CHECKPOINT_SIDE_FILES = [
37
42
  "preprocessor_config.json",
38
43
  "processor_config.json",
39
44
  "video_preprocessor_config.json",
45
+ // Encoders: the sentence-transformers pipeline (pooling, normalization,
46
+ // sequence length).
47
+ "modules.json",
48
+ "sentence_bert_config.json",
49
+ "config_sentence_transformers.json",
50
+ "1_Pooling/config.json",
40
51
  ];
41
52
  export const SAFETENSORS_INDEX = "model.safetensors.index.json";
42
53
  export const SAFETENSORS_SINGLE = "model.safetensors";
@@ -85,6 +96,58 @@ export function isAdapterListing(names) {
85
96
  const present = new Set(names);
86
97
  return present.has(ADAPTER_CONFIG) && present.has(ADAPTER_WEIGHTS) && !present.has("config.json");
87
98
  }
99
+ /** The pipeline description at the root of a `diffusers` repository. */
100
+ export const MODEL_INDEX = "model_index.json";
101
+ /** Components a text-to-image pipeline reads (one weight file each). */
102
+ const PIPELINE_COMPONENTS = ["text_encoder", "unet", "vae"];
103
+ /** Small files of a text-to-image pipeline (`diffusion::PIPELINE_METADATA_FILES` in Rust). */
104
+ const PIPELINE_METADATA_FILES = [
105
+ MODEL_INDEX,
106
+ "scheduler/scheduler_config.json",
107
+ "tokenizer/vocab.json",
108
+ "tokenizer/merges.txt",
109
+ "tokenizer/tokenizer_config.json",
110
+ "tokenizer/special_tokens_map.json",
111
+ "text_encoder/config.json",
112
+ "unet/config.json",
113
+ "vae/config.json",
114
+ ];
115
+ /**
116
+ * Weight files of a pipeline component (`""` for a standalone component at
117
+ * the root, such as an autoencoder), the half-precision variant first.
118
+ */
119
+ function componentWeightCandidates(component) {
120
+ const stem = component === "text_encoder" ? "model" : "diffusion_pytorch_model";
121
+ const prefix = component === "" ? "" : `${component}/`;
122
+ return [`${prefix}${stem}.fp16.safetensors`, `${prefix}${stem}.safetensors`];
123
+ }
124
+ /** Whether a repository file list is a `diffusers` text-to-image pipeline. */
125
+ export function isImagePipelineListing(names) {
126
+ return names.includes(MODEL_INDEX);
127
+ }
128
+ /**
129
+ * The files of a `diffusers` pipeline or standalone component to download
130
+ * (`diffusion::needed_files` in Rust): a pipeline needs its metadata and
131
+ * one weight file per component, preferring half precision; a standalone
132
+ * autoencoder (`madebyollin/taesd`: a `config.json`, no tokenizer, and
133
+ * `diffusion_pytorch_model.safetensors`) its config and weights. `undefined`
134
+ * for other repositories; `weights` is empty when a component has none.
135
+ */
136
+ export function selectDiffusionFiles(names) {
137
+ const present = new Set(names);
138
+ const pick = (component) => componentWeightCandidates(component).find((f) => present.has(f));
139
+ if (present.has(MODEL_INDEX)) {
140
+ const side = PIPELINE_METADATA_FILES.filter((f) => present.has(f));
141
+ const weights = PIPELINE_COMPONENTS.map(pick);
142
+ return { side, weights: weights.every((w) => w !== undefined) ? weights : [] };
143
+ }
144
+ if (present.has("config.json") && !present.has("tokenizer.json")) {
145
+ const weights = pick("");
146
+ if (weights !== undefined)
147
+ return { side: ["config.json"], weights: [weights] };
148
+ }
149
+ return undefined;
150
+ }
88
151
  /**
89
152
  * The Hub endpoint: `hubUrl`, else `HF_ENDPOINT` from the environment (Node,
90
153
  * Bun, Deno; a mirror or a local stand-in, as for the `webslm` command-line
@@ -197,13 +260,19 @@ function parseGated(value) {
197
260
  * weights (the shards named by the index, `model.safetensors`, or every
198
261
  * top-level `*.safetensors`). `index` is the parsed index when there is one.
199
262
  * With `gguf`, or for a repository without safetensors weights, the weights
200
- * are one GGUF file ({@link pickGgufFile}).
263
+ * are one GGUF file ({@link pickGgufFile}). A text-to-image pipeline gets
264
+ * the files {@link selectDiffusionFiles} picks.
201
265
  */
202
266
  export function selectCheckpointFiles(names, index, gguf) {
203
267
  // A LoRA adapter needs only its two files.
204
268
  if (isAdapterListing(names))
205
269
  return { side: [ADAPTER_CONFIG], weights: [ADAPTER_WEIGHTS] };
206
270
  const present = new Set(names);
271
+ if (gguf === undefined) {
272
+ const diffusion = selectDiffusionFiles(names);
273
+ if (diffusion !== undefined)
274
+ return diffusion;
275
+ }
207
276
  const side = CHECKPOINT_SIDE_FILES.filter((f) => present.has(f));
208
277
  const hasSafetensors = present.has(SAFETENSORS_INDEX) || names.some((n) => !n.includes("/") && n.endsWith(".safetensors"));
209
278
  const ggufFile = gguf ?? (hasSafetensors ? undefined : pickGgufFile(names));
@@ -218,8 +287,11 @@ export function selectCheckpointFiles(names, index, gguf) {
218
287
  const weights = names.filter((n) => !n.includes("/") && n.endsWith(".safetensors")).sort();
219
288
  return { side, weights };
220
289
  }
221
- /** Why an embedding, reranker or classifier checkpoint is refused. */
222
- export const EMBEDDING_REASON = "embedding model, see #17";
290
+ /**
291
+ * Why an embedding, reranker or classifier checkpoint of an architecture
292
+ * other than the supported encoders is refused.
293
+ */
294
+ export const EMBEDDING_REASON = "embedding model of an unsupported architecture (webslm embeds with BERT, ModernBERT and model2vec)";
223
295
  const ENCODER_PIPELINES = ["feature-extraction", "sentence-similarity", "text-ranking", "text-classification"];
224
296
  /**
225
297
  * Whether a repository holds an embedding, reranker or classification model
@@ -277,7 +349,7 @@ export function estimateMemory(params) {
277
349
  export function unsupportedReason(modelType) {
278
350
  if (modelType === undefined)
279
351
  return "no config.json model_type published";
280
- if (SUPPORTED_MODEL_TYPES.includes(modelType))
352
+ if (SUPPORTED_MODEL_TYPES.includes(modelType) || ENCODER_MODEL_TYPES.includes(modelType))
281
353
  return undefined;
282
354
  return `architecture "${modelType}" is not supported yet`;
283
355
  }
@@ -335,7 +407,8 @@ function toHubModel(entry, maxParams) {
335
407
  const ggufType = ggufArchitecture === undefined ? undefined : GGUF_ARCHITECTURES[ggufArchitecture];
336
408
  const ggufTotal = entry.gguf?.total;
337
409
  const params = typeof total === "number" ? total : typeof ggufTotal === "number" && ggufType !== undefined ? ggufTotal : undefined;
338
- const embedding = isEmbeddingModel({
410
+ const encoder = modelType !== undefined && ENCODER_MODEL_TYPES.includes(modelType);
411
+ const embedding = encoder || isEmbeddingModel({
339
412
  repo: entry.id,
340
413
  pipelineTag: typeof entry.pipeline_tag === "string" ? entry.pipeline_tag : undefined,
341
414
  libraryName: typeof entry.library_name === "string" ? entry.library_name : undefined,
@@ -343,7 +416,7 @@ function toHubModel(entry, maxParams) {
343
416
  });
344
417
  // GGUF files of a supported architecture run whatever else the repository holds.
345
418
  const gguf = ggufType !== undefined && SUPPORTED_MODEL_TYPES.includes(ggufType);
346
- let reason = embedding ? EMBEDDING_REASON : gguf ? undefined : unsupportedReason(modelType);
419
+ let reason = embedding && !encoder ? EMBEDDING_REASON : gguf ? undefined : unsupportedReason(modelType);
347
420
  if (reason === undefined && params === undefined)
348
421
  reason = "no safetensors weights";
349
422
  if (reason === undefined && !gguf)
@@ -362,6 +435,8 @@ function toHubModel(entry, maxParams) {
362
435
  model.modelType = ggufType;
363
436
  if (gguf)
364
437
  model.gguf = true;
438
+ if (embedding)
439
+ model.embedding = true;
365
440
  if (architectures !== undefined)
366
441
  model.architectures = architectures;
367
442
  if (params !== undefined) {
@@ -437,7 +512,9 @@ export async function checkModel(repo, options = {}) {
437
512
  else {
438
513
  reasons.push("no config.json");
439
514
  }
440
- if (isEmbeddingModel({ repo, files: names }))
515
+ const encoder = modelType !== undefined && ENCODER_MODEL_TYPES.includes(modelType);
516
+ const embedding = encoder || isEmbeddingModel({ repo, files: names });
517
+ if (embedding && !encoder)
441
518
  reasons.unshift(EMBEDDING_REASON);
442
519
  const hasTokenizer = names.includes("tokenizer.json");
443
520
  if (!hasTokenizer)
@@ -469,7 +546,7 @@ export async function checkModel(repo, options = {}) {
469
546
  hasEmbeddings = true;
470
547
  }
471
548
  }
472
- if (selected.weights.length > 0 && !hasEmbeddings) {
549
+ if (selected.weights.length > 0 && !hasEmbeddings && !encoder) {
473
550
  reasons.push("unexpected weight layout (no model.embed_tokens.weight)");
474
551
  }
475
552
  const packed = packedWeightsReason(dtypes);
@@ -495,6 +572,8 @@ export async function checkModel(repo, options = {}) {
495
572
  };
496
573
  if (modelType !== undefined)
497
574
  check.modelType = modelType;
575
+ if (embedding)
576
+ check.embedding = true;
498
577
  if (config !== undefined) {
499
578
  check.config = config;
500
579
  if (shapes.length > 0) {
@@ -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>>;