webslm 0.9.0 → 0.11.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 CHANGED
@@ -258,6 +258,19 @@ providerMetadata.webslm.images; // [{ seed, width, height, timeMs }, ...]
258
258
 
259
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
260
 
261
+ Whisper checkpoints are transcription models, behind `transcribe`:
262
+
263
+ ```ts
264
+ import { transcribe } from "ai";
265
+
266
+ const { text, language, segments, durationInSeconds } = await transcribe({
267
+ model: webslm.transcriptionModel("openai/whisper-tiny"),
268
+ audio: await fetch("/speech.mp3").then((r) => r.arrayBuffer()),
269
+ });
270
+ ```
271
+
272
+ `webslm.transcriptionModel(modelId, settings)` takes the load options too, and `language`, `task` (`"transcribe"` or `"translate"`) and `maxNewTokens` (also per call in `providerOptions.webslm`). Segments are the 30 s windows; word timestamps come back as an `unsupported` warning. Other model ids reject with `UNSUPPORTED_TASK`.
273
+
261
274
  `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.
262
275
 
263
276
  ## Embeddings
@@ -275,6 +288,24 @@ model.info().embedding; // { dimensions: 384, pooling: ["mean"], normalize: true
275
288
 
276
289
  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
290
 
291
+ ## Speech recognition
292
+
293
+ Whisper checkpoints (`openai/whisper-tiny`, `whisper-tiny.en`, `whisper-base`...) load with `loadModel` and answer `transcribe`: the text, its language, and one segment per 30 s window.
294
+
295
+ ```ts
296
+ import { loadModel } from "webslm";
297
+
298
+ const model = await loadModel("openai/whisper-tiny");
299
+ const recording = await fetch("/speech.webm").then((r) => r.blob()); // or a File, an ArrayBuffer, a Uint8Array
300
+ const { text, language, duration, segments } = await model.transcribe(recording, {
301
+ onToken: (piece) => output.append(piece), // the text as it is generated
302
+ });
303
+ await model.transcribe(samples, { sampleRate: 48000, language: "fr", task: "translate" }); // PCM, into English
304
+ model.info().speech; // { sampleRate: 16000, melBins: 80, windowSeconds: 30, multilingual: true, languages: ["en", "zh", ...] }
305
+ ```
306
+
307
+ `audio` is mono PCM (`Float32Array`, at `sampleRate`, 16 kHz by default; other rates are resampled) or an audio file (`ArrayBuffer`, `Uint8Array` or `Blob`). WAV files are decoded by the engine everywhere; in a page, other formats (MP3, Ogg, WebM, M4A, whatever the browser plays) are decoded with Web Audio (`OfflineAudioContext`, at 16 kHz, mixed down to mono; `decodeAudio(file)` does it alone). In Node, pass PCM or WAV, and convert other formats with ffmpeg (`ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav`). `language` is a code (`"en"`), an English name (`"french"`) or a token (`"<|fr|>"`), detected from the first window when absent (English-only checkpoints take English only); `task: "translate"` translates into English; `maxNewTokens` caps each window; `signal` stops the transcription (`ABORTED`). Without `quant`, a speech model loads in f32. The greedy tokens are those of `transformers` exactly, in the WebAssembly engine, natively and on the GPU (see the [repository README](../../README.md#speech-recognition)). Other calls reject on a speech model with `UNSUPPORTED_TASK`, and `transcribe` on other models; `searchModels` and `checkModel` mark Whisper repositories with `speech: true` (`SPEECH_MODEL_TYPES`).
308
+
278
309
  ## Advanced API
279
310
 
280
311
  The simple API above is built on `loadModel`, `Model` and `Session`, which expose every option.
@@ -422,6 +453,37 @@ With `s = (lora_alpha / r) · scale` (`lora_alpha / sqrt(r)` with `use_rslora`),
422
453
 
423
454
  `target_modules` (names, a regular expression or `"all-linear"`), `exclude_modules`, `layers_to_transform`, `layers_pattern`, `rank_pattern` and `alpha_pattern` are honoured. `applyAdapter` replaces the previous adapter; `removeAdapter` restores the base model exactly (bit-identical logits). An adapter that does not fit the model rejects with `INVALID_ADAPTER` and leaves the model unchanged; DoRA, LoRA biases and `modules_to_save` are refused. Every session starts over at its next call after a change.
424
455
 
456
+ ## Training
457
+
458
+ `model.train` trains LoRA factors (or dense deltas) of chosen layers of a llama-like model (Llama, SmolLM2) on token sequences, everything else frozen, and resolves to the trained delta as PEFT adapter files, which `applyAdapter` loads at any scale:
459
+
460
+ ```ts
461
+ const model = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct");
462
+ const controller = new AbortController();
463
+ const result = await model.train({
464
+ steps: 100,
465
+ params: { method: "lora", rank: 8, alpha: 16, targets: ["q_proj", "v_proj"], layers: [26, 27, 28, 29] },
466
+ optimizer: { lr: 1e-3, warmupSteps: 10, schedule: "cosine", weightDecay: 0, maxNormRatio: 0.05 },
467
+ dataset: notes.map((text) => ({ text })), // or { ids, weights?, teacher? }
468
+ batchSize: 8,
469
+ loss: { ce: 1 },
470
+ device: "auto", // WebGPU when there is one
471
+ onStep: ({ step, loss, lr, timeMs }) => console.log(step, loss, lr, timeMs),
472
+ signal: controller.signal,
473
+ });
474
+ result.files; // { "adapter_config.json": Uint8Array, "adapter_model.safetensors": Uint8Array }
475
+ result.trainableParameters; // 61440
476
+ await model.applyAdapter({ files: result.files }, { scale: 0.5 }); // base + 0.5 · delta
477
+ ```
478
+
479
+ - `params`: `method` `"lora"` (default; `rank` 8, `alpha` twice the rank) or `"full"` (a dense delta of each whole matrix, exported as exact full-rank factors), `targets` (`"q_proj"`, `"k_proj"`, `"v_proj"`, `"o_proj"`, `"gate_proj"`, `"up_proj"`, `"down_proj"`, `"attention"`, `"mlp"`, `"all"`: the default) and `layers` (default: all).
480
+ - Data: `dataset` (one group, with `batchSize`, 8 by default, and `loss`) or `groups` (several, each with `examples`, `batchSize`, `weight`, `loss` and `sampling`: `"random"`, `"sequential"` or one weight per example). An example has `ids` (or `text`, tokenized with special tokens), optional per-prediction `weights` (`ids.length - 1` values) and an optional `teacher` for the KL term: `"base"` (the model without the delta), `{ k, ids, probs }` (the teacher's top `k` tokens of each prediction; the remaining mass forms a tail bucket) or `{ logits }`.
481
+ - `loss`: `ce · cross-entropy + kl · KL(teacher ‖ model)` (defaults `ce: 1`, `kl: 0`), averaged over tokens, or with `reduction: "sequence"` summed per sequence and averaged over sequences.
482
+ - `optimizer`: AdamW (`lr` 5e-4, `beta1` 0.9, `beta2` 0.999, `eps` 1e-8, `weightDecay` 0, as `torch.optim.AdamW` computes it), `warmupSteps` then `schedule` (`"cosine"`, `"linear"`, `"constant"`), and `maxNormRatio`, which scales back after each step every matrix whose delta exceeds that fraction of the base matrix's norm.
483
+ - `microBatch` (tokens per micro-batch; a step sums their gradients), `checkpointing` (default `true`), `seed`, `format` (`"peft"`, the default, or `"dense"`: `delta.safetensors`) and `baseModel` (the adapter's `base_model_name_or_path`, default the model's repository).
484
+
485
+ Training loads its own f32 copy of the weights from the model's source (the Hub cache, `files` or `fetch`), so it needs a safetensors checkpoint and memory for the weights in f32, the trained parameters four times, and the activations of one micro-batch (see the [repository README](../../README.md#on-device-training) for the memory strategy, the accuracy against PyTorch and step times). The model itself is unchanged until the files are applied. `signal` stops training before the next step (`ABORTED`); other architectures reject with `UNSUPPORTED_MODEL`. In Node, training runs on the native engine (Metal, Vulkan, DX12 or the native CPU kernels).
486
+
425
487
  ## Low-level sessions
426
488
 
427
489
  ```ts
