webslm 0.2.0 → 0.3.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/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
@@ -21,11 +21,13 @@ export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session,
21
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";
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;
package/dist/models.js CHANGED
@@ -2,6 +2,8 @@
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"];
7
9
  /**
@@ -171,9 +173,9 @@ function requestPersistentStorage() {
171
173
  */
172
174
  export async function loadModel(source, options = {}) {
173
175
  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(", ")}`);
176
+ const requested = options.quant ?? "q8";
177
+ if (requested !== "auto" && !QUANTS.includes(requested)) {
178
+ throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
177
179
  }
178
180
  const normalized = normalizeSource(source, options.revision);
179
181
  const adapter = options.adapter === undefined ? undefined : normalizeAdapterSource(options.adapter);
@@ -182,6 +184,7 @@ export async function loadModel(source, options = {}) {
182
184
  throw abortError(options.signal);
183
185
  if (normalized.kind === "hub" && !isNode())
184
186
  requestPersistentStorage();
187
+ const { quant, note: quantNote } = requested === "auto" ? await resolveAutoQuant(normalized, options) : { quant: requested, note: undefined };
185
188
  const shared = options.engine;
186
189
  if (shared !== undefined && !(shared instanceof EngineHandle)) {
187
190
  throw new WebslmError("INVALID_ARGUMENT", "`engine` must come from createEngine()");
@@ -210,7 +213,8 @@ export async function loadModel(source, options = {}) {
210
213
  ...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
211
214
  ...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
212
215
  });
213
- return new Model(client, result.model, result.info, {
216
+ const info = quantNote === undefined ? result.info : { ...result.info, quantNote };
217
+ return new Model(client, result.model, info, {
214
218
  ...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
215
219
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
216
220
  }, shared === undefined);
@@ -223,6 +227,61 @@ export async function loadModel(source, options = {}) {
223
227
  throw toWebslmError(error);
224
228
  }
225
229
  }
230
+ /**
231
+ * The weight format `quant: "auto"` loads: Q8_0 unless the memory estimate
232
+ * (config.json and the safetensors headers, before downloading) says it does
233
+ * not fit this environment, then Q4 (see {@link fitModel}). Falls back to
234
+ * Q8_0 when the checkpoint cannot be sized (offline, unreadable config).
235
+ */
236
+ export async function resolveAutoQuant(source, options) {
237
+ try {
238
+ const resources = await getBrowserResources();
239
+ let shapes;
240
+ if (source.kind === "hub") {
241
+ const check = await checkModel(source.repo, {
242
+ ...(source.revision === undefined ? {} : { revision: source.revision }),
243
+ ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
244
+ ...(options.token === undefined ? {} : { token: options.token }),
245
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
246
+ });
247
+ if (check.config === undefined || check.tensors === undefined) {
248
+ throw new WebslmError("INVALID_CHECKPOINT", check.reasons.join("; ") || "no config.json");
249
+ }
250
+ shapes = { config: check.config, tensors: check.tensors, params: check.params };
251
+ }
252
+ else {
253
+ shapes = await readCheckpointShapes(checkpointReader(source));
254
+ }
255
+ return autoQuant(shapes, resources, options.contextLength);
256
+ }
257
+ catch (error) {
258
+ if (isAborted(options.signal))
259
+ throw abortError(options.signal);
260
+ const message = error instanceof Error ? error.message : String(error);
261
+ return { quant: "q8", note: `auto: q8 (the model could not be sized: ${message})` };
262
+ }
263
+ }
264
+ /** Reads the files of a `files` or `fetch` source. */
265
+ function checkpointReader(source) {
266
+ if (source.kind === "fetch") {
267
+ return async (path, range) => {
268
+ const bytes = await source.fetch(path, range);
269
+ if (bytes === null || bytes === undefined)
270
+ return undefined;
271
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
272
+ };
273
+ }
274
+ return async (path, range) => {
275
+ const data = source.files[path];
276
+ if (data === undefined)
277
+ return undefined;
278
+ const [start, end] = range ?? [0, data instanceof Blob ? data.size : data.byteLength];
279
+ if (data instanceof Blob)
280
+ return new Uint8Array(await data.slice(start, end).arrayBuffer());
281
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
282
+ return bytes.subarray(start, end);
283
+ };
284
+ }
226
285
  function wireOptions(options) {
227
286
  const out = {};
228
287
  if (options.maxTokens !== undefined)
package/dist/types.d.ts CHANGED
@@ -101,9 +101,14 @@ export interface LoadModelOptions {
101
101
  readonly device?: Device;
102
102
  /**
103
103
  * Weight format. Defaults to `"q8"`; `"q4"` (4-bit, 16-value blocks) is
104
- * smaller and less accurate.
104
+ * smaller and less accurate. `"auto"` estimates the memory of the model
105
+ * before downloading it (config.json and the safetensors headers) and
106
+ * loads Q8_0 unless it does not fit this environment's memory
107
+ * (`navigator.deviceMemory`, the WebGPU adapter limits, the 4 GiB of
108
+ * WebAssembly), then Q4 ({@link ModelInfo.quantNote} says why; see
109
+ * `fitModel`).
105
110
  */
106
- readonly quant?: Quant;
111
+ readonly quant?: Quant | "auto";
107
112
  /**
108
113
  * Precision of the activations against quantized weights (default
109
114
  * `"quantized"`). With `"f32"`, `quant: "q8"` on a checkpoint whose
@@ -388,6 +393,8 @@ export interface ModelInfo {
388
393
  /** The LoRA adapter merged into the weights, if any. */
389
394
  readonly lora?: LoraInfo;
390
395
  readonly quant: string;
396
+ /** Why `quant: "auto"` did not load Q8_0, when it did not. */
397
+ readonly quantNote?: string;
391
398
  /** Precision of the activations against quantized weights (`"f32"` on WebGPU). */
392
399
  readonly activations: Activations;
393
400
  readonly hiddenSize: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webslm",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Run small language models in the browser and in Node, straight from their original Hugging Face checkpoints: a Rust engine compiled to WebAssembly, in a worker, with an offline cache.",
5
5
  "license": "MIT",
6
6
  "author": "Maxime Golfier",