webslm 0.2.1 → 0.3.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/dist/hub.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * downloaded by the search and check helpers.
5
5
  */
6
6
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
7
+ import { estimateModelMemory } from "./memory.js";
7
8
  /** Default Hub endpoint. */
8
9
  export const DEFAULT_HUB_URL = "https://huggingface.co";
9
10
  /**
@@ -171,6 +172,29 @@ export function selectCheckpointFiles(names, index) {
171
172
  const weights = names.filter((n) => !n.includes("/") && n.endsWith(".safetensors")).sort();
172
173
  return { side, weights };
173
174
  }
175
+ /** Why an embedding, reranker or classifier checkpoint is refused. */
176
+ export const EMBEDDING_REASON = "embedding model, see #17";
177
+ const ENCODER_PIPELINES = ["feature-extraction", "sentence-similarity", "text-ranking", "text-classification"];
178
+ /**
179
+ * Whether a repository holds an embedding, reranker or classification model
180
+ * rather than one for text generation, even when its architecture is a
181
+ * supported decoder (`Qwen/Qwen3-Embedding-0.6B` is a `qwen3`): an encoder
182
+ * task, the `sentence-transformers` library or its files (`modules.json`,
183
+ * `config_sentence_transformers.json`), and as a last resort a name with
184
+ * `-Embedding` or `-Reranker` in it. The same rules as the CLI.
185
+ */
186
+ export function isEmbeddingModel(info) {
187
+ const st = "sentence-transformers";
188
+ if (info.pipelineTag !== undefined && ENCODER_PIPELINES.includes(info.pipelineTag))
189
+ return true;
190
+ if (info.libraryName === st || info.tags?.includes(st) === true)
191
+ return true;
192
+ if (info.files?.some((f) => f === "modules.json" || f === "config_sentence_transformers.json") === true) {
193
+ return true;
194
+ }
195
+ const name = (info.repo.split("/").pop() ?? "").toLowerCase();
196
+ return name.includes("-embedding") || name.includes("-reranker");
197
+ }
174
198
  const DTYPE_BYTES = {
175
199
  F64: 8,
176
200
  I64: 8,
@@ -234,7 +258,7 @@ export async function searchModels(query, options = {}) {
234
258
  const maxParams = options.maxParams ?? 2e9;
235
259
  const limit = Math.max(1, Math.min(options.limit ?? 20, 100));
236
260
  const params = new URLSearchParams({ search: query.trim(), sort: "downloads", limit: String(limit) });
237
- for (const field of ["safetensors", "config", "gated", "downloads", "pipeline_tag"]) {
261
+ for (const field of ["safetensors", "config", "gated", "downloads", "pipeline_tag", "library_name", "tags"]) {
238
262
  params.append("expand[]", field);
239
263
  }
240
264
  const url = `${hubBase(options.hubUrl)}/api/models?${params.toString()}`;
@@ -262,7 +286,13 @@ function toHubModel(entry, maxParams) {
262
286
  }
263
287
  const total = entry.safetensors?.total;
264
288
  const params = typeof total === "number" ? total : undefined;
265
- let reason = unsupportedReason(modelType);
289
+ const embedding = isEmbeddingModel({
290
+ repo: entry.id,
291
+ pipelineTag: typeof entry.pipeline_tag === "string" ? entry.pipeline_tag : undefined,
292
+ libraryName: typeof entry.library_name === "string" ? entry.library_name : undefined,
293
+ tags: Array.isArray(entry.tags) ? entry.tags.filter((t) => typeof t === "string") : undefined,
294
+ });
295
+ let reason = embedding ? EMBEDDING_REASON : unsupportedReason(modelType);
266
296
  if (reason === undefined && params === undefined)
267
297
  reason = "no safetensors weights";
268
298
  if (reason === undefined)
@@ -341,8 +371,9 @@ export async function checkModel(repo, options = {}) {
341
371
  const reasons = [];
342
372
  const url = (file) => fileUrl(repo, info.sha, file, options.hubUrl);
343
373
  let modelType;
374
+ let config;
344
375
  if (names.includes("config.json")) {
345
- const config = (await fetchJson(url("config.json"), options));
376
+ config = (await fetchJson(url("config.json"), options));
346
377
  modelType = typeof config.model_type === "string" ? config.model_type : undefined;
347
378
  const reason = unsupportedReason(modelType);
348
379
  if (reason !== undefined)
@@ -351,6 +382,8 @@ export async function checkModel(repo, options = {}) {
351
382
  else {
352
383
  reasons.push("no config.json");
353
384
  }
385
+ if (isEmbeddingModel({ repo, files: names }))
386
+ reasons.unshift(EMBEDDING_REASON);
354
387
  const hasTokenizer = names.includes("tokenizer.json");
355
388
  if (!hasTokenizer)
356
389
  reasons.push("no tokenizer.json (only fast tokenizers are supported)");
@@ -367,11 +400,13 @@ export async function checkModel(repo, options = {}) {
367
400
  if (selected.weights.length === 0)
368
401
  reasons.push("no safetensors weights");
369
402
  const dtypes = {};
403
+ const shapes = [];
370
404
  let params = 0;
371
405
  let hasEmbeddings = false;
372
406
  for (const file of selected.weights) {
373
407
  const tensors = await fetchSafetensorsHeader(url(file), options);
374
408
  for (const [name, tensor] of Object.entries(tensors)) {
409
+ shapes.push([name, tensor.shape]);
375
410
  const count = tensor.shape.reduce((n, d) => n * d, 1);
376
411
  params += count;
377
412
  dtypes[tensor.dtype] = (dtypes[tensor.dtype] ?? 0) + count;
@@ -405,5 +440,21 @@ export async function checkModel(repo, options = {}) {
405
440
  };
406
441
  if (modelType !== undefined)
407
442
  check.modelType = modelType;
443
+ if (config !== undefined) {
444
+ check.config = config;
445
+ if (shapes.length > 0) {
446
+ check.tensors = shapes;
447
+ try {
448
+ const estimate = (quant) => estimateModelMemory(config, shapes, {
449
+ quant,
450
+ ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
451
+ });
452
+ check.memory = { q8: estimate("q8"), q4: estimate("q4"), f32: estimate("f32") };
453
+ }
454
+ catch {
455
+ // A config the estimate cannot read: no memory figures.
456
+ }
457
+ }
458
+ }
408
459
  return check;
409
460
  }
package/dist/index.d.ts CHANGED
@@ -18,14 +18,16 @@ import type { SafetensorsHeader } from "./safetensors.js";
18
18
  export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, type Answer, type AskOptions, type Chat, type ChatOptions, type ChatTurnOptions, type LLM, type PromptOptions, type SharedAskOptions, type SharedStreamOptions, type TextStream, } from "./simple.js";
19
19
  export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
20
20
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
21
- export type { Activations, AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
21
+ export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
22
22
  export { WebslmError, type WebslmErrorCode } from "./errors.js";
23
23
  export { CURATED_MODELS, type CuratedModel } from "./curated.js";
24
- export { checkModel, DEFAULT_HUB_URL, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
24
+ export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
25
25
  export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
26
26
  export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
27
27
  export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
28
28
  export { loadWasm, type WasmExports, type WasmSource } from "./wasm.js";
29
+ export { classifyFit, fitModel, fitParams, getBrowserResources, AUTO_QUANTS, WASM_MEMORY_LIMIT, type BrowserResources, type DeviceFit, type DeviceLimits, type FitChoice, type FitLevel, type FitModelOptions, type ModelFit, } from "./fit.js";
30
+ export { estimateModelMemory, type EstimateFormat, type EstimateOptions, type KvLayers, type MemoryEstimate, } from "./memory.js";
29
31
  /** Version of the Rust engine, read from the WebAssembly module. */
30
32
  export declare function version(): Promise<string>;
31
33
  /**
package/dist/index.js CHANGED
@@ -20,10 +20,12 @@ export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js"
20
20
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
21
21
  export { WebslmError } from "./errors.js";
22
22
  export { CURATED_MODELS } from "./curated.js";
23
- export { checkModel, DEFAULT_HUB_URL, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
23
+ export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
24
24
  export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
25
25
  export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
26
26
  export { loadWasm } from "./wasm.js";
27
+ export { classifyFit, fitModel, fitParams, getBrowserResources, AUTO_QUANTS, WASM_MEMORY_LIMIT, } from "./fit.js";
28
+ export { estimateModelMemory, } from "./memory.js";
27
29
  /** Version of the Rust engine, read from the WebAssembly module. */
28
30
  export async function version() {
29
31
  const wasm = await loadWasm();
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Memory a model needs, estimated from its `config.json` and safetensors
3
+ * headers before downloading it: a port of the Rust estimate
4
+ * (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
5
+ * KV cache layer by layer (full attention grows with the context,
6
+ * sliding-window layers keep a ring of `2 × window - 1` positions,
7
+ * convolution and linear-attention layers a fixed state) and the
8
+ * activations of a 512-token prefill. Both implementations are checked
9
+ * against the same cases (`fixtures/memory/estimates.json`).
10
+ */
11
+ import type { HeaderTensors } from "./hub.js";
12
+ import type { Quant } from "./types.js";
13
+ /** Formats an estimate can be made for. */
14
+ export type EstimateFormat = Quant | "f16" | "bf16";
15
+ /** Layers of one kind and the cache they hold. */
16
+ export interface KvLayers {
17
+ readonly layers: number;
18
+ readonly bytes: number;
19
+ }
20
+ /** Memory a model needs in one weight format, in bytes. */
21
+ export interface MemoryEstimate {
22
+ readonly quant: EstimateFormat;
23
+ /** Weights in their stored formats. */
24
+ readonly weights: number;
25
+ /** KV caches and recurrent states of one sequence at `contextLength`. */
26
+ readonly kvCache: number;
27
+ /** What one more position adds to the KV cache. */
28
+ readonly kvPerToken: number;
29
+ /** Activations of a prefill batch. */
30
+ readonly activations: number;
31
+ /** The largest single buffer (WebGPU binds each buffer whole). */
32
+ readonly largestBuffer: number;
33
+ /** Positions the estimate assumes. */
34
+ readonly contextLength: number;
35
+ /**
36
+ * Bytes read per decoded token, on average over a context filled from
37
+ * empty: decoding is bound by memory bandwidth.
38
+ */
39
+ readonly decodeBytes: number;
40
+ /** Weights, caches and activations. */
41
+ readonly total: number;
42
+ /** The KV cache by kind of layer. */
43
+ readonly kvLayers: {
44
+ readonly fullAttention: KvLayers;
45
+ readonly slidingAttention: KvLayers;
46
+ readonly conv: KvLayers;
47
+ readonly linearAttention: KvLayers;
48
+ };
49
+ }
50
+ export interface EstimateOptions {
51
+ /** Weight format (default `"q8"`). */
52
+ readonly quant?: EstimateFormat;
53
+ /** Positions of one sequence (default: min(4096, the model's maximum)). */
54
+ readonly contextLength?: number;
55
+ }
56
+ export type LayerType = "full" | "sliding" | "conv" | "linear";
57
+ /** The text decoder hyperparameters the estimate reads (see `TextConfig` in Rust). */
58
+ export interface TextConfig {
59
+ readonly hiddenSize: number;
60
+ readonly numKeyValueHeads: number;
61
+ readonly headDim: number;
62
+ readonly intermediateSize: number | undefined;
63
+ readonly vocabSize: number | undefined;
64
+ readonly maxPositionEmbeddings: number | undefined;
65
+ readonly tieWordEmbeddings: boolean | undefined;
66
+ readonly layerTypes: readonly LayerType[];
67
+ readonly convKernel: number | undefined;
68
+ readonly slidingWindow: number | undefined;
69
+ readonly linearKeyHeadDim: number | undefined;
70
+ readonly linearNumKeyHeads: number | undefined;
71
+ }
72
+ /** Multimodal configs nest the decoder under `text_config`. */
73
+ export declare function textConfig(config: unknown): TextConfig;
74
+ /** Bytes of a `[rows, cols]` matrix stored in `format` (block formats need whole blocks per row, else f32). */
75
+ export declare function matrixBytes(rows: number, cols: number, format: EstimateFormat): number;
76
+ /**
77
+ * Estimates the memory of loading a checkpoint, from its `config.json`
78
+ * and the tensor shapes of its safetensors headers (no weights are read).
79
+ * Gives the numbers of the Rust engine's own estimate.
80
+ *
81
+ * @throws WebslmError `INVALID_CHECKPOINT` when the config is malformed.
82
+ */
83
+ export declare function estimateModelMemory(config: unknown, tensors: HeaderTensors | Iterable<readonly [string, readonly number[]]>, options?: EstimateOptions): MemoryEstimate;
package/dist/memory.js ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Memory a model needs, estimated from its `config.json` and safetensors
3
+ * headers before downloading it: a port of the Rust estimate
4
+ * (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
5
+ * KV cache layer by layer (full attention grows with the context,
6
+ * sliding-window layers keep a ring of `2 × window - 1` positions,
7
+ * convolution and linear-attention layers a fixed state) and the
8
+ * activations of a 512-token prefill. Both implementations are checked
9
+ * against the same cases (`fixtures/memory/estimates.json`).
10
+ */
11
+ import { WebslmError } from "./errors.js";
12
+ /** Rows of the prefill batch the activation estimate assumes. */
13
+ const PREFILL_ROWS = 512;
14
+ /** Context length when none is given, capped by the model. */
15
+ const DEFAULT_CONTEXT = 4096;
16
+ function isObject(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ /** First present, non-null value among `keys`. */
20
+ function lookup(map, keys) {
21
+ for (const key of keys) {
22
+ const value = map[key];
23
+ if (value !== undefined && value !== null)
24
+ return [key, value];
25
+ }
26
+ return undefined;
27
+ }
28
+ function configError(field, reason) {
29
+ return new WebslmError("INVALID_CHECKPOINT", `invalid model config field \`${field}\`: ${reason}`);
30
+ }
31
+ function optInt(map, keys) {
32
+ const found = lookup(map, keys);
33
+ if (found === undefined)
34
+ return undefined;
35
+ const [key, value] = found;
36
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
37
+ throw configError(key, `expected a non-negative integer, got ${JSON.stringify(value)}`);
38
+ }
39
+ return value;
40
+ }
41
+ function reqInt(map, keys) {
42
+ const value = optInt(map, keys);
43
+ if (value === undefined)
44
+ throw configError(keys[0] ?? "?", "missing");
45
+ return value;
46
+ }
47
+ function optBool(map, keys) {
48
+ const found = lookup(map, keys);
49
+ if (found === undefined)
50
+ return undefined;
51
+ const [key, value] = found;
52
+ if (typeof value !== "boolean")
53
+ throw configError(key, `expected a boolean, got ${JSON.stringify(value)}`);
54
+ return value;
55
+ }
56
+ function parseLayerType(name) {
57
+ switch (name) {
58
+ case "sliding_attention":
59
+ return "sliding";
60
+ case "conv":
61
+ case "short_conv":
62
+ return "conv";
63
+ case "linear_attention":
64
+ return "linear";
65
+ default:
66
+ // Full attention, and unknown types (counted like full attention).
67
+ return "full";
68
+ }
69
+ }
70
+ /** Multimodal configs nest the decoder under `text_config`. */
71
+ export function textConfig(config) {
72
+ if (!isObject(config))
73
+ throw new WebslmError("INVALID_CHECKPOINT", "config.json is not an object");
74
+ const map = isObject(config.text_config) ? { ...config, ...config.text_config } : config;
75
+ const layers = reqInt(map, ["num_hidden_layers", "n_layer", "num_layers"]);
76
+ const heads = reqInt(map, ["num_attention_heads", "num_heads", "n_head"]);
77
+ const kvHeads = optInt(map, ["num_key_value_heads", "n_kv_heads"]) ?? heads;
78
+ const hidden = reqInt(map, ["hidden_size", "n_embd", "d_model"]);
79
+ let layerTypes;
80
+ const listed = lookup(map, ["layer_types"]);
81
+ if (listed !== undefined) {
82
+ const [, value] = listed;
83
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
84
+ throw configError("layer_types", "expected a list of strings");
85
+ }
86
+ if (value.length !== layers) {
87
+ throw configError("layer_types", `${value.length} entries for ${layers} layers`);
88
+ }
89
+ layerTypes = value.map(parseLayerType);
90
+ }
91
+ else {
92
+ const idxs = lookup(map, ["full_attn_idxs"]);
93
+ if (idxs !== undefined && Array.isArray(idxs[1])) {
94
+ // Early LFM2 configs list their attention layers instead.
95
+ const attention = new Set(idxs[1].filter((i) => typeof i === "number"));
96
+ layerTypes = Array.from({ length: layers }, (_, i) => (attention.has(i) ? "full" : "conv"));
97
+ }
98
+ else {
99
+ layerTypes = Array.from({ length: layers }, () => "full");
100
+ }
101
+ }
102
+ const slidingWindow = optBool(map, ["use_sliding_window"]) === false ? undefined : optInt(map, ["sliding_window"]);
103
+ const headDim = optInt(map, ["head_dim"]) ?? Math.floor(hidden / Math.max(heads, 1));
104
+ return {
105
+ hiddenSize: hidden,
106
+ numKeyValueHeads: kvHeads,
107
+ headDim,
108
+ intermediateSize: optInt(map, ["intermediate_size", "block_ff_dim"]),
109
+ vocabSize: optInt(map, ["vocab_size"]),
110
+ maxPositionEmbeddings: optInt(map, ["max_position_embeddings"]),
111
+ tieWordEmbeddings: optBool(map, ["tie_word_embeddings", "tie_embedding"]),
112
+ layerTypes,
113
+ convKernel: optInt(map, ["conv_L_cache", "conv_l_cache", "conv_kernel_size"]),
114
+ slidingWindow,
115
+ linearKeyHeadDim: optInt(map, ["linear_key_head_dim"]),
116
+ linearNumKeyHeads: optInt(map, ["linear_num_key_heads"]),
117
+ };
118
+ }
119
+ /** Values per block and bytes per block of a weight format. */
120
+ function blockOf(format) {
121
+ switch (format) {
122
+ case "f32":
123
+ return [1, 4];
124
+ case "f16":
125
+ case "bf16":
126
+ return [1, 2];
127
+ case "q8":
128
+ // Q8_0: 34 bytes per 32 values.
129
+ return [32, 34];
130
+ case "q4":
131
+ // Q4_0_16 (what "q4" loads): 10 bytes per 16 values.
132
+ return [16, 10];
133
+ }
134
+ }
135
+ /** Bytes of a `[rows, cols]` matrix stored in `format` (block formats need whole blocks per row, else f32). */
136
+ export function matrixBytes(rows, cols, format) {
137
+ const values = rows * cols;
138
+ const [block, bytes] = blockOf(format);
139
+ if (cols % block !== 0)
140
+ return values * 4;
141
+ return Math.floor(values / block) * bytes;
142
+ }
143
+ /** Tensors of parts of the checkpoint the text model does not load (vision tower, projector). */
144
+ function isSkipped(name) {
145
+ return ["vision", "visual", "multi_modal_projector", "mtp."].some((part) => name.includes(part));
146
+ }
147
+ const QUANT_NAMES = ["q8", "q4", "f32", "f16", "bf16"];
148
+ /**
149
+ * Estimates the memory of loading a checkpoint, from its `config.json`
150
+ * and the tensor shapes of its safetensors headers (no weights are read).
151
+ * Gives the numbers of the Rust engine's own estimate.
152
+ *
153
+ * @throws WebslmError `INVALID_CHECKPOINT` when the config is malformed.
154
+ */
155
+ export function estimateModelMemory(config, tensors, options = {}) {
156
+ const quant = options.quant ?? "q8";
157
+ if (!QUANT_NAMES.includes(quant)) {
158
+ throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANT_NAMES.join(", ")}`);
159
+ }
160
+ const text = textConfig(config);
161
+ const embedding = quant === "q4" ? "q8" : quant;
162
+ const tied = text.tieWordEmbeddings === true;
163
+ const entries = Symbol.iterator in tensors
164
+ ? tensors
165
+ : Object.entries(tensors).map(([n, t]) => [n, t.shape]);
166
+ let weights = 0;
167
+ let inputEmbedding = 0;
168
+ let widestMatrix = 0;
169
+ for (const [name, shape] of entries) {
170
+ if (isSkipped(name) || (tied && name.startsWith("lm_head")))
171
+ continue;
172
+ const elements = shape.reduce((n, d) => n * d, 1);
173
+ const [rows, cols] = shape;
174
+ if (shape.length === 2 && rows !== undefined && cols !== undefined) {
175
+ if (name.includes("embed_tokens") || name.startsWith("lm_head")) {
176
+ const bytes = matrixBytes(rows, cols, embedding);
177
+ if (!tied && name.includes("embed_tokens"))
178
+ inputEmbedding += bytes;
179
+ weights += bytes;
180
+ continue;
181
+ }
182
+ if (rows > 1 && cols >= 16 && !name.includes("norm")) {
183
+ widestMatrix = Math.max(widestMatrix, rows);
184
+ weights += matrixBytes(rows, cols, quant);
185
+ continue;
186
+ }
187
+ }
188
+ weights += elements * 4;
189
+ }
190
+ const context = options.contextLength ?? Math.min(text.maxPositionEmbeddings ?? DEFAULT_CONTEXT, DEFAULT_CONTEXT);
191
+ const kvWidth = text.numKeyValueHeads * text.headDim;
192
+ const hidden = text.hiddenSize;
193
+ const fullPerToken = 2 * kvWidth * 4;
194
+ const kv = {
195
+ fullAttention: { layers: 0, bytes: 0 },
196
+ slidingAttention: { layers: 0, bytes: 0 },
197
+ conv: { layers: 0, bytes: 0 },
198
+ linearAttention: { layers: 0, bytes: 0 },
199
+ };
200
+ let kvPerToken = 0;
201
+ for (const layer of text.layerTypes) {
202
+ switch (layer) {
203
+ case "sliding": {
204
+ const window = text.slidingWindow ?? context;
205
+ kv.slidingAttention.layers += 1;
206
+ kv.slidingAttention.bytes += fullPerToken * Math.min(Math.max(2 * window - 1, 0), context);
207
+ break;
208
+ }
209
+ case "conv":
210
+ kv.conv.layers += 1;
211
+ kv.conv.bytes += hidden * 3 * 4 * (text.convKernel ?? 3);
212
+ break;
213
+ case "linear": {
214
+ const heads = text.linearNumKeyHeads ?? 16;
215
+ const dim = text.linearKeyHeadDim ?? 128;
216
+ kv.linearAttention.layers += 1;
217
+ kv.linearAttention.bytes += 2 * heads * dim * dim * 4 + 4 * hidden * 4 * 4;
218
+ break;
219
+ }
220
+ case "full":
221
+ kvPerToken += fullPerToken;
222
+ kv.fullAttention.layers += 1;
223
+ kv.fullAttention.bytes += fullPerToken * context;
224
+ break;
225
+ }
226
+ }
227
+ const kvCache = kv.fullAttention.bytes + kv.slidingAttention.bytes + kv.conv.bytes + kv.linearAttention.bytes;
228
+ const intermediate = text.intermediateSize ?? 4 * hidden;
229
+ const vocab = text.vocabSize ?? 0;
230
+ const rows = Math.min(PREFILL_ROWS, Math.max(context, 1));
231
+ const activations = rows * (6 * hidden + 3 * intermediate) * 4 + vocab * 4;
232
+ const largestBuffer = Math.max(context * kvWidth * 4, rows * 2 * intermediate * 4, rows * Math.max(widestMatrix, hidden) * 4);
233
+ const decodeBytes = weights - inputEmbedding + kvCache - Math.floor((kvPerToken * context) / 2);
234
+ return {
235
+ quant,
236
+ weights,
237
+ kvCache,
238
+ kvPerToken,
239
+ activations,
240
+ largestBuffer,
241
+ contextLength: context,
242
+ decodeBytes,
243
+ total: weights + kvCache + activations,
244
+ kvLayers: kv,
245
+ };
246
+ }
package/dist/models.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
2
  import { EngineClient } from "./client.js";
3
- import type { AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
3
+ import type { AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
4
4
  /**
5
5
  * An engine (a worker, or the calling thread) that several models can share
6
6
  * (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
@@ -72,6 +72,16 @@ export declare function normalizeAdapterSource(source: AdapterSource, revision?:
72
72
  * `~/.cache/webslm` in Node) and read from it afterwards, without network.
73
73
  */
74
74
  export declare function loadModel(source: string | ModelSource, options?: LoadModelOptions): Promise<Model>;
75
+ /**
76
+ * The weight format `quant: "auto"` loads: Q8_0 unless the memory estimate
77
+ * (config.json and the safetensors headers, before downloading) says it does
78
+ * not fit this environment, then Q4 (see {@link fitModel}). Falls back to
79
+ * Q8_0 when the checkpoint cannot be sized (offline, unreadable config).
80
+ */
81
+ export declare function resolveAutoQuant(source: NormalizedSource, options: LoadModelOptions): Promise<{
82
+ quant: Quant;
83
+ note?: string;
84
+ }>;
75
85
  /** Operations shared by {@link Model} (its default session) and {@link Session}. */
76
86
  declare abstract class Conversation {
77
87
  #private;
@@ -129,11 +139,13 @@ export declare class Model extends Conversation {
129
139
  /** Clears the default session's cache. */
130
140
  reset(): Promise<void>;
131
141
  /**
132
- * Merges a PEFT LoRA adapter (`adapter_config.json` and
133
- * `adapter_model.safetensors`, as published on the Hub) into the weights,
134
- * replacing the adapter applied before, if any. The affected base
135
- * matrices are read again from the model's source and merged in f32
136
- * before quantization: decoding runs at the base model's speed.
142
+ * Applies a PEFT LoRA adapter (`adapter_config.json` and
143
+ * `adapter_model.safetensors`, as published on the Hub), replacing the
144
+ * adapter applied before, if any, in the model's `adapterMode` (see
145
+ * {@link AdapterMode}): unmerged (the default), its small f32 factors are
146
+ * uploaded beside the weights; merged, the affected base matrices are
147
+ * read again from the model's source and merged in f32 before
148
+ * quantization.
137
149
  *
138
150
  * Rejects with `INVALID_ADAPTER`, leaving the model unchanged, when the
139
151
  * adapter does not fit the model (a module it does not have, other
package/dist/models.js CHANGED
@@ -2,8 +2,11 @@
2
2
  import { AsyncQueue } from "./async-queue.js";
3
3
  import { EngineClient } from "./client.js";
4
4
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
5
+ import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
6
+ import { checkModel } from "./hub.js";
5
7
  import { isNode } from "./runtime.js";
6
8
  const QUANTS = ["q8", "q4", "f32"];
9
+ const ADAPTER_MODES = ["unmerged", "merged"];
7
10
  /**
8
11
  * An engine (a worker, or the calling thread) that several models can share
9
12
  * (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
@@ -171,17 +174,21 @@ function requestPersistentStorage() {
171
174
  */
172
175
  export async function loadModel(source, options = {}) {
173
176
  const device = resolveDevice(options.device);
174
- const quant = options.quant ?? "q8";
175
- if (!QUANTS.includes(quant)) {
176
- throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")}`);
177
+ const requested = options.quant ?? "q8";
178
+ if (requested !== "auto" && !QUANTS.includes(requested)) {
179
+ throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
177
180
  }
178
181
  const normalized = normalizeSource(source, options.revision);
179
182
  const adapter = options.adapter === undefined ? undefined : normalizeAdapterSource(options.adapter);
180
183
  checkScale(options.adapterScale);
184
+ if (options.adapterMode !== undefined && !ADAPTER_MODES.includes(options.adapterMode)) {
185
+ throw new WebslmError("INVALID_ARGUMENT", `adapterMode must be one of ${ADAPTER_MODES.join(", ")}`);
186
+ }
181
187
  if (isAborted(options.signal))
182
188
  throw abortError(options.signal);
183
189
  if (normalized.kind === "hub" && !isNode())
184
190
  requestPersistentStorage();
191
+ const { quant, note: quantNote } = requested === "auto" ? await resolveAutoQuant(normalized, options) : { quant: requested, note: undefined };
185
192
  const shared = options.engine;
186
193
  if (shared !== undefined && !(shared instanceof EngineHandle)) {
187
194
  throw new WebslmError("INVALID_ARGUMENT", "`engine` must come from createEngine()");
@@ -197,6 +204,7 @@ export async function loadModel(source, options = {}) {
197
204
  quant,
198
205
  device,
199
206
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
207
+ ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
200
208
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
201
209
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
202
210
  ...(options.deterministic === true ? { deterministic: true } : {}),
@@ -210,7 +218,8 @@ export async function loadModel(source, options = {}) {
210
218
  ...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
211
219
  ...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
212
220
  });
213
- return new Model(client, result.model, result.info, {
221
+ const info = quantNote === undefined ? result.info : { ...result.info, quantNote };
222
+ return new Model(client, result.model, info, {
214
223
  ...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
215
224
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
216
225
  }, shared === undefined);
@@ -223,6 +232,61 @@ export async function loadModel(source, options = {}) {
223
232
  throw toWebslmError(error);
224
233
  }
225
234
  }
235
+ /**
236
+ * The weight format `quant: "auto"` loads: Q8_0 unless the memory estimate
237
+ * (config.json and the safetensors headers, before downloading) says it does
238
+ * not fit this environment, then Q4 (see {@link fitModel}). Falls back to
239
+ * Q8_0 when the checkpoint cannot be sized (offline, unreadable config).
240
+ */
241
+ export async function resolveAutoQuant(source, options) {
242
+ try {
243
+ const resources = await getBrowserResources();
244
+ let shapes;
245
+ if (source.kind === "hub") {
246
+ const check = await checkModel(source.repo, {
247
+ ...(source.revision === undefined ? {} : { revision: source.revision }),
248
+ ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
249
+ ...(options.token === undefined ? {} : { token: options.token }),
250
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
251
+ });
252
+ if (check.config === undefined || check.tensors === undefined) {
253
+ throw new WebslmError("INVALID_CHECKPOINT", check.reasons.join("; ") || "no config.json");
254
+ }
255
+ shapes = { config: check.config, tensors: check.tensors, params: check.params };
256
+ }
257
+ else {
258
+ shapes = await readCheckpointShapes(checkpointReader(source));
259
+ }
260
+ return autoQuant(shapes, resources, options.contextLength);
261
+ }
262
+ catch (error) {
263
+ if (isAborted(options.signal))
264
+ throw abortError(options.signal);
265
+ const message = error instanceof Error ? error.message : String(error);
266
+ return { quant: "q8", note: `auto: q8 (the model could not be sized: ${message})` };
267
+ }
268
+ }
269
+ /** Reads the files of a `files` or `fetch` source. */
270
+ function checkpointReader(source) {
271
+ if (source.kind === "fetch") {
272
+ return async (path, range) => {
273
+ const bytes = await source.fetch(path, range);
274
+ if (bytes === null || bytes === undefined)
275
+ return undefined;
276
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
277
+ };
278
+ }
279
+ return async (path, range) => {
280
+ const data = source.files[path];
281
+ if (data === undefined)
282
+ return undefined;
283
+ const [start, end] = range ?? [0, data instanceof Blob ? data.size : data.byteLength];
284
+ if (data instanceof Blob)
285
+ return new Uint8Array(await data.slice(start, end).arrayBuffer());
286
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
287
+ return bytes.subarray(start, end);
288
+ };
289
+ }
226
290
  function wireOptions(options) {
227
291
  const out = {};
228
292
  if (options.maxTokens !== undefined)
@@ -480,11 +544,13 @@ export class Model extends Conversation {
480
544
  await this.client.request({ type: "reset", model: this.modelId });
481
545
  }
482
546
  /**
483
- * Merges a PEFT LoRA adapter (`adapter_config.json` and
484
- * `adapter_model.safetensors`, as published on the Hub) into the weights,
485
- * replacing the adapter applied before, if any. The affected base
486
- * matrices are read again from the model's source and merged in f32
487
- * before quantization: decoding runs at the base model's speed.
547
+ * Applies a PEFT LoRA adapter (`adapter_config.json` and
548
+ * `adapter_model.safetensors`, as published on the Hub), replacing the
549
+ * adapter applied before, if any, in the model's `adapterMode` (see
550
+ * {@link AdapterMode}): unmerged (the default), its small f32 factors are
551
+ * uploaded beside the weights; merged, the affected base matrices are
552
+ * read again from the model's source and merged in f32 before
553
+ * quantization.
488
554
  *
489
555
  * Rejects with `INVALID_ADAPTER`, leaving the model unchanged, when the
490
556
  * adapter does not fit the model (a module it does not have, other