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/README.md CHANGED
@@ -99,7 +99,7 @@ chat.reset();
99
99
  await llm.unload();
100
100
  ```
101
101
 
102
- `load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
102
+ `load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized, `"auto"` picks `"q8"` unless the model does not fit this environment's memory, then `"q4"`, see [`fitModel`](#hub-helpers-and-cache); `ModelInfo.quantNote` says why), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
103
103
 
104
104
  Each chat keeps its own cache in the engine, so a turn only processes the new message; `chat.dispose()` frees it. Calls on one model, and turns of one chat, run one after the other. `llm.model` is the underlying `Model`, for the advanced API.
105
105
 
@@ -273,19 +273,25 @@ type ModelSource =
273
273
  PEFT LoRA adapters, as published on the Hub (`adapter_config.json` and `adapter_model.safetensors`), from the same kinds of sources as models (a repo id, `{ hub }`, `{ files }` or `{ fetch }`):
274
274
 
275
275
  ```ts
276
- // Merged as the model loads (also with the simple API: `load(model, { adapter })`).
276
+ // Applied as the model loads (also with the simple API: `load(model, { adapter })`).
277
277
  const model = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", {
278
278
  adapter: "user/my-lora",
279
279
  adapterScale: 1, // default
280
+ adapterMode: "unmerged", // default; or "merged"
280
281
  });
281
- model.info().lora; // { modules: ["model.layers.20.self_attn.q_proj", ...], scale, rank, baseModel, repo, revision }
282
+ model.info().lora; // { modules: ["model.layers.20.self_attn.q_proj", ...], scale, rank, mode, baseModel, repo, revision }
282
283
 
283
284
  // Later: swap to another adapter, then back to the base model.
284
285
  await model.applyAdapter({ files: { "adapter_config.json": config, "adapter_model.safetensors": weights } }, { scale: 0.5 });
285
286
  await model.removeAdapter();
286
287
  ```
287
288
 
288
- The adapter is merged into the matrices it targets, `W' = W + (lora_alpha / r) · scale · B·A` (`lora_alpha / sqrt(r)` with `use_rslora`), in f32 before quantization, so decoding runs at the base model's speed. `target_modules` (names, a regular expression or `"all-linear"`), `exclude_modules`, `layers_to_transform`, `layers_pattern`, `rank_pattern` and `alpha_pattern` are honoured. `applyAdapter` reads the affected base matrices again from the model's source (the cache for Hub models; a `fetch` source is called again) and replaces the previous adapter; `removeAdapter` restores the base weights 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.
289
+ With `s = (lora_alpha / r) · scale` (`lora_alpha / sqrt(r)` with `use_rslora`), `adapterMode` (set at load, for every adapter of the model) chooses how an adapter runs:
290
+
291
+ - `"unmerged"` (the default): every adapted layer adds the delta in f32 beside the weights, `y = W·x + s·B(A·x)`, as `peft` computes it. The weights and the adapter each keep their precision: `quant: "q8"` with `activations: "f32"` on a checkpoint whose matrices hold exact Q8_0 values gives the logits of `quant: "f32"` with the same adapter, bit for bit on the CPU. `applyAdapter` and `removeAdapter` only upload or drop the adapter's small f32 factors. Decoding pays two small matmuls per adapted layer (on SmolLM2-135M with one thread, 3 to 5% of the decode speed of Q8_0 and Q4 weights, under 1.5% with f32 weights or f32 activations).
292
+ - `"merged"`: `W' = W + s·B·A` is merged into the matrices it targets in f32 before quantization, so decoding runs at the base model's speed, but quantization rounds the adapter's delta with the weights. `applyAdapter` reads the affected base matrices again from the model's source (the cache for Hub models; a `fetch` source is called again).
293
+
294
+ `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.
289
295
 
290
296
  ## Low-level sessions
291
297
 
@@ -307,16 +313,25 @@ Attention caches rewind for free. Models with recurrent layers (LFM2 and LFM3 sh
307
313
  ## Hub helpers and cache
308
314
 
309
315
  ```ts
310
- import { searchModels, checkModel, listCachedModels, deleteCachedModel, cacheUsage } from "webslm";
316
+ import { searchModels, checkModel, fitModel, listCachedModels, deleteCachedModel, cacheUsage } from "webslm";
311
317
 
312
318
  const results = await searchModels("qwen", { maxParams: 2e9, limit: 20 });
313
319
  // [{ repo, supported, reason?, gated, params, sizeBytes, modelType, estimatedMemoryBytes }]
314
320
  const check = await checkModel("Qwen/Qwen3-0.6B"); // config, tokenizer, template, safetensors headers by Range
