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
package/dist/models.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
2
  import { AsyncQueue } from "./async-queue.js";
3
+ import { prepareAudio } from "./audio.js";
3
4
  import { EngineClient } from "./client.js";
4
5
  import { recommendedSampling } from "./curated.js";
5
6
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
@@ -139,8 +140,8 @@ export function normalizeSource(source, revision) {
139
140
  if (file !== undefined && !(file in files)) {
140
141
  throw new WebslmError("INVALID_ARGUMENT", `\`files\` has no "${file}"`);
141
142
  }
142
- // A GGUF file carries its configuration.
143
- if (!("config.json" in files) && !Object.keys(files).some(isGgufFile)) {
143
+ // A GGUF file carries its configuration; a text-to-image pipeline has a model_index.json.
144
+ if (!("config.json" in files) && !("model_index.json" in files) && !Object.keys(files).some(isGgufFile)) {
144
145
  throw new WebslmError("INVALID_ARGUMENT", "`files` must include config.json or a .gguf file");
145
146
  }
146
147
  return { kind: "files", files, ...withFile };
@@ -170,8 +171,8 @@ export function normalizeAdapterSource(source, revision) {
170
171
  }
171
172
  return normalizeSource(source, revision);
172
173
  }
173
- /** The form of a normalized source posted to the engine. */
174
- function toWire(normalized, token) {
174
+ /** @internal The form of a normalized source posted to the engine. */
175
+ export function toWire(normalized, token) {
175
176
  switch (normalized.kind) {
176
177
  case "hub":
177
178
  return {
@@ -271,6 +272,7 @@ export async function loadModel(source, options = {}) {
271
272
  options: {
272
273
  quant,
273
274
  ...(requested === "auto" ? { autoQuant: true } : {}),
275
+ ...(options.quant === undefined ? { defaultQuant: true } : {}),
274
276
  device,
275
277
  ...(backend === "auto" ? {} : { backend }),
276
278
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
@@ -294,8 +296,11 @@ export async function loadModel(source, options = {}) {
294
296
  ...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
295
297
  });
296
298
  // The native engine chose the format again, from the machine's memory
297
- // (its own note says why when it did not load q8).
298
- const info = quantNote === undefined || result.info.runtime === "native" ? result.info : { ...result.info, quantNote };
299
+ // (its own note says why when it did not load q8); an encoder loads in
300
+ // f32 under `auto`.
301
+ const info = quantNote === undefined || result.info.runtime === "native" || result.info.embedding !== undefined
302
+ ? result.info
303
+ : { ...result.info, quantNote };
299
304
  return new Model(client, result.model, info, {
300
305
  ...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
301
306
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
@@ -749,6 +754,94 @@ export class Model extends Conversation {
749
754
  this.#info = info;
750
755
  return removed ?? undefined;
751
756
  }
757
+ /**
758
+ * Embeds texts with an encoder (an embedding model: BERT, ModernBERT,
759
+ * model2vec; see {@link ModelInfo.embedding}): one vector per text,
760
+ * pooled and normalized as the checkpoint's sentence-transformers
761
+ * settings say unless `options` say otherwise. Texts longer than the
762
+ * model's limit are cut. Rejects with `UNSUPPORTED_TASK` on a language
763
+ * model.
764
+ *
765
+ * ```ts
766
+ * const model = await loadModel("sentence-transformers/all-MiniLM-L6-v2");
767
+ * const { vectors } = await model.embed(["A cat sleeps.", "A kitten naps."]);
768
+ * const cosine = vectors[0].reduce((s, v, i) => s + v * vectors[1][i], 0);
769
+ * ```
770
+ */
771
+ async embed(texts, options = {}) {
772
+ const list = typeof texts === "string" ? [texts] : [...texts];
773
+ if (list.some((t) => typeof t !== "string")) {
774
+ throw new WebslmError("INVALID_ARGUMENT", "embed takes a string or an array of strings");
775
+ }
776
+ if (this.#info.embedding === undefined) {
777
+ const kind = this.#info.speech === undefined ? "a language model" : "a speech recognition model";
778
+ throw new WebslmError("UNSUPPORTED_TASK", `${this.#info.repo ?? this.#info.modelType} is ${kind}; embed needs an embedding model`);
779
+ }
780
+ const result = await this.client.request({
781
+ type: "embed",
782
+ model: this.modelId,
783
+ texts: list,
784
+ options: {
785
+ ...(options.pooling === undefined ? {} : { pooling: options.pooling }),
786
+ ...(options.normalize === undefined ? {} : { normalize: options.normalize }),
787
+ },
788
+ }, options.signal === undefined ? {} : { signal: options.signal });
789
+ const { data, dimensions } = result;
790
+ const vectors = list.map((_, i) => data.subarray(i * dimensions, (i + 1) * dimensions));
791
+ return { vectors, data, dimensions, tokens: Array.from(result.tokens) };
792
+ }
793
+ /**
794
+ * Transcribes speech with a speech recognition model (Whisper; see
795
+ * {@link ModelInfo.speech}), 30 s at a time, decoding greedily as
796
+ * `transformers` does. `audio` is mono PCM (`Float32Array`, at
797
+ * `options.sampleRate`, 16 kHz by default) or an audio file: WAV
798
+ * everywhere, any format the browser decodes in a page (see
799
+ * {@link AudioInput}). The language is detected unless given;
800
+ * `task: "translate"` translates into English. Rejects with
801
+ * `UNSUPPORTED_TASK` on other models, and with `ABORTED` when
802
+ * `options.signal` fires.
803
+ *
804
+ * ```ts
805
+ * const model = await loadModel("openai/whisper-tiny");
806
+ * const file = await fetch("/speech.mp3").then((r) => r.blob());
807
+ * const { text, language } = await model.transcribe(file, { onToken: (t) => output.append(t) });
808
+ * ```
809
+ */
810
+ async transcribe(audio, options = {}) {
811
+ if (this.#info.speech === undefined) {
812
+ throw new WebslmError("UNSUPPORTED_TASK", `${this.#info.repo ?? this.#info.modelType} is not a speech recognition model; transcribe needs one (Whisper)`);
813
+ }
814
+ if (options.task !== undefined && options.task !== "transcribe" && options.task !== "translate") {
815
+ throw new WebslmError("INVALID_ARGUMENT", 'task must be "transcribe" or "translate"');
816
+ }
817
+ if (isAborted(options.signal))
818
+ throw abortError(options.signal);
819
+ const prepared = await prepareAudio(audio, options.sampleRate);
820
+ const onToken = options.onToken;
821
+ const result = await this.client.request({
822
+ type: "transcribe",
823
+ model: this.modelId,
824
+ audio: prepared.audio,
825
+ options: {
826
+ ...(options.language === undefined ? {} : { language: options.language }),
827
+ ...(options.task === undefined ? {} : { task: options.task }),
828
+ ...(options.maxNewTokens === undefined ? {} : { maxNewTokens: options.maxNewTokens }),
829
+ ...(prepared.sampleRate === undefined ? {} : { sampleRate: prepared.sampleRate }),
830
+ },
831
+ }, {
832
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
833
+ ...(onToken === undefined ? {} : { onDelta: (delta) => onToken(delta.text) }),
834
+ });
835
+ if (result.stopped && isAborted(options.signal))
836
+ throw abortError(options.signal);
837
+ return {
838
+ text: result.text,
839
+ ...(result.language === null ? {} : { language: result.language }),
840
+ duration: result.duration,
841
+ segments: result.segments,
842
+ tokens: result.tokens,
843
+ };
844
+ }
752
845
  /** Starts an independent session (its own KV cache) for low-level use. */
753
846
  async session() {
754
847
  const id = await this.client.request({ type: "createSession", model: this.modelId });
package/dist/native.d.ts CHANGED
@@ -56,6 +56,23 @@ export interface NativeLoadArgs {
56
56
  readonly threads?: number;
57
57
  }
58
58
  /** A model loaded by the native engine. */
59
+ /** Settings of an image model load that only the native engine has. */
60
+ export interface NativeImageLoadArgs {
61
+ /** Directory of a standalone autoencoder replacing the pipeline's decoder. */
62
+ readonly decoderDir?: string;
63
+ readonly threads?: number;
64
+ }
65
+ /** A text-to-image pipeline on the native engine. */
66
+ export interface NativeImageModel {
67
+ info(): Record<string, unknown>;
68
+ generate(prompt: string, optionsJson: string, onProgress?: ((phase: string, step: number, steps: number) => void) | null, cancel?: NativeCancelToken | null): Promise<{
69
+ width: number;
70
+ height: number;
71
+ seed: number;
72
+ rgba: Uint8Array;
73
+ }>;
74
+ free(): void;
75
+ }
59
76
  export interface NativeModel {
60
77
  info(): NativeModelInfo;
61
78
  applyAdapter(dir: string, optionsJson: string): Promise<unknown>;
@@ -68,12 +85,25 @@ export interface NativeModel {
68
85
  tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
69
86
  detokenize(ids: Uint32Array, skipSpecialTokens: boolean): Promise<string>;
70
87
  renderChat(messagesJson: string, kwargsJson: string): Promise<string>;
88
+ /** Encoders only (`UNSUPPORTED_TASK` otherwise). */
89
+ embed(textsJson: string, optionsJson: string): Promise<{
90
+ data: Float32Array;
91
+ dimensions: number;
92
+ tokens: Uint32Array;
93
+ }>;
94
+ /**
95
+ * Speech recognition models only (`UNSUPPORTED_TASK` otherwise). Resolves
96
+ * to the transcription and `pieces`, the number of `onText` calls (they
97
+ * can arrive after the result).
98
+ */
99
+ transcribe?(audio: Float32Array | Uint8Array, optionsJson: string, onText: ((text: string) => void) | null, cancel: NativeCancelToken | null): Promise<unknown>;
71
100
  free(): void;
72
101
  }
73
102
  /** The exports of the addon. */
74
103
  export interface NativeAddon {
75
104
  version(): string;
76
105
  supportedModelTypes(): string[];
106
+ supportedEncoderTypes(): string[];
77
107
  buildInfo(): {
78
108
  version: string;
79
109
  target: string;
@@ -83,6 +113,10 @@ export interface NativeAddon {
83
113
  readonly NativeModel: {
84
114
  load(dir: string, optionsJson: string, args?: NativeLoadArgs | null): Promise<NativeModel>;
85
115
  };
116
+ /** Absent from addons older than text-to-image support. */
117
+ readonly NativeImageModel?: {
118
+ load(dir: string, optionsJson: string, args?: NativeImageLoadArgs | null): Promise<NativeImageModel>;
119
+ };
86
120
  readonly CancelToken: new () => NativeCancelToken;
87
121
  }
88
122
  /** Where the addon came from, or why it could not load. */
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { SerializedError } from "./errors.js";
9
9
  import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
10
+ import type { ImageModelInfo, ImagePhase, ImageQuant } from "./image.js";
10
11
  import type { KvCacheType } from "./memory.js";
11
12
  import type { WasmFlavour } from "./wasm-flavour.js";
12
13
  /** A model source in a form that can be posted to a worker. */
@@ -36,6 +37,11 @@ export interface WireLoadOptions {
36
37
  * machine's memory and GPU.
37
38
  */
38
39
  readonly autoQuant?: boolean;
40
+ /**
41
+ * `quant` is the default, not the caller's choice: an encoder then loads
42
+ * in f32 (small models, embeddings compared across texts).
43
+ */
44
+ readonly defaultQuant?: boolean;
39
45
  /** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`; the engine reports what it used. */
40
46
  readonly device?: string;
41
47
  /** `"auto"` (default), `"native"` or `"wasm"`. */
@@ -56,6 +62,25 @@ export interface WireLoadOptions {
56
62
  readonly wasmFlavour?: WasmFlavour;
57
63
  readonly threads?: number;
58
64
  }
65
+ /** Load options of a text-to-image pipeline. */
66
+ export interface WireImageLoadOptions {
67
+ readonly quant: ImageQuant;
68
+ /** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`. */
69
+ readonly device?: string;
70
+ readonly backend?: Backend;
71
+ readonly cacheDir?: string;
72
+ readonly wasmFlavour?: WasmFlavour;
73
+ readonly threads?: number;
74
+ }
75
+ /** Image options as sent to the engine (no signal). */
76
+ export interface WireImageOptions {
77
+ readonly width?: number;
78
+ readonly height?: number;
79
+ readonly steps?: number;
80
+ readonly guidance?: number;
81
+ readonly seed?: number;
82
+ readonly negativePrompt?: string;
83
+ }
59
84
  /** Generation options as sent to the engine (no signal). */
60
85
  export interface WireGenerateOptions {
61
86
  readonly maxTokens?: number;
@@ -209,6 +234,31 @@ export type Request = WithId<{
209
234
  readonly model: number;
210
235
  readonly messages: readonly WireMessage[];
211
236
  readonly templateKwargs: Readonly<Record<string, unknown>>;
237
+ } | {
238
+ readonly type: "embed";
239
+ readonly model: number;
240
+ readonly texts: readonly string[];
241
+ readonly options: {
242
+ readonly pooling?: string;
243
+ readonly normalize?: boolean;
244
+ };
245
+ } | {
246
+ readonly type: "loadImage";
247
+ readonly source: WireSource;
248
+ /** A standalone autoencoder replacing the pipeline's decoder. */
249
+ readonly decoder?: WireSource;
250
+ readonly options: WireImageLoadOptions;
251
+ } | {
252
+ readonly type: "generateImage";
253
+ readonly model: number;
254
+ readonly prompt: string;
255
+ readonly options: WireImageOptions;
256
+ } | {
257
+ readonly type: "transcribe";
258
+ readonly model: number;
259
+ /** Mono PCM samples, or the bytes of a WAV file. */
260
+ readonly audio: Float32Array | Uint8Array;
261
+ readonly options: WireTranscribeOptions;
212
262
  } | {
213
263
  readonly type: "unload";
214
264
  readonly model: number;
@@ -248,6 +298,12 @@ export type Response = {
248
298
  readonly id: number;
249
299
  readonly done: number;
250
300
  readonly total: number;
301
+ } | {
302
+ readonly type: "imageProgress";
303
+ readonly id: number;
304
+ readonly phase: ImagePhase;
305
+ readonly step: number;
306
+ readonly steps: number;
251
307
  } | {
252
308
  readonly type: "read";
253
309
  readonly id: number;
@@ -255,16 +311,64 @@ export type Response = {
255
311
  readonly path: string;
256
312
  readonly start?: number;
257
313
  readonly end?: number;
258
- /** `"adapter"` for files of the LoRA adapter, absent for the model's own. */
259
- readonly target?: "adapter";
314
+ /**
315
+ * `"adapter"` for files of the LoRA adapter, `"decoder"` for those of
316
+ * an image model's standalone decoder, absent for the model's own.
317
+ */
318
+ readonly target?: "adapter" | "decoder";
260
319
  };
261
320
  /** Value of an `applyAdapter` result (`removeAdapter` resolves to it or `null`). */
262
321
  export type WireLoraResult = LoraInfo;
322
+ /** Options of a `transcribe` request (no signal, no callback). */
323
+ export interface WireTranscribeOptions {
324
+ readonly language?: string;
325
+ readonly task?: "transcribe" | "translate";
326
+ readonly maxNewTokens?: number;
327
+ readonly sampleRate?: number;
328
+ }
329
+ /**
330
+ * Value of a `transcribe` result. Its text streams as `delta` messages
331
+ * (`token` is -1: pieces of text, not tokens).
332
+ */
333
+ export interface WireTranscription {
334
+ readonly text: string;
335
+ readonly language: string | null;
336
+ readonly duration: number;
337
+ readonly segments: readonly {
338
+ readonly id: number;
339
+ readonly start: number;
340
+ readonly end: number;
341
+ readonly text: string;
342
+ readonly tokens: readonly number[];
343
+ }[];
344
+ readonly tokens: number;
345
+ readonly stopped: boolean;
346
+ }
347
+ /** Value of an `embed` result. */
348
+ export interface WireEmbedResult {
349
+ readonly data: Float32Array;
350
+ readonly dimensions: number;
351
+ readonly tokens: Uint32Array;
352
+ }
263
353
  /** Value of a `load` result. */
264
354
  export interface LoadResult {
265
355
  readonly model: number;
266
356
  readonly info: ModelInfo;
267
357
  }
358
+ /** Value of a `loadImage` result. */
359
+ export interface ImageLoadResult {
360
+ readonly model: number;
361
+ readonly info: ImageModelInfo;
362
+ }
363
+ /** Value of a `generateImage` result. */
364
+ export interface WireImageResult {
365
+ readonly width: number;
366
+ readonly height: number;
367
+ readonly seed: number;
368
+ /** Row-major 8-bit RGBA pixels. */
369
+ readonly rgba: Uint8Array;
370
+ readonly timeMs: number;
371
+ }
268
372
  /** Value of a `chat` or `generate` result. */
269
373
  export interface WireGenerationResult {
270
374
  readonly text: string;
package/dist/simple.d.ts CHANGED
@@ -329,5 +329,8 @@ export declare function ask(prompt: string, options?: SharedAskOptions): Promise
329
329
  * ```
330
330
  */
331
331
  export declare function stream(prompt: string, options?: SharedStreamOptions): TextStream;
332
- /** Unloads every model loaded by the module-level {@link ask} and {@link stream}. */
332
+ /**
333
+ * Unloads every model loaded by the module-level {@link ask} and
334
+ * {@link stream} (and by `generateImage`).
335
+ */
333
336
  export declare function unloadAll(): Promise<void>;
package/dist/simple.js CHANGED
@@ -6,6 +6,7 @@
6
6
  import { AsyncQueue } from "./async-queue.js";
7
7
  import { recommendedSampling } from "./curated.js";
8
8
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
9
+ import { unloadImageModels } from "./image.js";
9
10
  import { loadModel } from "./models.js";
10
11
  /**
11
12
  * The model {@link load}, {@link ask} and {@link stream} use when none is
@@ -580,9 +581,15 @@ export function stream(prompt, options = {}) {
580
581
  await llm.runPrompt(context, prompt, rest);
581
582
  }, rest);
582
583
  }
583
- /** Unloads every model loaded by the module-level {@link ask} and {@link stream}. */
584
+ /**
585
+ * Unloads every model loaded by the module-level {@link ask} and
586
+ * {@link stream} (and by `generateImage`).
587
+ */
584
588
  export async function unloadAll() {
585
589
  const pending = [...shared.values()];
586
590
  shared.clear();
587
- await Promise.all(pending.map((p) => p.then((llm) => llm.unload(), () => { })));
591
+ await Promise.all([
592
+ ...pending.map((p) => p.then((llm) => llm.unload(), () => { })),
593
+ unloadImageModels(),
594
+ ]);
588
595
  }
package/dist/types.d.ts CHANGED
@@ -184,7 +184,8 @@ export interface LoadModelOptions {
184
184
  * per token, the most recent {@link LoadModelOptions.kvResidual} positions
185
185
  * kept in f32): about 3 times less memory at 4096 positions, on the CPU
186
186
  * and WebGPU, at a small cost in accuracy. Sliding-window and recurrent
187
- * layers keep their own small states.
187
+ * layers keep their own small states. Encoders (embedding models) have
188
+ * no KV cache and ignore this and the other KV options.
188
189
  */
189
190
  readonly kvCache?: KvCacheType;
190
191
  /** Int8 KV cache: the most recent positions kept in f32 (default 128, rounded up to a multiple of 32). */
@@ -596,6 +597,101 @@ export interface ModelMemory {
596
597
  readonly maxBuffer?: number;
597
598
  }
598
599
  /** Description of a loaded model. */
600
+ /** Pooling of the token vectors of a text into one embedding (sentence-transformers' modes). */
601
+ export type Pooling = "cls" | "mean" | "max" | "mean_sqrt_len_tokens" | "weightedmean" | "lasttoken";
602
+ /** The embeddings of an encoder, in {@link ModelInfo.embedding}. */
603
+ export interface EmbeddingInfo {
604
+ /** Length of an embedding. */
605
+ readonly dimensions: number;
606
+ /** Pooling modes, concatenated in this order (`1_Pooling/config.json`; mean for a plain checkpoint). */
607
+ readonly pooling: readonly Pooling[];
608
+ /** Whether vectors are L2-normalized (a `Normalize` module, or model2vec's `normalize`). */
609
+ readonly normalize: boolean;
610
+ /** Largest number of tokens read from a text; longer texts are cut. */
611
+ readonly maxLength?: number;
612
+ }
613
+ /** Options of {@link Model.embed}. */
614
+ export interface EmbedOptions {
615
+ /** Pooling instead of the model's (static models pool by mean only). */
616
+ readonly pooling?: Pooling;
617
+ /** L2-normalize the vectors, or not, instead of the model's setting. */
618
+ readonly normalize?: boolean;
619
+ readonly signal?: AbortSignal;
620
+ }
621
+ /** What {@link Model.embed} returns. */
622
+ export interface Embeddings {
623
+ /** One vector per text, in order (views on {@link Embeddings.data}). */
624
+ readonly vectors: readonly Float32Array[];
625
+ /** The vectors one after the other. */
626
+ readonly data: Float32Array;
627
+ /** Length of each vector. */
628
+ readonly dimensions: number;
629
+ /** Tokens read from each text (texts longer than the model's limit are cut). */
630
+ readonly tokens: readonly number[];
631
+ }
632
+ /** What a speech recognition model (Whisper) reads, in {@link ModelInfo.speech}. */
633
+ export interface SpeechInfo {
634
+ /** Sample rate the model reads (16000); other rates are resampled. */
635
+ readonly sampleRate: number;
636
+ /** Mel bins of the features (80, or 128 for large-v3 checkpoints). */
637
+ readonly melBins: number;
638
+ /** Seconds of audio per window (30): longer audio is transcribed one window after the other. */
639
+ readonly windowSeconds: number;
640
+ /** Whether the model knows several languages (and translates into English). */
641
+ readonly multilingual: boolean;
642
+ /** Codes of the languages it has tokens for (empty for English-only models). */
643
+ readonly languages: readonly string[];
644
+ }
645
+ /**
646
+ * Audio for {@link Model.transcribe}: mono PCM samples (`Float32Array`, at
647
+ * {@link TranscribeOptions.sampleRate}, 16 kHz by default), or an encoded
648
+ * file (`ArrayBuffer`, `Uint8Array` or `Blob`). WAV files are decoded by the
649
+ * engine everywhere; browsers decode the other formats (MP3, Ogg, WebM, M4A...)
650
+ * with Web Audio first. In Node, pass PCM or WAV (convert other formats with
651
+ * ffmpeg, e.g. `ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav`).
652
+ */
653
+ export type AudioInput = Float32Array | ArrayBuffer | Uint8Array | Blob;
654
+ /** Options of {@link Model.transcribe}. */
655
+ export interface TranscribeOptions {
656
+ /**
657
+ * The spoken language: a code (`"en"`), an English name (`"french"`) or a
658
+ * token (`"<|fr|>"`). Default: detected from the first 30 s (ignored by
659
+ * English-only models, which take only English).
660
+ */
661
+ readonly language?: string;
662
+ /** `"transcribe"` (default), or `"translate"` into English (multilingual models). */
663
+ readonly task?: "transcribe" | "translate";
664
+ /** Largest number of tokens per 30 s window (default: the model's limit, 448 positions). */
665
+ readonly maxNewTokens?: number;
666
+ /** Sample rate of PCM input (default 16000; other rates are resampled). Ignored for files. */
667
+ readonly sampleRate?: number;
668
+ /** Stops the transcription: the promise rejects with an `ABORTED` error. */
669
+ readonly signal?: AbortSignal;
670
+ /** Receives the text as it is generated, piece by piece. */
671
+ readonly onToken?: (text: string) => void;
672
+ }
673
+ /** One 30 s window of a {@link Transcription}. */
674
+ export interface TranscriptionSegment {
675
+ readonly id: number;
676
+ /** Start and end of the window, in seconds. */
677
+ readonly start: number;
678
+ readonly end: number;
679
+ readonly text: string;
680
+ /** Token ids generated for the window (no prompt, no end token). */
681
+ readonly tokens: readonly number[];
682
+ }
683
+ /** What {@link Model.transcribe} resolves to. */
684
+ export interface Transcription {
685
+ /** The whole text, trimmed. */
686
+ readonly text: string;
687
+ /** The language code used (given or detected); absent for English-only models. */
688
+ readonly language?: string;
689
+ /** Length of the audio, in seconds. */
690
+ readonly duration: number;
691
+ readonly segments: readonly TranscriptionSegment[];
692
+ /** Tokens generated, over every window. */
693
+ readonly tokens: number;
694
+ }
599
695
  export interface ModelInfo {
600
696
  /** Hub repository id, when loaded from the hub. */
601
697
  readonly repo?: string;
@@ -644,6 +740,16 @@ export interface ModelInfo {
644
740
  readonly images: boolean;
645
741
  readonly videos: boolean;
646
742
  };
743
+ /**
744
+ * What `embed` returns by default, for an encoder (an embedding model:
745
+ * BERT, ModernBERT, model2vec); absent for language models.
746
+ */
747
+ readonly embedding?: EmbeddingInfo;
748
+ /**
749
+ * What `transcribe` reads, for a speech recognition model (Whisper);
750
+ * absent for other models.
751
+ */
752
+ readonly speech?: SpeechInfo;
647
753
  readonly stopTokens: readonly number[];
648
754
  readonly tokenizer: {
649
755
  readonly vocabSize: number;
package/dist/wasm.d.ts CHANGED
@@ -11,6 +11,10 @@ export interface WasmExports {
11
11
  version(): string;
12
12
  /** `model_type` values the engine runs. */
13
13
  supportedModelTypes(): string[];
14
+ /** `model_type` values of the encoders the engine embeds with. */
15
+ supportedEncoderTypes(): string[];
16
+ /** `model_type` values of the speech recognition models the engine transcribes with. */
17
+ supportedSpeechTypes(): string[];
14
18
  /** Parses a safetensors header (see `parseSafetensorsHeader`). */
15
19
  parseSafetensorsHeader(bytes: Uint8Array): unknown;
16
20
  /** Incremental SHA-256 (`finish()` returns the hex digest and resets). */
@@ -1,47 +1,47 @@
1
1
  {
2
- "version": "0.7.0",
2
+ "version": "0.10.0",
3
3
  "assets": {
4
4
  "darwin-arm64": {
5
- "file": "webslm-node-0.7.0-darwin-arm64.node.gz",
6
- "size": 5186619,
7
- "sha256": "b71fd469f2a2e6b81cbf51fab65bf6dbbc32c4a054f7003aa7a4d65afec87cff",
8
- "nodeSha256": "34b9a88ebf50ca0f249c7191523919bf090e77288a50784d7093193d7aa75a7e"
5
+ "file": "webslm-node-0.10.0-darwin-arm64.node.gz",
6
+ "size": 5735325,
7
+ "sha256": "1c71b3a4118910683e4c8bad68dd3e1a3bfa2dd52f0ad175fdbdca4411ead808",
8
+ "nodeSha256": "340dd77e562ee2a2c16baa9e9d58e51d839d739c4e136d6f004f410a9ae1db28"
9
9
  },
10
10
  "darwin-x64": {
11
- "file": "webslm-node-0.7.0-darwin-x64.node.gz",
12
- "size": 5463196,
13
- "sha256": "0bfa4bd88609a85ea6b0f6cdd0db62a65647bd683d2442b39e621554bd22fc4d",
14
- "nodeSha256": "3f7b6f3804695c80da8da56b2d586b46e5e02be6aedd00251f87582c1621dd58"
11
+ "file": "webslm-node-0.10.0-darwin-x64.node.gz",
12
+ "size": 6050335,
13
+ "sha256": "3af237e3ee639cfb6c282a57d04cbf064009e5e16aac7eb00e94fcdc4e081709",
14
+ "nodeSha256": "5a57693b8f73b5e594d7a742181d87bf8a6c4e08f2f7a22c142b8cf1b1dad692"
15
15
  },
16
16
  "linux-x64-gnu": {
17
- "file": "webslm-node-0.7.0-linux-x64-gnu.node.gz",
18
- "size": 5500625,
19
- "sha256": "642ba1ff52d5244486e9b0995ed8b670b2fa1a75aef014262121d553023b27bb",
20
- "nodeSha256": "836a4b1b1b2ea37c478871f744c88062a135cf9889ef58be6435d2dbf0adf814"
17
+ "file": "webslm-node-0.10.0-linux-x64-gnu.node.gz",
18
+ "size": 6072387,
19
+ "sha256": "1e0da2b585266ae48d7c0a627e2666ed0535b6c9284c0605ea287a76236fb1af",
20
+ "nodeSha256": "c28830b7d6e940160161b3f202d4ee767627e7bd48d34958ed6c5c04bff1ccc8"
21
21
  },
22
22
  "linux-arm64-gnu": {
23
- "file": "webslm-node-0.7.0-linux-arm64-gnu.node.gz",
24
- "size": 5160915,
25
- "sha256": "574a67dc1cf3f2e78368b987f1084e28542a28fda25d7640a23d293aab21c7f9",
26
- "nodeSha256": "9fe42ed8ce64b79a0dd549d3677de7562e18061458ab843e7f73d57bb6481c6e"
23
+ "file": "webslm-node-0.10.0-linux-arm64-gnu.node.gz",
24
+ "size": 5696840,
25
+ "sha256": "2ec200a92be2b0bf5f2923d992e395fa1cd6de52ed83bc0153c319f10b44cc3b",
26
+ "nodeSha256": "93fe958e29512ee71a1c10013e775e28aba2e5e6c38606b17519d292ae290390"
27
27
  },
28
28
  "linux-x64-musl": {
29
- "file": "webslm-node-0.7.0-linux-x64-musl.node.gz",
30
- "size": 5891685,
31
- "sha256": "a447a0d7b4e62acf7a816e7155053cf2a49657a6a2f147bfa87ba7991db72813",
32
- "nodeSha256": "8dbf43b1db37ebfb1ed80c8cd7aae5749662ec7cbc53fcc787a9990f2e1987a2"
29
+ "file": "webslm-node-0.10.0-linux-x64-musl.node.gz",
30
+ "size": 6479536,
31
+ "sha256": "30b430823f967231d5dec99f5dca9634e490f7ab62c1363b1fd723548ea42e91",
32
+ "nodeSha256": "069dc4e6fe0abe7a656f29233e04ac8cb3c51c044cec5fb88ef1b12dbeefa83b"
33
33
  },
34
34
  "linux-arm64-musl": {
35
- "file": "webslm-node-0.7.0-linux-arm64-musl.node.gz",
36
- "size": 5670254,
37
- "sha256": "c475896a044e2524b9affd4d1405fa3cc3c8cf6b615a757c6db1794b0686ca68",
38
- "nodeSha256": "ecaa553f3ad3a8d259014031ad44d28552d755b55a01ac992dee086edd7bab52"
35
+ "file": "webslm-node-0.10.0-linux-arm64-musl.node.gz",
36
+ "size": 6233551,
37
+ "sha256": "b895c2602be95b45fd9013f64b3ea6a4877b87d18924eb7291a821afe0a273e1",
38
+ "nodeSha256": "b3422581d06a0511b77c7cd8ec8e9f719f9b5f95827ba476841bea59122d016a"
39
39
  },
40
40
  "win32-x64-msvc": {
41
- "file": "webslm-node-0.7.0-win32-x64-msvc.node.gz",
42
- "size": 5937878,
43
- "sha256": "474409ee9825da5d28725ce3658eff6bc6c51c7085f9929c61defa94034070e9",
44
- "nodeSha256": "9920eeddbe937e3b986a15d3af28456245da2ce08b8984eb1ebf3a0e6fa621ef"
41
+ "file": "webslm-node-0.10.0-win32-x64-msvc.node.gz",
42
+ "size": 6582581,
43
+ "sha256": "e25818bbc876742f833dae75deb947dcdac3e24c4ebcc290afee582f39b35be3",
44
+ "nodeSha256": "d55270b77bbe9d8ccfc928b4d469f0527734e5efb292fe71b6a0b726c948d2ff"
45
45
  }
46
46
  }
47
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webslm",
3
- "version": "0.7.0",
3
+ "version": "0.10.0",
4
4
  "description": "Run small language models in the browser and in Node, straight from their original Hugging Face checkpoints: a Rust engine compiled to WebAssembly, in a worker, with an offline cache.",
5
5
  "license": "MIT",
6
6
  "author": "Maxime Golfier",