@@ -541,7 +603,7 @@ export default defineConfig({
541
603
  });
542
604
  ```
543
605
 
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>.
606
+ 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.11.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>.
545
607
 
546
608
  ## Errors
547
609
 
@@ -38,6 +38,17 @@
38
38
  * });
39
39
  * ```
40
40
  *
41
+ * Whisper checkpoints are transcription models, behind `transcribe`:
42
+ *
43
+ * ```ts
44
+ * import { transcribe } from "ai";
45
+ *
46
+ * const { text } = await transcribe({
47
+ * model: webslm.transcriptionModel("openai/whisper-tiny"),
48
+ * audio: wavBytes,
49
+ * });
50
+ * ```
51
+ *
41
52
  * `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
42
53
  * `webslm`: install them to use this entry point.
43
54
  *
@@ -47,6 +58,7 @@ import type { ProviderV4 } from "@ai-sdk/provider";
47
58
  import { WebslmEmbeddingModel, type WebslmEmbeddingSettings } from "./embedding-model.js";
48
59
  import { WebslmImageModel, type WebslmImageEngine, type WebslmImageModelSettings } from "./image-model.js";
49
60
  import { WebslmLanguageModel, type WebslmModelSettings } from "./language-model.js";
61
+ import { WebslmTranscriptionModel, type WebslmTranscriptionSettings } from "./transcription-model.js";
50
62
  import { type WebslmEngine, type WebslmLoadOptions } from "./loader.js";
51
63
  export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "../curated.js";
52
64
  export { searchModels, type HubModel, type SearchModelsOptions } from "../hub.js";
@@ -54,6 +66,7 @@ export { DEFAULT_MODEL } from "../simple.js";
54
66
  export type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
55
67
  export { WebslmLanguageModel, type WebslmCallSettings, type WebslmModelSettings, type WebslmPreloadOptions, } from "./language-model.js";
56
68
  export { WebslmEmbeddingModel, type WebslmEmbeddingCallSettings, type WebslmEmbeddingSettings, } from "./embedding-model.js";
69
+ export { WebslmTranscriptionModel, type WebslmTranscriptionCallSettings, type WebslmTranscriptionSettings, } from "./transcription-model.js";
57
70
  export type { WebslmEngine, WebslmLoadOptions } from "./loader.js";
58
71
  export { MAX_IMAGES_PER_CALL, WebslmImageModel, type WebslmImageEngine, type WebslmImageLoadOptions, type WebslmImageModelSettings, } from "./image-model.js";
59
72
  export { DEFAULT_IMAGE_MODEL } from "../image.js";
@@ -84,6 +97,8 @@ export interface WebslmProvider extends ProviderV4 {
84
97
  * models of one id and the same load options share one loaded model.
85
98
  */
86
99
  imageModel(modelId: string, settings?: WebslmImageModelSettings): WebslmImageModel;
100
+ /** A speech recognition model (Whisper) as a transcription model, for `transcribe`. */
101
+ transcriptionModel(modelId: string, settings?: WebslmTranscriptionSettings): WebslmTranscriptionModel;
87
102
  /** Frees every model this provider loaded (each loads again on its next call). */
88
103
  unloadAll(): Promise<void>;
89
104
  }
@@ -38,6 +38,17 @@
38
38
  * });
39
39
  * ```