321
+ check.memory?.q8; // { weights, kvCache, activations, total, largestBuffer, kvLayers, ... } at the context length
322
+
323
+ const fit = await fitModel("LiquidAI/LFM3-1.7B", { contextLength: 8192 });
324
+ fit.level; // "fits" | "tight" | "too-big" | "unknown"
325
+ fit.recommended; // { quant: "q8", device: "webgpu", level: "fits", maxContextLength: 65536 }
326
+ fit.devices; // per device: usable memory, fit and longest context per quant
327
+ fit.storage; // { neededBytes, availableBytes, fits }
315
328
  await listCachedModels();
316
329
  await deleteCachedModel("Qwen/Qwen3-0.6B");
317
330
  await cacheUsage(); // { usedBytes, originUsageBytes, quotaBytes, persisted }
318
331
  ```
319
332
 
333
+ `fitModel` estimates the memory of each weight format from `config.json` and the safetensors headers (no weights are downloaded): the weights in their load format, the KV cache layer by layer at `contextLength` (full attention grows with the context, sliding-window layers keep a ring of `2 × window - 1` positions, convolution and Gated DeltaNet layers a fixed state) and the activations of a prefill, the same numbers as the Rust engine's estimate (`estimateModelMemory` gives them for any config and tensor shapes). It compares them with what the environment reports: `navigator.deviceMemory` less a reserve for the browser and the OS, the 4 GiB a WebAssembly memory can address (the CPU engine), the largest buffer of the WebGPU adapter, and `navigator.storage.estimate()` for the download (`getBrowserResources()` reads them, `fitParams(params, resources)` gives a quick verdict from a parameter count, as search results carry no config). A model fits below 80% of the usable memory and is tight up to 100%. Browsers round `deviceMemory` down and cap it (8 GiB in Chromium), and do not report GPU memory, so the verdict is conservative.
334
+
320
335
  ## Node, Bun and Deno
321
336
 
322
337
  The same API works in Node 20+ and Bun, as a plain ESM script with no bundler. The cache lives in `WEBSLM_CACHE_DIR` or `~/.cache/webslm` (`cacheDir` in the options overrides it). `WEBSLM_OFFLINE=1` (or `HF_HUB_OFFLINE=1`) forbids network access: models already in the cache load, anything else rejects with `NETWORK`. `HF_ENDPOINT` replaces `https://huggingface.co` (a mirror, or a local stand-in in tests) unless a source gives its own `hubUrl`. The engine runs in a `worker_threads` worker, which does not keep the process alive between calls; pass `worker: false` to run it on the calling thread. Deno 2 runs Hub models as is; for a `files` source of a few hundred megabytes, pass `worker: false` (Deno's `worker_threads` cannot copy buffers that large).
@@ -361,7 +376,7 @@ export default defineConfig({
361
376
  });
