webslm 0.10.0 → 0.11.1

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
@@ -453,6 +453,37 @@ With `s = (lora_alpha / r) · scale` (`lora_alpha / sqrt(r)` with `use_rslora`),
453
453
 
454
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.
455
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
+
456
487
  ## Low-level sessions
457
488
 
458
489
  ```ts
@@ -572,7 +603,7 @@ export default defineConfig({
572
603
  });
573
604
  ```
574
605
 
575
- 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.10.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.1/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>.
576
607
 
577
608
  ## Errors
578
609
 
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
@@ -236,6 +236,8 @@ export class Engine {
236
236
  }
237
237
  case "transcribe":
238
238
  return [await this.#transcribe(request, signal)];
239
+ case "train":
240
+ return [await this.#train(request, signal)];
239
241
  case "unload": {
240
242
  const image = this.#imageModels.get(request.model);
241
243
  if (image !== undefined) {
@@ -693,6 +695,7 @@ export class Engine {
693
695
  info,
694
696
  active,
695
697
  adapterQueue: Promise.resolve(),
698
+ ...(gguf === undefined ? { trainSource: opened } : {}),
696
699
  });
697
700
  progress({
698
701
  phase: "ready",
@@ -770,6 +773,8 @@ export class Engine {
770
773
  info,
771
774
  active,
772
775
  adapterQueue: Promise.resolve(),
776
+ ...(gguf === undefined ? { trainDir: dir } : {}),
777
+ ...(options.threads === undefined ? {} : { threads: options.threads }),
773
778
  });
774
779
  progress({
775
780
  phase: "ready",
@@ -832,6 +837,58 @@ export class Engine {
832
837
  return removed === null ? null : (lora ?? removed);
833
838
  });
834
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
+ }
835
892
  /**
836
893
  * Loads a text-to-image pipeline (and a standalone decoder): on the
837
894
  * native engine from the snapshot directories the download wrote, else
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type Ca
22
22
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
23
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
24
  export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
25
+ export type { TrainExample, TrainGroup, TrainLoss, TrainOptimizer, TrainOptions, TrainParams, TrainResult, TrainStep, TrainTeacher, } from "./train.js";
25
26
  export { WebslmError, type WebslmErrorCode } from "./errors.js";
26
27
  export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
27
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";
package/dist/models.d.ts CHANGED
@@ -2,6 +2,7 @@
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 { type TrainOptions, type TrainResult } from "./train.js";
5
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
@@ -229,6 +230,32 @@ export declare class Model extends Conversation {
229
230
  * ```
230
231
  */
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>;
232
259
  /** Starts an independent session (its own KV cache) for low-level use. */
233
260
  session(): Promise<Session>;
234
261
  /**
package/dist/models.js CHANGED
@@ -8,6 +8,7 @@ import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
8
8
  import { checkModel, isGgufFile } from "./hub.js";
9
9
  import { messageParts, prepareMessages, wireMessage } from "./media.js";
10
10
  import { isNode } from "./runtime.js";
11
+ import { wireTrainGroups, wireTrainOptions } from "./train.js";
11
12
  const QUANTS = ["q8", "q4", "f32"];
12
13
  const ADAPTER_MODES = ["unmerged", "merged"];
13
14
  /**
@@ -842,6 +843,62 @@ export class Model extends Conversation {
842
843
  tokens: result.tokens,
843
844
  };
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
+ }
845
902
  /** Starts an independent session (its own KV cache) for low-level use. */
846
903
  async session() {
847
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>;
@@ -117,6 +127,10 @@ export interface NativeAddon {
117
127
  readonly NativeImageModel?: {
118
128
  load(dir: string, optionsJson: string, args?: NativeImageLoadArgs | null): Promise<NativeImageModel>;
119
129
  };
130
+ /** Absent from addons older than training support. */
131
+ readonly NativeTrainer?: {
132
+ load(dir: string, optionsJson: string, threads?: number | null): Promise<NativeTrainer>;
133
+ };
120
134
  readonly CancelToken: new () => NativeCancelToken;
121
135
  }
122
136
  /** Where the addon came from, or why it could not load. */
@@ -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 = {
@@ -259,6 +260,15 @@ export type Request = WithId<{
259
260
  /** Mono PCM samples, or the bytes of a WAV file. */
260
261
  readonly audio: Float32Array | Uint8Array;
261
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;
262
272
  } | {
263
273
  readonly type: "unload";
264
274
  readonly model: number;
@@ -304,6 +314,10 @@ export type Response = {
304
314
  readonly phase: ImagePhase;
305
315
  readonly step: number;
306
316
  readonly steps: number;
317
+ } | {
318
+ readonly type: "trainStep";
319
+ readonly id: number;
320
+ readonly step: TrainStep;
307
321
  } | {
308
322
  readonly type: "read";
309
323
  readonly id: number;
@@ -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[]>;
package/dist/train.js ADDED
@@ -0,0 +1,99 @@
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
+ import { WebslmError } from "./errors.js";
6
+ const invalid = (message) => new WebslmError("INVALID_ARGUMENT", message);
7
+ const u32 = (values) => values instanceof Uint32Array ? values : Uint32Array.from(values);
8
+ const f32 = (values) => values instanceof Float32Array ? values : Float32Array.from(values);
9
+ /** The options JSON of `Trainer.load` (`TrainOptionsJs`). */
10
+ export function wireTrainOptions(options) {
11
+ if (!Number.isInteger(options.steps) || options.steps < 1) {
12
+ throw invalid("train: `steps` must be a positive integer");
13
+ }
14
+ const { params = {}, optimizer = {} } = options;
15
+ const device = options.device === "gpu" ? "webgpu" : options.device;
16
+ return JSON.stringify({
17
+ steps: options.steps,
18
+ method: params.method,
19
+ rank: params.rank,
20
+ alpha: params.alpha,
21
+ targets: params.targets,
22
+ layers: params.layers,
23
+ lr: optimizer.lr,
24
+ beta1: optimizer.beta1,
25
+ beta2: optimizer.beta2,
26
+ eps: optimizer.eps,
27
+ weightDecay: optimizer.weightDecay,
28
+ warmupSteps: optimizer.warmupSteps,
29
+ schedule: optimizer.schedule,
30
+ maxNormRatio: optimizer.maxNormRatio,
31
+ microBatch: options.microBatch,
32
+ checkpointing: options.checkpointing,
33
+ seed: options.seed,
34
+ device,
35
+ });
36
+ }
37
+ /**
38
+ * The groups of `options` as the engine takes them, texts tokenized with
39
+ * `tokenize`.
40
+ */
41
+ export async function wireTrainGroups(options, tokenize) {
42
+ const groups = [];
43
+ if (options.dataset !== undefined) {
44
+ groups.push({
45
+ examples: options.dataset,
46
+ ...(options.batchSize === undefined ? {} : { batchSize: options.batchSize }),
47
+ ...(options.loss === undefined ? {} : { loss: options.loss }),
48
+ });
49
+ }
50
+ groups.push(...(options.groups ?? []));
51
+ if (groups.length === 0 || groups.every((g) => g.examples.length === 0)) {
52
+ throw invalid("train: give examples in `dataset` or `groups`");
53
+ }
54
+ const wire = [];
55
+ for (const group of groups) {
56
+ const sampling = group.sampling;
57
+ const groupOptions = JSON.stringify({
58
+ batchSize: group.batchSize,
59
+ weight: group.weight,
60
+ ce: group.loss?.ce,
61
+ kl: group.loss?.kl,
62
+ reduction: group.loss?.reduction,
63
+ ...(Array.isArray(sampling) ? { sampleWeights: sampling } : { sampling }),
64
+ });
65
+ const examples = [];
66
+ for (const example of group.examples) {
67
+ let ids;
68
+ if (example.ids !== undefined)
69
+ ids = u32(example.ids);
70
+ else if (example.text !== undefined)
71
+ ids = await tokenize(example.text);
72
+ else
73
+ throw invalid("train: every example needs `ids` or `text`");
74
+ const teacher = example.teacher;
75
+ const weights = example.weights === undefined ? {} : { weights: f32(example.weights) };
76
+ if (teacher === undefined) {
77
+ examples.push({ ids, ...weights, teacher: "none", k: 0 });
78
+ }
79
+ else if (teacher === "base") {
80
+ examples.push({ ids, ...weights, teacher: "base", k: 0 });
81
+ }
82
+ else if ("logits" in teacher) {
83
+ examples.push({ ids, ...weights, teacher: "logits", k: 0, teacherValues: f32(teacher.logits) });
84
+ }
85
+ else {
86
+ examples.push({
87
+ ids,
88
+ ...weights,
89
+ teacher: "topk",
90
+ k: teacher.k,
91
+ teacherIds: u32(teacher.ids),
92
+ teacherValues: f32(teacher.probs),
93
+ });
94
+ }
95
+ }
96
+ wire.push({ options: groupOptions, examples });
97
+ }
98
+ return wire;
99
+ }