40
40
  *
41
+ * Whisper checkpoints are transcription models, behind `transcribe`:
42
+ *
43
+ * ```ts
44
+ * import { transcribe } from "ai";
45
+ *
46
+ * const { text } = await transcribe({
47
+ * model: webslm.transcriptionModel("openai/whisper-tiny"),
48
+ * audio: wavBytes,
49
+ * });
50
+ * ```
51
+ *
41
52
  * `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
42
53
  * `webslm`: install them to use this entry point.
43
54
  *
@@ -49,12 +60,14 @@ import { loadModel } from "../models.js";
49
60
  import { EMBEDDING_SETTING_KEYS, WebslmEmbeddingModel, } from "./embedding-model.js";
50
61
  import { ImageModelSlot, WebslmImageModel, } from "./image-model.js";
51
62
  import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
63
+ import { TRANSCRIPTION_SETTING_KEYS, WebslmTranscriptionModel, } from "./transcription-model.js";
52
64
  import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
53
65
  export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "../curated.js";
54
66
  export { searchModels } from "../hub.js";
55
67
  export { DEFAULT_MODEL } from "../simple.js";
56
68
  export { WebslmLanguageModel, } from "./language-model.js";
57
69
  export { WebslmEmbeddingModel, } from "./embedding-model.js";
70
+ export { WebslmTranscriptionModel, } from "./transcription-model.js";
58
71
  export { MAX_IMAGES_PER_CALL, WebslmImageModel, } from "./image-model.js";
59
72
  export { DEFAULT_IMAGE_MODEL } from "../image.js";
60
73
  function checkModelId(modelId) {
@@ -111,12 +124,18 @@ export function createWebslm(options = {}) {
111
124
  const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, EMBEDDING_SETTING_KEYS) };
112
125
  return new WebslmEmbeddingModel(id, slotFor(id, loadOptions), settings);
113
126
  };
127
+ const transcriptionModel = (modelId, settings = {}) => {
128
+ const id = checkModelId(modelId);
129
+ const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, TRANSCRIPTION_SETTING_KEYS) };
130
+ return new WebslmTranscriptionModel(id, slotFor(id, loadOptions), settings);
131
+ };
114
132
  const provider = (modelId, settings) => languageModel(modelId, settings);
115
133
  return Object.assign(provider, {
116
134
  specificationVersion: "v4",
117
135
  languageModel,
118
136
  embeddingModel,
119
137
  imageModel,
138
+ transcriptionModel,
120
139
  unloadAll: async () => {
121
140
  const all = [...slots.values()];
122
141
  await Promise.all([...all.map((slot) => slot.unload()), ...[...imageSlots.values()].map((slot) => slot.unload())]);
@@ -0,0 +1,48 @@
1
+ /** The AI SDK transcription model (specification v4) over a webslm speech recognition model (Whisper). */
2
+ import type { TranscriptionModelV4, TranscriptionModelV4CallOptions, TranscriptionModelV4Result } from "@ai-sdk/provider";
3
+ import type { LoadModelOptions, ModelInfo } from "../types.js";
4
+ import { type ModelSlot } from "./loader.js";
5
+ import type { WebslmPreloadOptions } from "./language-model.js";
6
+ /** Defaults of every `transcribe` call; a call's `providerOptions.webslm` takes precedence. */
7
+ export interface WebslmTranscriptionCallSettings {
8
+ /** The spoken language: a code (`"en"`) or an English name (default: detected). */
9
+ readonly language?: string;
10
+ /** `"transcribe"` (default), or `"translate"` into English. */
11
+ readonly task?: "transcribe" | "translate";
12
+ /** Largest number of tokens per 30 s window. */
13
+ readonly maxNewTokens?: number;
14
+ }
15
+ /** Settings of `webslm.transcriptionModel(modelId, settings)`: how to load the model, and call defaults. */
16
+ export interface WebslmTranscriptionSettings extends Omit<LoadModelOptions, "signal">, WebslmTranscriptionCallSettings {
17
+ }
18
+ /** The fields of {@link WebslmTranscriptionSettings} that are not load options. */
19
+ export declare const TRANSCRIPTION_SETTING_KEYS: readonly ["language", "task", "maxNewTokens"];
20
+ /**
21
+ * An AI SDK transcription model backed by a webslm speech recognition model
22
+ * (Whisper), loaded on the first call and shared by every model of the
23
+ * provider with the same id and load options. Calls run one at a time.
24
+ * WAV audio is decoded everywhere; other formats need Web Audio (browsers).
25
+ *
26
+ * ```ts
27
+ * import { webslm } from "webslm/ai-sdk";
28
+ * import { transcribe } from "ai";
29
+ *
30
+ * const { text, language, segments } = await transcribe({
31
+ * model: webslm.transcriptionModel("openai/whisper-tiny"),
32
+ * audio: await readFile("speech.wav"),
33
+ * });
34
+ * ```
35
+ */
36
+ export declare class WebslmTranscriptionModel implements TranscriptionModelV4 {
37
+ #private;
38
+ readonly specificationVersion: "v4";
39
+ readonly provider = "webslm";
40
+ readonly modelId: string;
41
+ /** @internal Built by the provider (`webslm.transcriptionModel(id)`). */
42
+ constructor(modelId: string, slot: ModelSlot, settings?: WebslmTranscriptionSettings);
43
+ /** Downloads and loads the model now instead of at the first call; resolves to its description. */
44
+ load(options?: WebslmPreloadOptions): Promise<ModelInfo>;
45
+ /** Frees the model (once the call in progress ends); the next call loads it again. */
46
+ unload(): Promise<void>;
47
+ doGenerate(options: TranscriptionModelV4CallOptions): Promise<TranscriptionModelV4Result>;
48
+ }
@@ -0,0 +1,115 @@
1
+ /** The AI SDK transcription model (specification v4) over a webslm speech recognition model (Whisper). */
2
+ import { WebslmError, toWebslmError } from "../errors.js";
3
+ import { abortReason, raceAbort } from "./loader.js";
4
+ const PROVIDER = "webslm";
5
+ /** The fields of {@link WebslmTranscriptionSettings} that are not load options. */
6
+ export const TRANSCRIPTION_SETTING_KEYS = ["language", "task", "maxNewTokens"];
7
+ /** `providerOptions.webslm` of a call, read leniently (unknown keys and wrong types are ignored). */
8
+ function callSettings(options) {
9
+ const raw = options.providerOptions?.[PROVIDER];
10
+ if (raw === undefined)
11
+ return {};
12
+ const out = {};
13
+ if (typeof raw.language === "string")
14
+ out.language = raw.language;
15
+ if (raw.task === "transcribe" || raw.task === "translate")
16
+ out.task = raw.task;
17
+ if (typeof raw.maxNewTokens === "number")
18
+ out.maxNewTokens = raw.maxNewTokens;
19
+ return out;
20
+ }
21
+ /** The bytes of a base64 string. */
22
+ function fromBase64(data) {
23
+ const binary = atob(data);
24
+ const bytes = new Uint8Array(binary.length);
25
+ for (let i = 0; i < binary.length; i++)
26
+ bytes[i] = binary.charCodeAt(i);
27
+ return bytes;
28
+ }
29
+ /**
30
+ * An AI SDK transcription model backed by a webslm speech recognition model
31
+ * (Whisper), loaded on the first call and shared by every model of the
32
+ * provider with the same id and load options. Calls run one at a time.
33
+ * WAV audio is decoded everywhere; other formats need Web Audio (browsers).
34
+ *
35
+ * ```ts
36
+ * import { webslm } from "webslm/ai-sdk";
37
+ * import { transcribe } from "ai";
38
+ *
39
+ * const { text, language, segments } = await transcribe({
40
+ * model: webslm.transcriptionModel("openai/whisper-tiny"),
41
+ * audio: await readFile("speech.wav"),
42
+ * });
43
+ * ```
44
+ */
45
+ export class WebslmTranscriptionModel {
46
+ specificationVersion = "v4";
47
+ provider = PROVIDER;
48
+ modelId;
49
+ #slot;
50
+ #settings;
51
+ /** @internal Built by the provider (`webslm.transcriptionModel(id)`). */
52
+ constructor(modelId, slot, settings = {}) {
53
+ this.modelId = modelId;
54
+ this.#slot = slot;
55
+ this.#settings = settings;
56
+ }
57
+ /** Downloads and loads the model now instead of at the first call; resolves to its description. */
58
+ async load(options = {}) {
59
+ const loaded = await this.#slot.acquire(options.signal, [this.#settings.onProgress, options.onProgress]);
60
+ return loaded.model.info();
61
+ }
62
+ /** Frees the model (once the call in progress ends); the next call loads it again. */
63
+ unload() {
64
+ return this.#slot.unload();
65
+ }
66
+ async doGenerate(options) {
67
+ const signal = options.abortSignal;
68
+ try {
69
+ const loaded = await this.#slot.acquire(signal, [this.#settings.onProgress]);
70
+ if (loaded.model.info().speech === undefined) {
71
+ throw new WebslmError("UNSUPPORTED_TASK", `${this.modelId} is not a speech recognition model; transcription needs one (Whisper)`);
72
+ }
73
+ const warnings = [];
74
+ if (options.timestampGranularities?.includes("word") === true) {
75
+ warnings.push({
76
+ type: "unsupported",
77
+ feature: "timestampGranularities",
78
+ details: "webslm returns one segment per 30 s window, without word timings",
79
+ });
80
+ }
81
+ const audio = typeof options.audio === "string" ? fromBase64(options.audio) : options.audio;
82
+ const call = { ...pickCallSettings(this.#settings), ...callSettings(options) };
83
+ const result = await raceAbort(loaded.lock.run(async () => {
84
+ if (signal?.aborted === true)
85
+ throw abortReason(signal);
86
+ return loaded.model.transcribe(audio, { ...call, ...(signal === undefined ? {} : { signal }) });
87
+ }), signal);
88
+ return {
89
+ text: result.text,
90
+ segments: result.segments
91
+ .filter((s) => s.text.trim() !== "")
92
+ .map((s) => ({ text: s.text.trim(), startSecond: s.start, endSecond: s.end })),
93
+ language: result.language,
94
+ durationInSeconds: result.duration,
95
+ warnings,
96
+ usage: { tokens: result.tokens, seconds: result.duration },
97
+ response: { timestamp: new Date(), modelId: this.modelId },
98
+ };
99
+ }
100
+ catch (error) {
101
+ if (signal?.aborted === true)
102
+ throw abortReason(signal);
103
+ if (error instanceof DOMException)
104
+ throw error;
105
+ throw toWebslmError(error);
106
+ }
107
+ }
108
+ }
109
+ function pickCallSettings(settings) {
110
+ return {
111
+ ...(settings.language === undefined ? {} : { language: settings.language }),
112
+ ...(settings.task === undefined ? {} : { task: settings.task }),
113
+ ...(settings.maxNewTokens === undefined ? {} : { maxNewTokens: settings.maxNewTokens }),
114
+ };
115
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Audio for speech recognition, turned into what the engine reads: mono PCM
3
+ * samples (`Float32Array`) or the bytes of a WAV file, which the engine
4
+ * decodes itself (16-bit, 24-bit, 32-bit and float PCM, any channel count,
5
+ * any rate).
6
+ *
7
+ * Other formats (MP3, Ogg, WebM, M4A...) are decoded where the caller's
8
+ * objects live with Web Audio (`OfflineAudioContext.decodeAudioData`, which
9
+ * resamples to 16 kHz), then mixed down to mono. Node has no Web Audio: pass
10
+ * PCM or WAV there (ffmpeg converts anything: `ffmpeg -i in.mp3 -ac 1 -ar
11
+ * 16000 out.wav`).
12
+ */
13
+ import type { AudioInput } from "./types.js";
14
+ /** The sample rate Whisper reads; other rates are resampled. */
15
+ export declare const SPEECH_SAMPLE_RATE = 16000;
16
+ /** Whether `bytes` start like a RIFF/WAVE (or RF64) file. */
17
+ export declare function isWav(bytes: Uint8Array): boolean;
18
+ /**
19
+ * Decodes an encoded audio file into mono samples at `sampleRate` (16 kHz
20
+ * by default) with Web Audio. Browsers only: rejects with
21
+ * `INVALID_ARGUMENT` where there is no `OfflineAudioContext` (Node, Web
22
+ * Workers).
23
+ */
24
+ export declare function decodeAudio(input: ArrayBuffer | Uint8Array | Blob, sampleRate?: number): Promise<Float32Array>;
25
+ /**
26
+ * What the engine reads for `input`: PCM samples as they are, WAV bytes as
27
+ * they are, other files decoded to 16 kHz mono samples with Web Audio.
28
+ * Returns the sample rate of PCM it produced (`undefined` for WAV bytes).
29
+ */
30
+ export declare function prepareAudio(input: AudioInput, sampleRate: number | undefined): Promise<{
31
+ readonly audio: Float32Array | Uint8Array;
32
+ readonly sampleRate?: number;
33
+ }>;
package/dist/audio.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Audio for speech recognition, turned into what the engine reads: mono PCM
3
+ * samples (`Float32Array`) or the bytes of a WAV file, which the engine
4
+ * decodes itself (16-bit, 24-bit, 32-bit and float PCM, any channel count,
5
+ * any rate).
6
+ *
7
+ * Other formats (MP3, Ogg, WebM, M4A...) are decoded where the caller's
8
+ * objects live with Web Audio (`OfflineAudioContext.decodeAudioData`, which
9
+ * resamples to 16 kHz), then mixed down to mono. Node has no Web Audio: pass
10
+ * PCM or WAV there (ffmpeg converts anything: `ffmpeg -i in.mp3 -ac 1 -ar
11
+ * 16000 out.wav`).
12
+ */
13
+ import { WebslmError } from "./errors.js";
14
+ /** The sample rate Whisper reads; other rates are resampled. */
15
+ export const SPEECH_SAMPLE_RATE = 16000;
16
+ /** Whether `bytes` start like a RIFF/WAVE (or RF64) file. */
17
+ export function isWav(bytes) {
18
+ if (bytes.length < 12)
19
+ return false;
20
+ const tag = (at) => String.fromCharCode(bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]);
21
+ return (tag(0) === "RIFF" || tag(0) === "RF64") && tag(8) === "WAVE";
22
+ }
23
+ /** `OfflineAudioContext`, when the environment has Web Audio. */
24
+ function offlineAudioContext() {
25
+ const g = globalThis;
26
+ return g.OfflineAudioContext ?? g.webkitOfflineAudioContext;
27
+ }
28
+ /**
29
+ * Decodes an encoded audio file into mono samples at `sampleRate` (16 kHz
30
+ * by default) with Web Audio. Browsers only: rejects with
31
+ * `INVALID_ARGUMENT` where there is no `OfflineAudioContext` (Node, Web
32
+ * Workers).
33
+ */
34
+ export async function decodeAudio(input, sampleRate = SPEECH_SAMPLE_RATE) {
35
+ const Context = offlineAudioContext();
36
+ if (Context === undefined) {
37
+ throw new WebslmError("INVALID_ARGUMENT", "this environment has no Web Audio to decode the file: pass mono PCM samples (Float32Array) or a WAV file " +
38
+ "(ffmpeg converts other formats: ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav)");
39
+ }
40
+ const bytes = await toBytes(input);
41
+ // decodeAudioData detaches its buffer: give it a copy.
42
+ const copy = bytes.slice().buffer;
43
+ let buffer;
44
+ try {
45
+ buffer = await new Context(1, 1, sampleRate).decodeAudioData(copy);
46
+ }
47
+ catch (error) {
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ throw new WebslmError("INVALID_ARGUMENT", `cannot decode the audio file: ${message}`);
50
+ }
51
+ const channels = buffer.numberOfChannels;
52
+ if (channels === 1)
53
+ return buffer.getChannelData(0).slice();
54
+ const mono = new Float32Array(buffer.length);
55
+ for (let c = 0; c < channels; c++) {
56
+ const data = buffer.getChannelData(c);
57
+ for (let i = 0; i < mono.length; i++)
58
+ mono[i] = mono[i] + data[i] / channels;
59
+ }
60
+ return mono;
61
+ }
62
+ async function toBytes(input) {
63
+ if (input instanceof Uint8Array)
64
+ return input;
65
+ if (input instanceof ArrayBuffer)
66
+ return new Uint8Array(input);
67
+ if (typeof Blob !== "undefined" && input instanceof Blob)
68
+ return new Uint8Array(await input.arrayBuffer());
69
+ throw new WebslmError("INVALID_ARGUMENT", "audio must be a Float32Array, an ArrayBuffer, a Uint8Array or a Blob");
70
+ }
71
+ /**
72
+ * What the engine reads for `input`: PCM samples as they are, WAV bytes as
73
+ * they are, other files decoded to 16 kHz mono samples with Web Audio.
74
+ * Returns the sample rate of PCM it produced (`undefined` for WAV bytes).
75
+ */
76
+ export async function prepareAudio(input, sampleRate) {
77
+ if (input instanceof Float32Array) {
78
+ return { audio: input, ...(sampleRate === undefined ? {} : { sampleRate }) };
79
+ }
80
+ if (ArrayBuffer.isView(input) && !(input instanceof Uint8Array)) {
81
+ throw new WebslmError("INVALID_ARGUMENT", "audio must be a Float32Array of samples, or an ArrayBuffer, Uint8Array or Blob holding a file");
82
+ }
83
+ const bytes = await toBytes(input);
84
+ if (isWav(bytes))
85
+ return { audio: bytes };
86
+ return { audio: await decodeAudio(bytes, SPEECH_SAMPLE_RATE), sampleRate: SPEECH_SAMPLE_RATE };
87
+ }
package/dist/client.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { WebslmError } from "./errors.js";
6
6
  import type { Request, Response } from "./protocol.js";
7
+ import type { TrainStep } from "./train.js";
7
8
  import type { FetchFile, LoadProgress } from "./types.js";
8
9
  export type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
9
10
  /** A bidirectional message channel to an engine. */
@@ -41,6 +42,8 @@ export interface RequestHooks {
41
42
  readonly onImageProgress?: (progress: Extract<Response, {
42
43
  type: "imageProgress";
43
44
  }>) => void;
45
+ /** A training step done. */
46
+ readonly onTrainStep?: (step: TrainStep) => void;
44
47
  readonly signal?: AbortSignal;
45
48
  readonly transfer?: Transferable[];
46
49
  }
package/dist/client.js CHANGED
@@ -90,6 +90,9 @@ export class EngineClient {
90
90
  case "imageProgress":
91
91
  pending.hooks.onImageProgress?.(message);
92
92
  break;
93
+ case "trainStep":
94
+ pending.hooks.onTrainStep?.(message.step);
95
+ break;
93
96
  case "read":
94
97
  void this.#serveRead(message.target === "adapter"
95
98
  ? pending.hooks.onAdapterRead
package/dist/engine.js CHANGED
@@ -234,6 +234,10 @@ export class Engine {
234
234
  const result = await this.#generateImage(request, signal);
235
235
  return [result, result.rgba.buffer instanceof ArrayBuffer ? [result.rgba.buffer] : []];
236
236
  }
237
+ case "transcribe":
238
+ return [await this.#transcribe(request, signal)];
239
+ case "train":
240
+ return [await this.#train(request, signal)];
237
241
  case "unload": {
238
242
  const image = this.#imageModels.get(request.model);
239
243
  if (image !== undefined) {
@@ -304,6 +308,56 @@ export class Engine {
304
308
  : target.generate(request.prompt, options, onDelta, onPrefill)));
305
309
  return withTimings(summary, started, first, last);
306
310
  }
311
+ /**
312
+ * Transcribes speech: pieces of text stream as `delta` messages (`token`
313
+ * -1), and the signal stops the transcription before its next token.
314
+ */
315
+ async #transcribe(request, signal) {
316
+ const { handle } = this.#model(request.model);
317
+ const options = JSON.stringify(request.options);
318
+ const post = (text) => this.#host.post({ type: "delta", id: request.id, text, token: -1 });
319
+ if (handle.runtime === "wasm") {
320
+ const onText = async (text) => {
321
+ post(text);
322
+ // Let `abort` messages in before the next token.
323
+ await yieldToEventLoop();
324
+ return !signal.aborted;
325
+ };
326
+ return (await handle.model.transcribe(request.audio, options, onText));
327
+ }
328
+ if (handle.model.transcribe === undefined) {
329
+ throw new WebslmError("UNSUPPORTED_TASK", "this build of the native engine cannot transcribe");
330
+ }
331
+ const cancel = new handle.addon.CancelToken();
332
+ const onAbort = () => cancel.cancel();
333
+ signal.addEventListener("abort", onAbort, { once: true });
334
+ if (signal.aborted)
335
+ cancel.cancel();
336
+ // The result and the text come through different queues: wait for
337
+ // every piece the result counts.
338
+ let received = 0;
339
+ let expected = Number.POSITIVE_INFINITY;
340
+ let allReceived = () => { };
341
+ const done = new Promise((resolve) => {
342
+ allReceived = resolve;
343
+ });
344
+ const onText = (text) => {
345
+ post(text);
346
+ received += 1;
347
+ if (received >= expected)
348
+ allReceived();
349
+ };
350
+ try {
351
+ const { pieces, ...result } = (await handle.model.transcribe(request.audio, options, onText, cancel));
352
+ expected = pieces;
353
+ if (received < expected)
354
+ await done;
355
+ return result;
356
+ }
357
+ finally {
358
+ signal.removeEventListener("abort", onAbort);
359
+ }
360
+ }
307
361
  /**
308
362
  * A generation on the native engine: tokens arrive from the model's thread
309
363
  * through a threadsafe function, and the signal cancels the call (before
@@ -641,6 +695,7 @@ export class Engine {
641
695
  info,
642
696
  active,
643
697
  adapterQueue: Promise.resolve(),
698
+ ...(gguf === undefined ? { trainSource: opened } : {}),
644
699
  });
645
700
  progress({
646
701
  phase: "ready",
@@ -718,6 +773,8 @@ export class Engine {
718
773
  info,
719
774
  active,
720
775
  adapterQueue: Promise.resolve(),
776
+ ...(gguf === undefined ? { trainDir: dir } : {}),
777
+ ...(options.threads === undefined ? {} : { threads: options.threads }),
721
778
  });
722
779
  progress({
723
780
  phase: "ready",
@@ -780,6 +837,58 @@ export class Engine {
780
837
  return removed === null ? null : (lora ?? removed);
781
838
  });
782
839
  }
840
+ /**
841
+ * Trains on the model's weights: a trainer loads its own f32 copy from
842
+ * the model's source, takes the groups, runs the steps (reporting each)
843
+ * and exports the delta. The model itself is left unchanged.
844
+ */
845
+ async #train(request, signal) {
846
+ const model = this.#model(request.model);
847
+ return this.#exclusive(model, request.id, signal, async () => {
848
+ let trainer;
849
+ if (model.handle.runtime === "native") {
850
+ const { addon } = model.handle;
851
+ if (addon.NativeTrainer === undefined) {
852
+ throw new WebslmError("UNSUPPORTED_TASK", "this build of the native engine cannot train");
853
+ }
854
+ if (model.trainDir === undefined) {
855
+ throw new WebslmError("UNSUPPORTED_TASK", "training needs a safetensors checkpoint (not a GGUF file)");
856
+ }
857
+ trainer = await addon.NativeTrainer.load(model.trainDir, request.options, model.threads ?? null);
858
+ }
859
+ else {
860
+ if (model.trainSource === undefined) {
861
+ throw new WebslmError("UNSUPPORTED_TASK", "training needs a safetensors checkpoint (not a GGUF file)");
862
+ }
863
+ const engine = await initEngineWasm();
864
+ const { source } = this.#jsSource(model.trainSource, model.active, () => { }, engine.bindings);
865
+ trainer = await engine.bindings.WasmTrainer.load(source, request.options);
866
+ }
867
+ try {
868
+ for (const group of request.groups) {
869
+ const index = trainer.addGroup(group.options);
870
+ for (const e of group.examples) {
871
+ trainer.addExample(index, e.ids, e.weights, e.teacher, e.k, e.teacherIds, e.teacherValues);
872
+ }
873
+ }
874
+ await trainer.commit();
875
+ const steps = [];
876
+ for (let i = 0; i < request.steps; i++) {
877
+ if (signal.aborted)
878
+ throw abortError(signal);
879
+ const step = (await trainer.step());
880
+ steps.push(step);
881
+ this.#host.post({ type: "trainStep", id: request.id, step });
882
+ }
883
+ const files = (await trainer.files(request.format ?? "peft", request.baseModel));
884
+ const info = trainer.info();
885
+ return { files, steps, info };
886
+ }
887
+ finally {
888
+ trainer.free();
889
+ }
890
+ });
891
+ }
783
892
  /**
784
893
  * Loads a text-to-image pipeline (and a standalone decoder): on the
785
894
  * native engine from the snapshot directories the download wrote, else