362
377
  ```
363
378
 
364
- 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.2.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>.
379
+ 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.3.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>.
365
380
 
366
381
  ## Errors
367
382
 
package/dist/engine.js CHANGED
@@ -366,6 +366,7 @@ export class Engine {
366
366
  ...(options.deterministic === true ? { deterministic: true } : {}),
367
367
  ...(options.activations === undefined ? {} : { activations: options.activations }),
368
368
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
369
+ ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
369
370
  }), adapter === undefined ? undefined : this.#jsSource(adapter, active, () => { }, engine.bindings).source);
370
371
  if (signal.aborted) {
371
372
  wasm.free();
package/dist/fit.d.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Whether a model fits this browser (or Node process), in which weight
3
+ * format, and with how much context, before downloading it. The rules
4
+ * follow `crates/webslm-models/src/fit.rs`: under 80% of the usable memory
5
+ * a model fits, up to 100% it is tight, beyond it is too big; `"auto"`
6
+ * tries Q8_0 then the 4-bit format, each on every device before the next.
7
+ */
8
+ import { type CheckModelOptions, type ModelCheck } from "./hub.js";
9
+ import { type MemoryEstimate } from "./memory.js";
10
+ import type { Quant } from "./types.js";
11
+ /**
12
+ * How a model's memory compares to what a device can hold: under 80% of
13
+ * the usable memory it fits, up to 100% it is tight, beyond (or with one
14
+ * buffer above the device's largest) it is too big. `"unknown"` when the
15
+ * device does not say how much memory it has.
16
+ */
17
+ export type FitLevel = "fits" | "tight" | "too-big" | "unknown";
18
+ /** Classifies `needed` bytes against `usable` bytes. */
19
+ export declare function classifyFit(needed: number, usable: number | undefined): FitLevel;
20
+ /** What the browser (or Node) tells about its memory, storage and GPU. */
21
+ export interface BrowserResources {
22
+ /** `navigator.deviceMemory` in bytes (Chromium; rounded down, at most 8 GiB). */
23
+ readonly deviceMemoryBytes?: number;
24
+ /** Free space for the model cache: quota minus usage of `navigator.storage.estimate()`. */
25
+ readonly storageAvailableBytes?: number;
26
+ /** The WebGPU adapter, when there is one. */
27
+ readonly webgpu?: {
28
+ readonly description: string;
29
+ /** min(maxBufferSize, maxStorageBufferBindingSize): every buffer is bound whole. */
30
+ readonly maxBufferBytes: number;
31
+ };
32
+ }
33
+ /** The globals read by {@link getBrowserResources}; tests pass a stub. */
34
+ export interface ResourceEnvironment {
35
+ readonly navigator?: {
36
+ readonly deviceMemory?: number;
37
+ readonly storage?: {
38
+ estimate?: () => Promise<{
39
+ quota?: number;
40
+ usage?: number;
41
+ }>;
42
+ };
43
+ readonly gpu?: {
44
+ requestAdapter(options?: {
45
+ powerPreference?: "high-performance" | "low-power";
46
+ }): Promise<{
47
+ readonly info?: {
48
+ readonly description?: string;
49
+ readonly vendor?: string;
50
+ };
51
+ readonly limits: {
52
+ readonly maxBufferSize: number;
53
+ readonly maxStorageBufferBindingSize: number;
54
+ };
55
+ } | null>;
56
+ };
57
+ } | undefined;
58
+ }
59
+ /** wasm32 addresses at most 4 GiB: the CPU engine's weights, caches and activations live there. */
60
+ export declare const WASM_MEMORY_LIMIT: number;
61
+ /** Reads the memory, storage and WebGPU limits this environment reports. Missing figures stay undefined. */
62
+ export declare function getBrowserResources(env?: ResourceEnvironment): Promise<BrowserResources>;
63
+ /** What one device can hold. */
64
+ export interface DeviceLimits {
65
+ readonly device: "webgpu" | "cpu";
66
+ /** Bytes a model may use (undefined: unknown). */
67
+ readonly usableBytes?: number;
68
+ /** Largest single buffer. */
69
+ readonly maxBufferBytes?: number;
70
+ /** Where `usableBytes` comes from. */
71
+ readonly source: string;
72
+ }
73
+ /** The devices of `resources`, WebGPU first when there is an adapter. */
74
+ export declare function deviceLimits(resources: BrowserResources): DeviceLimits[];
75
+ /** How an estimate fits a device. */
76
+ export declare function fitLevel(estimate: MemoryEstimate, device: DeviceLimits): FitLevel;
77
+ /**
78
+ * The longest context (at most `limit` positions) whose memory stays under
79
+ * 80% of `usable`, or undefined when even a short one does not fit.
80
+ */
81
+ export declare function maxContextLength(estimate: MemoryEstimate, usable: number, limit: number): number | undefined;
82
+ /** Formats `quant: "auto"` tries, in order: Q8_0 unless memory is short. */
83
+ export declare const AUTO_QUANTS: readonly Quant[];
84
+ /** A recommendation of {@link fitModel}. */
85
+ export interface FitChoice {
86
+ readonly quant: Quant;
87
+ readonly device: "webgpu" | "cpu";
88
+ readonly level: FitLevel;
89
+ /** Longest context that fits, when the device's memory is known. */
90
+ readonly maxContextLength?: number;
91
+ }
92
+ /**
93
+ * The first of `estimates` (formats in order) that fits one of `devices`
94
+ * (in order), else the first that is tight. Formats are tried outer, so a
95
+ * model keeps Q8_0 as long as some device holds it.
96
+ */
97
+ export declare function chooseFit(estimates: readonly MemoryEstimate[], devices: readonly DeviceLimits[], limit?: number): FitChoice | undefined;
98
+ /** One device in a {@link ModelFit}. */
99
+ export interface DeviceFit extends DeviceLimits {
100
+ /** Fit per weight format. */
101
+ readonly levels: Readonly<Record<Quant, FitLevel>>;
102
+ /** Longest context that fits, per weight format. */
103
+ readonly maxContextLength: Readonly<Partial<Record<Quant, number>>>;
104
+ }
105
+ /** Result of {@link fitModel}. */
106
+ export interface ModelFit {
107
+ readonly check: ModelCheck;
108
+ readonly resources: BrowserResources;
109
+ /** Memory per weight format at `contextLength`. */
110
+ readonly memory: Readonly<Record<Quant, MemoryEstimate>>;
111
+ readonly contextLength: number;
112
+ readonly devices: readonly DeviceFit[];
113
+ /** Download size against the free storage (undefined when the browser does not say). */
114
+ readonly storage: {
115
+ readonly neededBytes: number;
116
+ readonly availableBytes?: number;
117
+ readonly fits?: boolean;
118
+ };
119
+ /** What `quant: "auto"` and `device: "auto"` would pick, when something fits. */
120
+ readonly recommended?: FitChoice;
121
+ /** The level of the recommendation, or `"too-big"` when nothing fits. */
122
+ readonly level: FitLevel;
123
+ }
124
+ export interface FitModelOptions extends CheckModelOptions {
125
+ /** Positions of one sequence (default: min(4096, the model's maximum)). */
126
+ readonly contextLength?: number;
127
+ /** Resources to fit against (default: {@link getBrowserResources}). */
128
+ readonly resources?: BrowserResources;
129
+ }
130
+ /**
131
+ * Whether `repo` fits this browser, without downloading weights: memory
132
+ * per weight format (from `config.json` and the safetensors headers, read
133
+ * by Range requests) against `navigator.deviceMemory`, the WebGPU adapter
134
+ * limits and the 4 GiB of WebAssembly, the download against
135
+ * `navigator.storage.estimate()`, and the weight format, device and
136
+ * context length `"auto"` would pick.
137
+ *
138
+ * ```ts
139
+ * const fit = await fitModel("Qwen/Qwen3-0.6B", { contextLength: 8192 });
140
+ * fit.level; // "fits" | "tight" | "too-big" | "unknown"
141
+ * fit.recommended; // { quant: "q8", device: "webgpu", level: "fits", maxContextLength: 40960 }
142
+ * ```
143
+ */
144
+ export declare function fitModel(repo: string, options?: FitModelOptions): Promise<ModelFit>;
145
+ /** {@link fitModel} from a check that kept the config and tensor shapes. */
146
+ export declare function fitFromCheck(check: ModelCheck, resources: BrowserResources, contextLength?: number): ModelFit;
147
+ /**
148
+ * A quick verdict from a parameter count alone (search results carry no
149
+ * config): Q8_0 weights plus 10% and 64 MiB for the runtime, Q4 when Q8_0
150
+ * does not fit, against the devices of `resources`.
151
+ */
152
+ export declare function fitParams(params: number, resources: BrowserResources): {
153
+ readonly quant: Quant;
154
+ readonly level: FitLevel;
155
+ readonly neededBytes: number;
156
+ readonly usableBytes?: number;
157
+ };
158
+ /** Reads a checkpoint file, whole or `[start, end)`; resolves to `undefined` when it does not exist. */
159
+ export type CheckpointReader = (path: string, range?: readonly [number, number]) => Promise<Uint8Array | undefined>;
160
+ /** The parts of a checkpoint an estimate needs. */
161
+ export interface CheckpointShapes {
162
+ readonly config: unknown;
163
+ readonly tensors: readonly (readonly [string, readonly number[]])[];
164
+ readonly params: number;
165
+ }
166
+ /** Reads `config.json` and the safetensors headers (no weights) through `read`. */
167
+ export declare function readCheckpointShapes(read: CheckpointReader): Promise<CheckpointShapes>;
168
+ /** What `quant: "auto"` picks for a checkpoint, and why when it is not Q8_0. */
169
+ export declare function autoQuant(shapes: CheckpointShapes, resources: BrowserResources, contextLength?: number): {
170
+ readonly quant: Quant;
171
+ readonly note?: string;
172
+ };
package/dist/fit.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Whether a model fits this browser (or Node process), in which weight
3
+ * format, and with how much context, before downloading it. The rules
4
+ * follow `crates/webslm-models/src/fit.rs`: under 80% of the usable memory
5
+ * a model fits, up to 100% it is tight, beyond it is too big; `"auto"`
6
+ * tries Q8_0 then the 4-bit format, each on every device before the next.
7
+ */
8
+ import { WebslmError } from "./errors.js";
9
+ import { checkModel } from "./hub.js";
10
+ import { estimateModelMemory, textConfig } from "./memory.js";
11
+ /** Classifies `needed` bytes against `usable` bytes. */
12
+ export function classifyFit(needed, usable) {
13
+ if (usable === undefined)
14
+ return "unknown";
15
+ if (usable <= 0)
16
+ return "too-big";
17
+ const ratio = needed / usable;
18
+ if (ratio < 0.8)
19
+ return "fits";
20
+ if (ratio <= 1)
21
+ return "tight";
22
+ return "too-big";
23
+ }
24
+ const GIB = 1024 ** 3;
25
+ /** wasm32 addresses at most 4 GiB: the CPU engine's weights, caches and activations live there. */
26
+ export const WASM_MEMORY_LIMIT = 4 * GIB;
27
+ /** Reads the memory, storage and WebGPU limits this environment reports. Missing figures stay undefined. */
28
+ export async function getBrowserResources(env = globalThis) {
29
+ const nav = env.navigator;
30
+ const out = {};
31
+ if (typeof nav?.deviceMemory === "number" && nav.deviceMemory > 0) {
32
+ out.deviceMemoryBytes = nav.deviceMemory * GIB;
33
+ }
34
+ try {
35
+ const estimate = await nav?.storage?.estimate?.();
36
+ if (typeof estimate?.quota === "number") {
37
+ out.storageAvailableBytes = Math.max(0, estimate.quota - (estimate.usage ?? 0));
38
+ }
39
+ }
40
+ catch {
41
+ // Storage estimates are unavailable (insecure context, Node).
42
+ }
43
+ try {
44
+ const adapter = await nav?.gpu?.requestAdapter({ powerPreference: "high-performance" });
45
+ if (adapter !== null && adapter !== undefined) {
46
+ out.webgpu = {
47
+ description: adapter.info?.description || adapter.info?.vendor || "WebGPU adapter",
48
+ maxBufferBytes: Math.min(adapter.limits.maxBufferSize, adapter.limits.maxStorageBufferBindingSize),
49
+ };
50
+ }
51
+ }
52
+ catch {
53
+ // No adapter.
54
+ }
55
+ return out;
56
+ }
57
+ /** Memory left to the OS and the rest of the browser: a quarter of RAM, between 1 and 4 GiB (as `webslm fit`). */
58
+ function osReserve(ram) {
59
+ return Math.min(Math.max(ram / 4, GIB), 4 * GIB);
60
+ }
61
+ /** The devices of `resources`, WebGPU first when there is an adapter. */
62
+ export function deviceLimits(resources) {
63
+ const ram = resources.deviceMemoryBytes;
64
+ const ramUsable = ram === undefined ? undefined : ram - osReserve(ram);
65
+ const devices = [];
66
+ if (resources.webgpu !== undefined) {
67
+ devices.push({
68
+ device: "webgpu",
69
+ ...(ramUsable === undefined ? {} : { usableBytes: ramUsable }),
70
+ maxBufferBytes: resources.webgpu.maxBufferBytes,
71
+ source: ramUsable === undefined
72
+ ? "unknown (browsers do not report GPU memory)"
73
+ : "navigator.deviceMemory less a reserve (browsers do not report GPU memory)",
74
+ });
75
+ }
76
+ devices.push({
77
+ device: "cpu",
78
+ usableBytes: ramUsable === undefined ? WASM_MEMORY_LIMIT : Math.min(ramUsable, WASM_MEMORY_LIMIT),
79
+ source: ramUsable === undefined || ramUsable > WASM_MEMORY_LIMIT
80
+ ? "the 4 GiB address space of WebAssembly"
81
+ : "navigator.deviceMemory less a reserve",
82
+ });
83
+ return devices;
84
+ }
85
+ /** How an estimate fits a device. */
86
+ export function fitLevel(estimate, device) {
87
+ if (device.maxBufferBytes !== undefined && estimate.largestBuffer > device.maxBufferBytes)
88
+ return "too-big";
89
+ return classifyFit(estimate.total, device.usableBytes);
90
+ }
91
+ /**
92
+ * The longest context (at most `limit` positions) whose memory stays under
93
+ * 80% of `usable`, or undefined when even a short one does not fit.
94
+ */
95
+ export function maxContextLength(estimate, usable, limit) {
96
+ const fixed = estimate.total - estimate.kvPerToken * estimate.contextLength;
97
+ const free = Math.floor(usable * 0.8) - fixed;
98
+ if (free < 0)
99
+ return undefined;
100
+ const positions = estimate.kvPerToken === 0 ? limit : Math.min(Math.floor(free / estimate.kvPerToken), limit);
101
+ return positions >= Math.min(256, limit) ? positions : undefined;
102
+ }
103
+ /** Formats `quant: "auto"` tries, in order: Q8_0 unless memory is short. */
104
+ export const AUTO_QUANTS = ["q8", "q4"];
105
+ /** Models with more parameters than this run on WebGPU under `device: "auto"` (as the engine decides). */
106
+ const AUTO_GPU_MIN_PARAMS = 100_000_000;
107
+ /**
108
+ * The first of `estimates` (formats in order) that fits one of `devices`
109
+ * (in order), else the first that is tight. Formats are tried outer, so a
110
+ * model keeps Q8_0 as long as some device holds it.
111
+ */
112
+ export function chooseFit(estimates, devices, limit = Number.MAX_SAFE_INTEGER) {
113
+ const candidates = estimates.flatMap((estimate) => devices.map((device) => ({ estimate, device, level: fitLevel(estimate, device) })));
114
+ const chosen = candidates.find((c) => c.level === "fits" || c.level === "unknown") ??
115
+ candidates.find((c) => c.level === "tight");
116
+ if (chosen === undefined)
117
+ return undefined;
118
+ const quant = chosen.estimate.quant;
119
+ if (quant !== "q8" && quant !== "q4" && quant !== "f32")
120
+ return undefined;
121
+ const usable = chosen.device.usableBytes;
122
+ const maxContext = usable === undefined ? undefined : maxContextLength(chosen.estimate, usable, limit);
123
+ return {
124
+ quant,
125
+ device: chosen.device.device,
126
+ level: chosen.level,
127
+ ...(maxContext === undefined ? {} : { maxContextLength: maxContext }),
128
+ };
129
+ }
130
+ const FIT_QUANTS = ["q8", "q4", "f32"];
131
+ /**
132
+ * Whether `repo` fits this browser, without downloading weights: memory
133
+ * per weight format (from `config.json` and the safetensors headers, read
134
+ * by Range requests) against `navigator.deviceMemory`, the WebGPU adapter
135
+ * limits and the 4 GiB of WebAssembly, the download against
136
+ * `navigator.storage.estimate()`, and the weight format, device and
137
+ * context length `"auto"` would pick.
138
+ *
139
+ * ```ts
140
+ * const fit = await fitModel("Qwen/Qwen3-0.6B", { contextLength: 8192 });
141
+ * fit.level; // "fits" | "tight" | "too-big" | "unknown"
142
+ * fit.recommended; // { quant: "q8", device: "webgpu", level: "fits", maxContextLength: 40960 }
143
+ * ```
144
+ */
145
+ export async function fitModel(repo, options = {}) {
146
+ const check = await checkModel(repo, options);
147
+ if (check.config === undefined || check.tensors === undefined) {
148
+ throw new WebslmError("INVALID_CHECKPOINT", `cannot size ${repo}: ${check.reasons.join("; ") || "no config.json or weights"}`);
149
+ }
150
+ const resources = options.resources ?? (await getBrowserResources());
151
+ return fitFromCheck(check, resources, options.contextLength);
152
+ }
153
+ /** {@link fitModel} from a check that kept the config and tensor shapes. */
154
+ export function fitFromCheck(check, resources, contextLength) {
155
+ const config = check.config;
156
+ const tensors = check.tensors ?? [];
157
+ const estimate = (quant) => estimateModelMemory(config, tensors, {
158
+ quant,
159
+ ...(contextLength === undefined ? {} : { contextLength }),
160
+ });
161
+ const memory = { q8: estimate("q8"), q4: estimate("q4"), f32: estimate("f32") };
162
+ const limit = maxPositions(config);
163
+ const all = deviceLimits(resources);
164
+ const devices = all.map((device) => {
165
+ const levels = { q8: "unknown", q4: "unknown", f32: "unknown" };
166
+ const maxContext = {};
167
+ for (const quant of FIT_QUANTS) {
168
+ levels[quant] = fitLevel(memory[quant], device);
169
+ const usable = device.usableBytes;
170
+ const n = usable === undefined ? undefined : maxContextLength(memory[quant], usable, limit);
171
+ if (n !== undefined)
172
+ maxContext[quant] = n;
173
+ }
174
+ return { ...device, levels, maxContextLength: maxContext };
175
+ });
176
+ // `device: "auto"` keeps small models on the CPU.
177
+ const autoDevices = check.params > AUTO_GPU_MIN_PARAMS ? all : all.filter((d) => d.device === "cpu");
178
+ const recommended = chooseFit(AUTO_QUANTS.map((q) => memory[q]), autoDevices, limit);
179
+ const available = resources.storageAvailableBytes;
180
+ return {
181
+ check,
182
+ resources,
183
+ memory,
184
+ contextLength: memory.q8.contextLength,
185
+ devices,
186
+ storage: {
187
+ neededBytes: check.sizeBytes,
188
+ ...(available === undefined ? {} : { availableBytes: available, fits: check.sizeBytes <= available }),
189
+ },
190
+ ...(recommended === undefined ? {} : { recommended }),
191
+ level: recommended?.level ?? "too-big",
192
+ };
193
+ }
194
+ function maxPositions(config) {
195
+ try {
196
+ return textConfig(config).maxPositionEmbeddings ?? Number.MAX_SAFE_INTEGER;
197
+ }
198
+ catch {
199
+ return Number.MAX_SAFE_INTEGER;
200
+ }
201
+ }
202
+ /**
203
+ * A quick verdict from a parameter count alone (search results carry no
204
+ * config): Q8_0 weights plus 10% and 64 MiB for the runtime, Q4 when Q8_0
205
+ * does not fit, against the devices of `resources`.
206
+ */
207
+ export function fitParams(params, resources) {
208
+ const needed = (bytesPerValue) => {
209
+ const weights = params * bytesPerValue;
210
+ return Math.ceil(weights * 1.1 + 64 * 1024 * 1024);
211
+ };
212
+ const devices = deviceLimits(resources).filter((d) => params > AUTO_GPU_MIN_PARAMS || d.device === "cpu");
213
+ let fallback;
214
+ for (const [quant, bytesPerValue] of [
215
+ ["q8", 34 / 32],
216
+ ["q4", 20 / 32],
217
+ ]) {
218
+ for (const device of devices) {
219
+ const neededBytes = needed(bytesPerValue);
220
+ const level = classifyFit(neededBytes, device.usableBytes);
221
+ const verdict = {
222
+ quant,
223
+ level,
224
+ neededBytes,
225
+ ...(device.usableBytes === undefined ? {} : { usableBytes: device.usableBytes }),
226
+ };
227
+ if (level === "fits" || level === "unknown")
228
+ return verdict;
229
+ if (level === "tight" && fallback?.level !== "tight")
230
+ fallback = verdict;
231
+ fallback ??= verdict;
232
+ }
233
+ }
234
+ return fallback ?? { quant: "q8", level: "unknown", neededBytes: needed(34 / 32) };
235
+ }
236
+ const MAX_HEADER_BYTES = 100 * 1024 * 1024;
237
+ /** Reads `config.json` and the safetensors headers (no weights) through `read`. */
238
+ export async function readCheckpointShapes(read) {
239
+ const json = async (path) => {
240
+ const bytes = await read(path);
241
+ return bytes === undefined ? undefined : JSON.parse(new TextDecoder().decode(bytes));
242
+ };
243
+ const config = await json("config.json");
244
+ if (config === undefined)
245
+ throw new WebslmError("INVALID_CHECKPOINT", "no config.json");
246
+ const index = (await json("model.safetensors.index.json"));
247
+ const files = index === undefined ? ["model.safetensors"] : [...new Set(Object.values(index.weight_map ?? {}))].sort();
248
+ const tensors = [];
249
+ let params = 0;
250
+ for (const file of files) {
251
+ const prefix = await read(file, [0, 8]);
252
+ if (prefix === undefined || prefix.length < 8) {
253
+ throw new WebslmError("INVALID_CHECKPOINT", `${file}: no safetensors header`);
254
+ }
255
+ const length = Number(new DataView(prefix.buffer, prefix.byteOffset, 8).getBigUint64(0, true));
256
+ if (length > MAX_HEADER_BYTES) {
257
+ throw new WebslmError("INVALID_CHECKPOINT", `${file}: safetensors header of ${length} bytes`);
258
+ }
259
+ const header = await read(file, [8, 8 + length]);
260
+ if (header === undefined)
261
+ throw new WebslmError("INVALID_CHECKPOINT", `${file}: truncated header`);
262
+ const parsed = JSON.parse(new TextDecoder().decode(header));
263
+ for (const [name, info] of Object.entries(parsed)) {
264
+ if (name === "__metadata__" || !Array.isArray(info.shape))
265
+ continue;
266
+ const shape = info.shape.map(Number);
267
+ tensors.push([name, shape]);
268
+ params += shape.reduce((n, d) => n * d, 1);
269
+ }
270
+ }
271
+ return { config, tensors, params };
272
+ }
273
+ /** What `quant: "auto"` picks for a checkpoint, and why when it is not Q8_0. */
274
+ export function autoQuant(shapes, resources, contextLength) {
275
+ const estimates = AUTO_QUANTS.map((quant) => estimateModelMemory(shapes.config, shapes.tensors, {
276
+ quant,
277
+ ...(contextLength === undefined ? {} : { contextLength }),
278
+ }));
279
+ const all = deviceLimits(resources);
280
+ const devices = shapes.params > AUTO_GPU_MIN_PARAMS ? all : all.filter((d) => d.device === "cpu");
281
+ const choice = chooseFit(estimates, devices);
282
+ const room = devices
283
+ .map((d) => `${d.device} ${d.usableBytes === undefined ? "unknown" : formatSize(d.usableBytes)}`)
284
+ .join(", ");
285
+ const q8 = estimates[0];
286
+ if (choice === undefined) {
287
+ const q4 = estimates[estimates.length - 1];
288
+ return {
289
+ quant: "q4",
290
+ note: `auto: q4, though the model needs about ${formatSize(q4?.total ?? 0)} in 4 bits, more than this environment can use (${room})`,
291
+ };
292
+ }
293
+ if (choice.quant === "q8" || q8 === undefined)
294
+ return { quant: choice.quant };
295
+ return {
296
+ quant: choice.quant,
297
+ note: `auto: ${choice.quant}, because q8 needs about ${formatSize(q8.total)} (${room})`,
298
+ };
299
+ }
300
+ function formatSize(bytes) {
301
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
302
+ let value = bytes;
303
+ let unit = 0;
304
+ while (value >= 1024 && unit < units.length - 1) {
305
+ value /= 1024;
306
+ unit += 1;
307
+ }
308
+ return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${units[unit]}`;
309
+ }
package/dist/hub.d.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  * compatibility checks. Everything here is plain `fetch`; no weights are
4
4
  * downloaded by the search and check helpers.
