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 +63 -1
- package/dist/ai-sdk/index.d.ts +15 -0
- package/dist/ai-sdk/index.js +19 -0
- package/dist/ai-sdk/transcription-model.d.ts +48 -0
- package/dist/ai-sdk/transcription-model.js +115 -0
- package/dist/audio.d.ts +33 -0
- package/dist/audio.js +87 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +3 -0
- package/dist/engine.js +109 -0
- package/dist/hub.d.ts +9 -0
- package/dist/hub.js +12 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/models.d.ts +46 -1
- package/dist/models.js +112 -1
- package/dist/native.d.ts +20 -0
- package/dist/protocol.d.ts +45 -0
- package/dist/train.d.ts +201 -0
- package/dist/train.js +99 -0
- package/dist/types.d.ts +68 -0
- package/dist/wasm.d.ts +2 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +85 -3
- package/wasm/relaxed/webslm_wasm.js +222 -15
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +14 -3
- package/wasm/simd/webslm_wasm.d.ts +85 -3
- package/wasm/simd/webslm_wasm.js +222 -15
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +14 -3
- package/wasm/threads/webslm_wasm.d.ts +86 -4
- package/wasm/threads/webslm_wasm.js +234 -27
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +15 -4
package/dist/hub.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export declare const SUPPORTED_MODEL_TYPES: readonly string[];
|
|
|
17
17
|
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
18
18
|
*/
|
|
19
19
|
export declare const ENCODER_MODEL_TYPES: readonly string[];
|
|
20
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
21
|
+
export declare const SPEECH_MODEL_TYPES: readonly string[];
|
|
20
22
|
/** Files read besides the weights, when the repository has them. */
|
|
21
23
|
export declare const CHECKPOINT_SIDE_FILES: readonly string[];
|
|
22
24
|
export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
@@ -151,6 +153,11 @@ export interface HubModel {
|
|
|
151
153
|
* {@link ENCODER_MODEL_TYPES} (load it and call `embed`), refused otherwise.
|
|
152
154
|
*/
|
|
153
155
|
readonly embedding?: boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Whether it is a speech recognition model (one of
|
|
158
|
+
* {@link SPEECH_MODEL_TYPES}: load it and call `transcribe`).
|
|
159
|
+
*/
|
|
160
|
+
readonly speech?: boolean;
|
|
154
161
|
/** Why it is not supported. */
|
|
155
162
|
readonly reason?: string;
|
|
156
163
|
readonly downloads?: number;
|
|
@@ -221,6 +228,8 @@ export interface ModelCheck {
|
|
|
221
228
|
* one of {@link ENCODER_MODEL_TYPES} (load it and call `embed`).
|
|
222
229
|
*/
|
|
223
230
|
readonly embedding?: boolean;
|
|
231
|
+
/** Whether it is a speech recognition model (load it and call `transcribe`). */
|
|
232
|
+
readonly speech?: boolean;
|
|
224
233
|
readonly modelType?: string;
|
|
225
234
|
readonly gated: false | "auto" | "manual";
|
|
226
235
|
readonly hasTokenizer: boolean;
|
package/dist/hub.js
CHANGED
|
@@ -29,6 +29,8 @@ export const SUPPORTED_MODEL_TYPES = [
|
|
|
29
29
|
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
30
30
|
*/
|
|
31
31
|
export const ENCODER_MODEL_TYPES = ["bert", "modernbert", "model2vec"];
|
|
32
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
33
|
+
export const SPEECH_MODEL_TYPES = ["whisper"];
|
|
32
34
|
/** Files read besides the weights, when the repository has them. */
|
|
33
35
|
export const CHECKPOINT_SIDE_FILES = [
|
|
34
36
|
"config.json",
|
|
@@ -349,8 +351,11 @@ export function estimateMemory(params) {
|
|
|
349
351
|
export function unsupportedReason(modelType) {
|
|
350
352
|
if (modelType === undefined)
|
|
351
353
|
return "no config.json model_type published";
|
|
352
|
-
if (SUPPORTED_MODEL_TYPES.includes(modelType) ||
|
|
354
|
+
if (SUPPORTED_MODEL_TYPES.includes(modelType) ||
|
|
355
|
+
ENCODER_MODEL_TYPES.includes(modelType) ||
|
|
356
|
+
SPEECH_MODEL_TYPES.includes(modelType)) {
|
|
353
357
|
return undefined;
|
|
358
|
+
}
|
|
354
359
|
return `architecture "${modelType}" is not supported yet`;
|
|
355
360
|
}
|
|
356
361
|
/**
|
|
@@ -437,6 +442,8 @@ function toHubModel(entry, maxParams) {
|
|
|
437
442
|
model.gguf = true;
|
|
438
443
|
if (embedding)
|
|
439
444
|
model.embedding = true;
|
|
445
|
+
if (modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType))
|
|
446
|
+
model.speech = true;
|
|
440
447
|
if (architectures !== undefined)
|
|
441
448
|
model.architectures = architectures;
|
|
442
449
|
if (params !== undefined) {
|
|
@@ -546,7 +553,8 @@ export async function checkModel(repo, options = {}) {
|
|
|
546
553
|
hasEmbeddings = true;
|
|
547
554
|
}
|
|
548
555
|
}
|
|
549
|
-
|
|
556
|
+
const speech = modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType);
|
|
557
|
+
if (selected.weights.length > 0 && !hasEmbeddings && !encoder && !speech) {
|
|
550
558
|
reasons.push("unexpected weight layout (no model.embed_tokens.weight)");
|
|
551
559
|
}
|
|
552
560
|
const packed = packedWeightsReason(dtypes);
|
|
@@ -574,6 +582,8 @@ export async function checkModel(repo, options = {}) {
|
|
|
574
582
|
check.modelType = modelType;
|
|
575
583
|
if (embedding)
|
|
576
584
|
check.embedding = true;
|
|
585
|
+
if (speech)
|
|
586
|
+
check.speech = true;
|
|
577
587
|
if (config !== undefined) {
|
|
578
588
|
check.config = config;
|
|
579
589
|
if (shapes.length > 0) {
|
package/dist/index.d.ts
CHANGED
|
@@ -20,10 +20,12 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
|
|
|
20
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";
|
|
21
21
|
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
22
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
23
|
-
export type { Activations, AdapterMode, AdapterSource, 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, 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";
|
|
25
|
+
export type { TrainExample, TrainGroup, TrainLoss, TrainOptimizer, TrainOptions, TrainParams, TrainResult, TrainStep, TrainTeacher, } from "./train.js";
|
|
24
26
|
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
25
27
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
|
|
26
|
-
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
28
|
+
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";
|
|
27
29
|
export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
|
|
28
30
|
export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
|
|
29
31
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
|
package/dist/index.js
CHANGED
|
@@ -20,9 +20,10 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
|
|
|
20
20
|
export { DEFAULT_IMAGE_MODEL, encodePng, GeneratedImage, generateImage, ImageModel, loadImageModel, unloadImageModels, } from "./image.js";
|
|
21
21
|
export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
|
|
22
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
|
|
23
|
+
export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
|
|
23
24
|
export { WebslmError } from "./errors.js";
|
|
24
25
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "./curated.js";
|
|
25
|
-
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, 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";
|
|
26
27
|
export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
|
|
27
28
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
|
|
28
29
|
export { loadWasm } from "./wasm.js";
|
package/dist/models.d.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { EngineClient } from "./client.js";
|
|
3
3
|
import { type CheckpointTraits } from "./curated.js";
|
|
4
4
|
import type { WireSource } from "./protocol.js";
|
|
5
|
-
import
|
|
5
|
+
import { type TrainOptions, type TrainResult } from "./train.js";
|
|
6
|
+
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";
|
|
6
7
|
/**
|
|
7
8
|
* An engine (a worker, or the calling thread) that several models can share
|
|
8
9
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -211,6 +212,50 @@ export declare class Model extends Conversation {
|
|
|
211
212
|
* ```
|
|
212
213
|
*/
|
|
213
214
|
embed(texts: string | readonly string[], options?: EmbedOptions): Promise<Embeddings>;
|
|
215
|
+
/**
|
|
216
|
+
* Transcribes speech with a speech recognition model (Whisper; see
|
|
217
|
+
* {@link ModelInfo.speech}), 30 s at a time, decoding greedily as
|
|
218
|
+
* `transformers` does. `audio` is mono PCM (`Float32Array`, at
|
|
219
|
+
* `options.sampleRate`, 16 kHz by default) or an audio file: WAV
|
|
220
|
+
* everywhere, any format the browser decodes in a page (see
|
|
221
|
+
* {@link AudioInput}). The language is detected unless given;
|
|
222
|
+
* `task: "translate"` translates into English. Rejects with
|
|
223
|
+
* `UNSUPPORTED_TASK` on other models, and with `ABORTED` when
|
|
224
|
+
* `options.signal` fires.
|
|
225
|
+
*
|
|
226
|
+
* ```ts
|
|
227
|
+
* const model = await loadModel("openai/whisper-tiny");
|
|
228
|
+
* const file = await fetch("/speech.mp3").then((r) => r.blob());
|
|
229
|
+
* const { text, language } = await model.transcribe(file, { onToken: (t) => output.append(t) });
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
transcribe(audio: AudioInput, options?: TranscribeOptions): Promise<Transcription>;
|
|
233
|
+
/**
|
|
234
|
+
* Trains LoRA factors (or dense deltas) of chosen layers on token
|
|
235
|
+
* sequences, everything else frozen, and resolves to the trained delta
|
|
236
|
+
* as PEFT adapter files. Llama-like models only (Llama, SmolLM2).
|
|
237
|
+
*
|
|
238
|
+
* The trainer loads its own f32 copy of the weights from the model's
|
|
239
|
+
* source, on WebGPU when there is one (`device`), and drops it at the
|
|
240
|
+
* end: this model is left unchanged until the files are applied with
|
|
241
|
+
* {@link Model.applyAdapter} (whose `scale` multiplies the delta). Each
|
|
242
|
+
* step draws `batchSize` sequences from each group, minimizes
|
|
243
|
+
* `ce · cross-entropy + kl · KL(teacher ‖ model)` with AdamW and calls
|
|
244
|
+
* `onStep`. Rejects with `UNSUPPORTED_MODEL` for other architectures,
|
|
245
|
+
* and with `ABORTED` when `options.signal` fires.
|
|
246
|
+
*
|
|
247
|
+
* ```ts
|
|
248
|
+
* const result = await model.train({
|
|
249
|
+
* steps: 200,
|
|
250
|
+
* params: { method: "lora", rank: 8, targets: ["q_proj", "v_proj"] },
|
|
251
|
+
* optimizer: { lr: 1e-3, warmupSteps: 10 },
|
|
252
|
+
* dataset: texts.map((text) => ({ text })),
|
|
253
|
+
* onStep: (s) => console.log(s.step, s.loss),
|
|
254
|
+
* });
|
|
255
|
+
* await model.applyAdapter({ files: result.files }, { scale: 0.5 });
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
train(options: TrainOptions): Promise<TrainResult>;
|
|
214
259
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
215
260
|
session(): Promise<Session>;
|
|
216
261
|
/**
|
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";
|
|
@@ -7,6 +8,7 @@ import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
|
|
|
7
8
|
import { checkModel, isGgufFile } from "./hub.js";
|
|
8
9
|
import { messageParts, prepareMessages, wireMessage } from "./media.js";
|
|
9
10
|
import { isNode } from "./runtime.js";
|
|
11
|
+
import { wireTrainGroups, wireTrainOptions } from "./train.js";
|
|
10
12
|
const QUANTS = ["q8", "q4", "f32"];
|
|
11
13
|
const ADAPTER_MODES = ["unmerged", "merged"];
|
|
12
14
|
/**
|
|
@@ -773,7 +775,8 @@ export class Model extends Conversation {
|
|
|
773
775
|
throw new WebslmError("INVALID_ARGUMENT", "embed takes a string or an array of strings");
|
|
774
776
|
}
|
|
775
777
|
if (this.#info.embedding === undefined) {
|
|
776
|
-
|
|
778
|
+
const kind = this.#info.speech === undefined ? "a language model" : "a speech recognition model";
|
|
779
|
+
throw new WebslmError("UNSUPPORTED_TASK", `${this.#info.repo ?? this.#info.modelType} is ${kind}; embed needs an embedding model`);
|
|
777
780
|
}
|
|
778
781
|
const result = await this.client.request({
|
|
779
782
|
type: "embed",
|
|
@@ -788,6 +791,114 @@ export class Model extends Conversation {
|
|
|
788
791
|
const vectors = list.map((_, i) => data.subarray(i * dimensions, (i + 1) * dimensions));
|
|
789
792
|
return { vectors, data, dimensions, tokens: Array.from(result.tokens) };
|
|
790
793
|
}
|
|
794
|
+
/**
|
|
795
|
+
* Transcribes speech with a speech recognition model (Whisper; see
|
|
796
|
+
* {@link ModelInfo.speech}), 30 s at a time, decoding greedily as
|
|
797
|
+
* `transformers` does. `audio` is mono PCM (`Float32Array`, at
|
|
798
|
+
* `options.sampleRate`, 16 kHz by default) or an audio file: WAV
|
|
799
|
+
* everywhere, any format the browser decodes in a page (see
|
|
800
|
+
* {@link AudioInput}). The language is detected unless given;
|
|
801
|
+
* `task: "translate"` translates into English. Rejects with
|
|
802
|
+
* `UNSUPPORTED_TASK` on other models, and with `ABORTED` when
|
|
803
|
+
* `options.signal` fires.
|
|
804
|
+
*
|
|
805
|
+
* ```ts
|
|
806
|
+
* const model = await loadModel("openai/whisper-tiny");
|
|
807
|
+
* const file = await fetch("/speech.mp3").then((r) => r.blob());
|
|
808
|
+
* const { text, language } = await model.transcribe(file, { onToken: (t) => output.append(t) });
|
|
809
|
+
* ```
|
|
810
|
+
*/
|
|
811
|
+
async transcribe(audio, options = {}) {
|
|
812
|
+
if (this.#info.speech === undefined) {
|
|
813
|
+
throw new WebslmError("UNSUPPORTED_TASK", `${this.#info.repo ?? this.#info.modelType} is not a speech recognition model; transcribe needs one (Whisper)`);
|
|
814
|
+
}
|
|
815
|
+
if (options.task !== undefined && options.task !== "transcribe" && options.task !== "translate") {
|
|
816
|
+
throw new WebslmError("INVALID_ARGUMENT", 'task must be "transcribe" or "translate"');
|
|
817
|
+
}
|
|
818
|
+
if (isAborted(options.signal))
|
|
819
|
+
throw abortError(options.signal);
|
|
820
|
+
const prepared = await prepareAudio(audio, options.sampleRate);
|
|
821
|
+
const onToken = options.onToken;
|
|
822
|
+
const result = await this.client.request({
|
|
823
|
+
type: "transcribe",
|
|
824
|
+
model: this.modelId,
|
|
825
|
+
audio: prepared.audio,
|
|
826
|
+
options: {
|
|
827
|
+
...(options.language === undefined ? {} : { language: options.language }),
|
|
828
|
+
...(options.task === undefined ? {} : { task: options.task }),
|
|
829
|
+
...(options.maxNewTokens === undefined ? {} : { maxNewTokens: options.maxNewTokens }),
|
|
830
|
+
...(prepared.sampleRate === undefined ? {} : { sampleRate: prepared.sampleRate }),
|
|
831
|
+
},
|
|
832
|
+
}, {
|
|
833
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
834
|
+
...(onToken === undefined ? {} : { onDelta: (delta) => onToken(delta.text) }),
|
|
835
|
+
});
|
|
836
|
+
if (result.stopped && isAborted(options.signal))
|
|
837
|
+
throw abortError(options.signal);
|
|
838
|
+
return {
|
|
839
|
+
text: result.text,
|
|
840
|
+
...(result.language === null ? {} : { language: result.language }),
|
|
841
|
+
duration: result.duration,
|
|
842
|
+
segments: result.segments,
|
|
843
|
+
tokens: result.tokens,
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Trains LoRA factors (or dense deltas) of chosen layers on token
|
|
848
|
+
* sequences, everything else frozen, and resolves to the trained delta
|
|
849
|
+
* as PEFT adapter files. Llama-like models only (Llama, SmolLM2).
|
|
850
|
+
*
|
|
851
|
+
* The trainer loads its own f32 copy of the weights from the model's
|
|
852
|
+
* source, on WebGPU when there is one (`device`), and drops it at the
|
|
853
|
+
* end: this model is left unchanged until the files are applied with
|
|
854
|
+
* {@link Model.applyAdapter} (whose `scale` multiplies the delta). Each
|
|
855
|
+
* step draws `batchSize` sequences from each group, minimizes
|
|
856
|
+
* `ce · cross-entropy + kl · KL(teacher ‖ model)` with AdamW and calls
|
|
857
|
+
* `onStep`. Rejects with `UNSUPPORTED_MODEL` for other architectures,
|
|
858
|
+
* and with `ABORTED` when `options.signal` fires.
|
|
859
|
+
*
|
|
860
|
+
* ```ts
|
|
861
|
+
* const result = await model.train({
|
|
862
|
+
* steps: 200,
|
|
863
|
+
* params: { method: "lora", rank: 8, targets: ["q_proj", "v_proj"] },
|
|
864
|
+
* optimizer: { lr: 1e-3, warmupSteps: 10 },
|
|
865
|
+
* dataset: texts.map((text) => ({ text })),
|
|
866
|
+
* onStep: (s) => console.log(s.step, s.loss),
|
|
867
|
+
* });
|
|
868
|
+
* await model.applyAdapter({ files: result.files }, { scale: 0.5 });
|
|
869
|
+
* ```
|
|
870
|
+
*/
|
|
871
|
+
async train(options) {
|
|
872
|
+
const wireOptions = wireTrainOptions(options);
|
|
873
|
+
if (isAborted(options.signal))
|
|
874
|
+
throw abortError(options.signal);
|
|
875
|
+
const groups = await wireTrainGroups(options, (text) => this.tokenize(text, { addSpecialTokens: true }));
|
|
876
|
+
const onStep = options.onStep;
|
|
877
|
+
const baseModel = options.baseModel ?? this.#info.repo;
|
|
878
|
+
const result = await this.client.request({
|
|
879
|
+
type: "train",
|
|
880
|
+
model: this.modelId,
|
|
881
|
+
options: wireOptions,
|
|
882
|
+
steps: options.steps,
|
|
883
|
+
groups,
|
|
884
|
+
...(options.format === undefined ? {} : { format: options.format }),
|
|
885
|
+
...(baseModel === undefined ? {} : { baseModel }),
|
|
886
|
+
}, {
|
|
887
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
888
|
+
...(this.#base.fetch === undefined ? {} : { onRead: this.#base.fetch }),
|
|
889
|
+
...(onStep === undefined ? {} : { onTrainStep: onStep }),
|
|
890
|
+
});
|
|
891
|
+
const { info } = result;
|
|
892
|
+
return {
|
|
893
|
+
files: result.files,
|
|
894
|
+
steps: result.steps,
|
|
895
|
+
method: info.method,
|
|
896
|
+
trainableParameters: info.trainableParameters,
|
|
897
|
+
modules: info.modules,
|
|
898
|
+
device: info.device,
|
|
899
|
+
...(info.deviceNote === undefined ? {} : { deviceNote: info.deviceNote }),
|
|
900
|
+
};
|
|
901
|
+
}
|
|
791
902
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
792
903
|
async session() {
|
|
793
904
|
const id = await this.client.request({ type: "createSession", model: this.modelId });
|
package/dist/native.d.ts
CHANGED
|
@@ -73,6 +73,16 @@ export interface NativeImageModel {
|
|
|
73
73
|
}>;
|
|
74
74
|
free(): void;
|
|
75
75
|
}
|
|
76
|
+
/** A model being trained on the native engine. */
|
|
77
|
+
export interface NativeTrainer {
|
|
78
|
+
info(): Record<string, unknown>;
|
|
79
|
+
addGroup(groupJson: string): number;
|
|
80
|
+
addExample(group: number, ids: Uint32Array, weights: Float32Array | undefined | null, teacher: string, k: number, teacherIds?: Uint32Array | null, teacherValues?: Float32Array | null): void;
|
|
81
|
+
commit(): Promise<void>;
|
|
82
|
+
step(): Promise<Record<string, unknown>>;
|
|
83
|
+
files(format?: string | null, baseModel?: string | null): Promise<Record<string, Uint8Array>>;
|
|
84
|
+
free(): void;
|
|
85
|
+
}
|
|
76
86
|
export interface NativeModel {
|
|
77
87
|
info(): NativeModelInfo;
|
|
78
88
|
applyAdapter(dir: string, optionsJson: string): Promise<unknown>;
|
|
@@ -91,6 +101,12 @@ export interface NativeModel {
|
|
|
91
101
|
dimensions: number;
|
|
92
102
|
tokens: Uint32Array;
|
|
93
103
|
}>;
|
|
104
|
+
/**
|
|
105
|
+
* Speech recognition models only (`UNSUPPORTED_TASK` otherwise). Resolves
|
|
106
|
+
* to the transcription and `pieces`, the number of `onText` calls (they
|
|
107
|
+
* can arrive after the result).
|
|
108
|
+
*/
|
|
109
|
+
transcribe?(audio: Float32Array | Uint8Array, optionsJson: string, onText: ((text: string) => void) | null, cancel: NativeCancelToken | null): Promise<unknown>;
|
|
94
110
|
free(): void;
|
|
95
111
|
}
|
|
96
112
|
/** The exports of the addon. */
|
|
@@ -111,6 +127,10 @@ export interface NativeAddon {
|
|
|
111
127
|
readonly NativeImageModel?: {
|
|
112
128
|
load(dir: string, optionsJson: string, args?: NativeImageLoadArgs | null): Promise<NativeImageModel>;
|
|
113
129
|
};
|
|
130
|
+
/** Absent from addons older than training support. */
|
|
131
|
+
readonly NativeTrainer?: {
|
|
132
|
+
load(dir: string, optionsJson: string, threads?: number | null): Promise<NativeTrainer>;
|
|
133
|
+
};
|
|
114
134
|
readonly CancelToken: new () => NativeCancelToken;
|
|
115
135
|
}
|
|
116
136
|
/** Where the addon came from, or why it could not load. */
|
package/dist/protocol.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { SerializedError } from "./errors.js";
|
|
|
9
9
|
import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
|
|
10
10
|
import type { ImageModelInfo, ImagePhase, ImageQuant } from "./image.js";
|
|
11
11
|
import type { KvCacheType } from "./memory.js";
|
|
12
|
+
import type { TrainStep, WireTrainGroup } from "./train.js";
|
|
12
13
|
import type { WasmFlavour } from "./wasm-flavour.js";
|
|
13
14
|
/** A model source in a form that can be posted to a worker. */
|
|
14
15
|
export type WireSource = {
|
|
@@ -253,6 +254,21 @@ export type Request = WithId<{
|
|
|
253
254
|
readonly model: number;
|
|
254
255
|
readonly prompt: string;
|
|
255
256
|
readonly options: WireImageOptions;
|
|
257
|
+
} | {
|
|
258
|
+
readonly type: "transcribe";
|
|
259
|
+
readonly model: number;
|
|
260
|
+
/** Mono PCM samples, or the bytes of a WAV file. */
|
|
261
|
+
readonly audio: Float32Array | Uint8Array;
|
|
262
|
+
readonly options: WireTranscribeOptions;
|
|
263
|
+
} | {
|
|
264
|
+
readonly type: "train";
|
|
265
|
+
readonly model: number;
|
|
266
|
+
/** `TrainOptionsJs` as JSON. */
|
|
267
|
+
readonly options: string;
|
|
268
|
+
readonly steps: number;
|
|
269
|
+
readonly groups: readonly WireTrainGroup[];
|
|
270
|
+
readonly format?: "peft" | "dense";
|
|
271
|
+
readonly baseModel?: string;
|
|
256
272
|
} | {
|
|
257
273
|
readonly type: "unload";
|
|
258
274
|
readonly model: number;
|
|
@@ -298,6 +314,10 @@ export type Response = {
|
|
|
298
314
|
readonly phase: ImagePhase;
|
|
299
315
|
readonly step: number;
|
|
300
316
|
readonly steps: number;
|
|
317
|
+
} | {
|
|
318
|
+
readonly type: "trainStep";
|
|
319
|
+
readonly id: number;
|
|
320
|
+
readonly step: TrainStep;
|
|
301
321
|
} | {
|
|
302
322
|
readonly type: "read";
|
|
303
323
|
readonly id: number;
|
|
@@ -313,6 +333,31 @@ export type Response = {
|
|
|
313
333
|
};
|
|
314
334
|
/** Value of an `applyAdapter` result (`removeAdapter` resolves to it or `null`). */
|
|
315
335
|
export type WireLoraResult = LoraInfo;
|
|
336
|
+
/** Options of a `transcribe` request (no signal, no callback). */
|
|
337
|
+
export interface WireTranscribeOptions {
|
|
338
|
+
readonly language?: string;
|
|
339
|
+
readonly task?: "transcribe" | "translate";
|
|
340
|
+
readonly maxNewTokens?: number;
|
|
341
|
+
readonly sampleRate?: number;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Value of a `transcribe` result. Its text streams as `delta` messages
|
|
345
|
+
* (`token` is -1: pieces of text, not tokens).
|
|
346
|
+
*/
|
|
347
|
+
export interface WireTranscription {
|
|
348
|
+
readonly text: string;
|
|
349
|
+
readonly language: string | null;
|
|
350
|
+
readonly duration: number;
|
|
351
|
+
readonly segments: readonly {
|
|
352
|
+
readonly id: number;
|
|
353
|
+
readonly start: number;
|
|
354
|
+
readonly end: number;
|
|
355
|
+
readonly text: string;
|
|
356
|
+
readonly tokens: readonly number[];
|
|
357
|
+
}[];
|
|
358
|
+
readonly tokens: number;
|
|
359
|
+
readonly stopped: boolean;
|
|
360
|
+
}
|
|
316
361
|
/** Value of an `embed` result. */
|
|
317
362
|
export interface WireEmbedResult {
|
|
318
363
|
readonly data: Float32Array;
|
package/dist/train.d.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-device training ({@link Model.train}): options, data and results, and
|
|
3
|
+
* their translation into the `train` request the engine runs.
|
|
4
|
+
*/
|
|
5
|
+
/** Which weights are trained; the rest of the model stays frozen. */
|
|
6
|
+
export interface TrainParams {
|
|
7
|
+
/** `"lora"` (default): LoRA factors of each chosen matrix; `"full"`: a dense delta of the whole matrix. */
|
|
8
|
+
readonly method?: "lora" | "full";
|
|
9
|
+
/** LoRA rank (default 8). */
|
|
10
|
+
readonly rank?: number;
|
|
11
|
+
/** LoRA alpha (default twice the rank): the update is scaled by `alpha / rank`. */
|
|
12
|
+
readonly alpha?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Projections to train (default `["all"]`): `"q_proj"`, `"k_proj"`,
|
|
15
|
+
* `"v_proj"`, `"o_proj"`, `"gate_proj"`, `"up_proj"`, `"down_proj"`, or
|
|
16
|
+
* the groups `"attention"`, `"mlp"`, `"all"`.
|
|
17
|
+
*/
|
|
18
|
+
readonly targets?: readonly string[];
|
|
19
|
+
/** Layer indices to train (default: every layer). */
|
|
20
|
+
readonly layers?: readonly number[];
|
|
21
|
+
}
|
|
22
|
+
/** The loss of a group of examples: `ce · CE + kl · KL(teacher ‖ model)`. */
|
|
23
|
+
export interface TrainLoss {
|
|
24
|
+
/** Weight of the next-token cross-entropy (default 1). */
|
|
25
|
+
readonly ce?: number;
|
|
26
|
+
/** Weight of the KL divergence from the examples' teachers (default 0). */
|
|
27
|
+
readonly kl?: number;
|
|
28
|
+
/**
|
|
29
|
+
* `"token"` (default): mean over the predictions drawn, weighted by
|
|
30
|
+
* their weights; `"sequence"`: sum over each sequence, mean over the
|
|
31
|
+
* sequences.
|
|
32
|
+
*/
|
|
33
|
+
readonly reduction?: "token" | "sequence";
|
|
34
|
+
}
|
|
35
|
+
/** AdamW and its learning-rate schedule. */
|
|
36
|
+
export interface TrainOptimizer {
|
|
37
|
+
/** Peak learning rate (default 5e-4). */
|
|
38
|
+
readonly lr?: number;
|
|
39
|
+
readonly beta1?: number;
|
|
40
|
+
readonly beta2?: number;
|
|
41
|
+
readonly eps?: number;
|
|
42
|
+
/** Decoupled weight decay (default 0). */
|
|
43
|
+
readonly weightDecay?: number;
|
|
44
|
+
/** Linear warmup steps (default 0). */
|
|
45
|
+
readonly warmupSteps?: number;
|
|
46
|
+
/** Decay after warmup (default `"cosine"`, to 0 at the last step). */
|
|
47
|
+
readonly schedule?: "cosine" | "linear" | "constant";
|
|
48
|
+
/**
|
|
49
|
+
* After each step, scales back every trained matrix whose
|
|
50
|
+
* `‖W + Δ‖ / ‖W‖` exceeds `1 + maxNormRatio`.
|
|
51
|
+
*/
|
|
52
|
+
readonly maxNormRatio?: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The distribution an example's KL term pulls the model towards:
|
|
56
|
+
* `"base"` (the model without what is being trained), the `k` most
|
|
57
|
+
* probable tokens of each prediction (the remaining mass forms one tail
|
|
58
|
+
* bucket), or full logits.
|
|
59
|
+
*/
|
|
60
|
+
export type TrainTeacher = "base" | {
|
|
61
|
+
readonly k: number;
|
|
62
|
+
/** `(length - 1) · k` token ids, prediction by prediction. */
|
|
63
|
+
readonly ids: Uint32Array | readonly number[];
|
|
64
|
+
/** Their probabilities. */
|
|
65
|
+
readonly probs: Float32Array | readonly number[];
|
|
66
|
+
} | {
|
|
67
|
+
/** `(length - 1) · vocabSize` logits, prediction by prediction. */
|
|
68
|
+
readonly logits: Float32Array | readonly number[];
|
|
69
|
+
};
|
|
70
|
+
/** One training sequence: position `t` predicts token `t + 1`. */
|
|
71
|
+
export interface TrainExample {
|
|
72
|
+
/** Token ids (at least two). */
|
|
73
|
+
readonly ids?: Uint32Array | readonly number[];
|
|
74
|
+
/** Text, tokenized with the model's tokenizer (special tokens added) when `ids` is absent. */
|
|
75
|
+
readonly text?: string;
|
|
76
|
+
/** Weight of each prediction (`length - 1` values; 0 leaves one out of the loss). */
|
|
77
|
+
readonly weights?: Float32Array | readonly number[];
|
|
78
|
+
/** Teacher of the KL term (none by default). */
|
|
79
|
+
readonly teacher?: TrainTeacher;
|
|
80
|
+
}
|
|
81
|
+
/** A group of examples with its own batch size and loss; a step draws from every group. */
|
|
82
|
+
export interface TrainGroup {
|
|
83
|
+
readonly examples: readonly TrainExample[];
|
|
84
|
+
/** Sequences drawn per step (default 8). */
|
|
85
|
+
readonly batchSize?: number;
|
|
86
|
+
/** Weight of the group's loss in the step's total (default 1). */
|
|
87
|
+
readonly weight?: number;
|
|
88
|
+
readonly loss?: TrainLoss;
|
|
89
|
+
/**
|
|
90
|
+
* `"random"` (default): with replacement, seeded; `"sequential"`: in
|
|
91
|
+
* order, wrapping around; or one sampling weight per example.
|
|
92
|
+
*/
|
|
93
|
+
readonly sampling?: "random" | "sequential" | readonly number[];
|
|
94
|
+
}
|
|
95
|
+
/** Options of {@link Model.train}. */
|
|
96
|
+
export interface TrainOptions {
|
|
97
|
+
/** Optimizer steps. */
|
|
98
|
+
readonly steps: number;
|
|
99
|
+
readonly params?: TrainParams;
|
|
100
|
+
readonly optimizer?: TrainOptimizer;
|
|
101
|
+
/** The examples, as one group (with `batchSize` and `loss`); or give `groups`. */
|
|
102
|
+
readonly dataset?: readonly TrainExample[];
|
|
103
|
+
/** Sequences per step drawn from `dataset` (default 8). */
|
|
104
|
+
readonly batchSize?: number;
|
|
105
|
+
/** Loss of `dataset` (default: cross-entropy). */
|
|
106
|
+
readonly loss?: TrainLoss;
|
|
107
|
+
/** Several groups of examples, each with its batch size and loss. */
|
|
108
|
+
readonly groups?: readonly TrainGroup[];
|
|
109
|
+
/**
|
|
110
|
+
* Rows (tokens) per micro-batch: a step accumulates the gradients of its
|
|
111
|
+
* micro-batches (default about 4096).
|
|
112
|
+
*/
|
|
113
|
+
readonly microBatch?: number;
|
|
114
|
+
/** Recompute activations in the backward pass instead of keeping them (default `true`). */
|
|
115
|
+
readonly checkpointing?: boolean;
|
|
116
|
+
/** Seed of the LoRA initialization and of the sampling (default 0). */
|
|
117
|
+
readonly seed?: number;
|
|
118
|
+
/**
|
|
119
|
+
* Where training runs: `"auto"` (default: the GPU whenever there is
|
|
120
|
+
* one), `"webgpu"` / `"gpu"`, or `"cpu"`.
|
|
121
|
+
*/
|
|
122
|
+
readonly device?: "auto" | "webgpu" | "gpu" | "cpu";
|
|
123
|
+
/**
|
|
124
|
+
* Files of the result: `"peft"` (default: `adapter_config.json` and
|
|
125
|
+
* `adapter_model.safetensors`, which {@link Model.applyAdapter} and PEFT
|
|
126
|
+
* load) or `"dense"` (`delta.safetensors`, one full delta per matrix).
|
|
127
|
+
*/
|
|
128
|
+
readonly format?: "peft" | "dense";
|
|
129
|
+
/** `base_model_name_or_path` of the adapter (default: the model's repository). */
|
|
130
|
+
readonly baseModel?: string;
|
|
131
|
+
/** Called after each step. */
|
|
132
|
+
readonly onStep?: (step: TrainStep) => void;
|
|
133
|
+
/** Stops training before the next step: the promise rejects with an `ABORTED` error. */
|
|
134
|
+
readonly signal?: AbortSignal;
|
|
135
|
+
}
|
|
136
|
+
/** What a step reports. */
|
|
137
|
+
export interface TrainStep {
|
|
138
|
+
/** Index of the step, from 0. */
|
|
139
|
+
readonly step: number;
|
|
140
|
+
/** Learning rate of the step. */
|
|
141
|
+
readonly lr: number;
|
|
142
|
+
/** Total loss (weighted over the groups). */
|
|
143
|
+
readonly loss: number;
|
|
144
|
+
/** Loss of each group. */
|
|
145
|
+
readonly groupLosses: readonly number[];
|
|
146
|
+
/** Predictions in the step. */
|
|
147
|
+
readonly tokens: number;
|
|
148
|
+
/** Matrices that `maxNormRatio` scaled back. */
|
|
149
|
+
readonly clamped: number;
|
|
150
|
+
readonly timeMs: number;
|
|
151
|
+
}
|
|
152
|
+
/** What {@link Model.train} resolves to. */
|
|
153
|
+
export interface TrainResult {
|
|
154
|
+
/**
|
|
155
|
+
* The trained delta as files: `{ files }` loads them back with
|
|
156
|
+
* {@link Model.applyAdapter} (`scale` multiplies the delta).
|
|
157
|
+
*/
|
|
158
|
+
readonly files: Readonly<Record<string, Uint8Array>>;
|
|
159
|
+
readonly steps: readonly TrainStep[];
|
|
160
|
+
readonly method: "lora" | "full";
|
|
161
|
+
/** Trained values. */
|
|
162
|
+
readonly trainableParameters: number;
|
|
163
|
+
/** Trained matrices, e.g. `"model.layers.4.mlp.gate_proj"`. */
|
|
164
|
+
readonly modules: readonly string[];
|
|
165
|
+
/** Where training ran: `"webgpu"`, `"gpu"` (native) or `"cpu"`. */
|
|
166
|
+
readonly device: string;
|
|
167
|
+
readonly deviceNote?: string;
|
|
168
|
+
}
|
|
169
|
+
/** An example as the engine takes it. */
|
|
170
|
+
export interface WireTrainExample {
|
|
171
|
+
readonly ids: Uint32Array;
|
|
172
|
+
readonly weights?: Float32Array;
|
|
173
|
+
readonly teacher: "none" | "base" | "topk" | "logits";
|
|
174
|
+
readonly k: number;
|
|
175
|
+
readonly teacherIds?: Uint32Array;
|
|
176
|
+
readonly teacherValues?: Float32Array;
|
|
177
|
+
}
|
|
178
|
+
/** A group as the engine takes it: options as JSON for `TrainGroupJs`. */
|
|
179
|
+
export interface WireTrainGroup {
|
|
180
|
+
readonly options: string;
|
|
181
|
+
readonly examples: readonly WireTrainExample[];
|
|
182
|
+
}
|
|
183
|
+
/** Value of a `train` result. */
|
|
184
|
+
export interface WireTrainResult {
|
|
185
|
+
readonly files: Record<string, Uint8Array>;
|
|
186
|
+
readonly steps: readonly TrainStep[];
|
|
187
|
+
readonly info: {
|
|
188
|
+
readonly method: "lora" | "full";
|
|
189
|
+
readonly trainableParameters: number;
|
|
190
|
+
readonly modules: readonly string[];
|
|
191
|
+
readonly device: string;
|
|
192
|
+
readonly deviceNote?: string;
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** The options JSON of `Trainer.load` (`TrainOptionsJs`). */
|
|
196
|
+
export declare function wireTrainOptions(options: TrainOptions): string;
|
|
197
|
+
/**
|
|
198
|
+
* The groups of `options` as the engine takes them, texts tokenized with
|
|
199
|
+
* `tokenize`.
|
|
200
|
+
*/
|
|
201
|
+
export declare function wireTrainGroups(options: TrainOptions, tokenize: (text: string) => Promise<Uint32Array>): Promise<WireTrainGroup[]>;
|