5
5
  */
6
+ import { type MemoryEstimate } from "./memory.js";
7
+ import type { Quant } from "./types.js";
6
8
  /** Default Hub endpoint. */
7
9
  export declare const DEFAULT_HUB_URL = "https://huggingface.co";
8
10
  /**
@@ -115,6 +117,23 @@ export interface SearchModelsOptions extends HubOptions {
115
117
  /** Drop unsupported repositories from the result (default `false`). */
116
118
  readonly supportedOnly?: boolean;
117
119
  }
120
+ /** Why an embedding, reranker or classifier checkpoint is refused. */
121
+ export declare const EMBEDDING_REASON = "embedding model, see #17";
122
+ /**
123
+ * Whether a repository holds an embedding, reranker or classification model
124
+ * rather than one for text generation, even when its architecture is a
125
+ * supported decoder (`Qwen/Qwen3-Embedding-0.6B` is a `qwen3`): an encoder
126
+ * task, the `sentence-transformers` library or its files (`modules.json`,
127
+ * `config_sentence_transformers.json`), and as a last resort a name with
128
+ * `-Embedding` or `-Reranker` in it. The same rules as the CLI.
129
+ */
130
+ export declare function isEmbeddingModel(info: {
131
+ readonly repo: string;
132
+ readonly pipelineTag?: string | undefined;
133
+ readonly libraryName?: string | undefined;
134
+ readonly tags?: readonly string[] | undefined;
135
+ readonly files?: readonly string[] | undefined;
136
+ }): boolean;
118
137
  /** Bytes of a tensor collection given its parameter count per dtype. */
119
138
  export declare function bytesForParams(paramsByDtype: Readonly<Record<string, number>>): number;
120
139
  /** Weight memory once loaded: Q8_0 stores 34 bytes per 32 values, Q4_0 18. */
@@ -161,15 +180,29 @@ export interface ModelCheck {
161
180
  readonly dtypes: Readonly<Record<string, number>>;
162
181
  /** Bytes to download. */
163
182
  readonly sizeBytes: number;
183
+ /** Weight memory per quant, from the parameter count (see {@link ModelCheck.memory} for the full estimate). */
164
184
  readonly estimatedMemoryBytes: {
165
185
  readonly q8: number;
166
186
  readonly q4: number;
167
187
  readonly f32: number;
168
188
  };
189
+ /** The parsed `config.json`, when the repository has one. */
190
+ readonly config?: unknown;
191
+ /** Names and shapes of the tensors of the safetensors headers. */
192
+ readonly tensors?: readonly (readonly [string, readonly number[]])[];
193
+ /**
194
+ * Memory per weight format (weights, KV cache layer by layer and
195
+ * activations at {@link CheckModelOptions.contextLength}), as the engine
196
+ * estimates it before loading. Absent when the config cannot be read.
197
+ * {@link fitModel} compares it with this browser's resources.
198
+ */
199
+ readonly memory?: Readonly<Record<Quant, MemoryEstimate>>;
169
200
  }
170
201
  export interface CheckModelOptions extends HubOptions {
171
202
  /** Defaults to `"main"`. */
172
203
  readonly revision?: string;
204
+ /** Context length the memory estimate assumes (default: min(4096, the model's maximum)). */
205
+ readonly contextLength?: number;
173
206
  }
174
207
  /** A parsed safetensors header: tensor name to dtype and shape. */
175
208
  export type HeaderTensors = Record<string, {