webslm 0.2.1 → 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/README.md +12 -3
- package/dist/fit.d.ts +172 -0
- package/dist/fit.js +309 -0
- package/dist/hub.d.ts +33 -0
- package/dist/hub.js +54 -3
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/memory.d.ts +83 -0
- package/dist/memory.js +246 -0
- package/dist/models.d.ts +11 -1
- package/dist/models.js +63 -4
- package/dist/types.d.ts +9 -2
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
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
|
|
|
@@ -307,16 +307,25 @@ Attention caches rewind for free. Models with recurrent layers (LFM2 and LFM3 sh
|
|
|
307
307
|
## Hub helpers and cache
|
|
308
308
|
|
|
309
309
|
```ts
|
|
310
|
-
import { searchModels, checkModel, listCachedModels, deleteCachedModel, cacheUsage } from "webslm";
|
|
310
|
+
import { searchModels, checkModel, fitModel, listCachedModels, deleteCachedModel, cacheUsage } from "webslm";
|
|
311
311
|
|
|
312
312
|
const results = await searchModels("qwen", { maxParams: 2e9, limit: 20 });
|
|
313
313
|
// [{ repo, supported, reason?, gated, params, sizeBytes, modelType, estimatedMemoryBytes }]
|
|
314
314
|
const check = await checkModel("Qwen/Qwen3-0.6B"); // config, tokenizer, template, safetensors headers by Range
|
|
315
|
+
check.memory?.q8; // { weights, kvCache, activations, total, largestBuffer, kvLayers, ... } at the context length
|
|
316
|
+
|
|
317
|
+
const fit = await fitModel("LiquidAI/LFM3-1.7B", { contextLength: 8192 });
|
|
318
|
+
fit.level; // "fits" | "tight" | "too-big" | "unknown"
|
|
319
|
+
fit.recommended; // { quant: "q8", device: "webgpu", level: "fits", maxContextLength: 65536 }
|
|
320
|
+
fit.devices; // per device: usable memory, fit and longest context per quant
|
|
321
|
+
fit.storage; // { neededBytes, availableBytes, fits }
|
|
315
322
|
await listCachedModels();
|
|
316
323
|
await deleteCachedModel("Qwen/Qwen3-0.6B");
|
|
317
324
|
await cacheUsage(); // { usedBytes, originUsageBytes, quotaBytes, persisted }
|
|
318
325
|
```
|
|
319
326
|
|
|
327
|
+
`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.
|
|
328
|
+
|
|
320
329
|
## Node, Bun and Deno
|
|
321
330
|
|
|
322
331
|
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 +370,7 @@ export default defineConfig({
|
|
|
361
370
|
});
|
|
362
371
|
```
|
|
363
372
|
|
|
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.
|
|
373
|
+
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.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
|
|
365
374
|
|
|
366
375
|
## Errors
|
|
367
376
|
|
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, {
|
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
|
-
|
|
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
|
-
|
|
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();
|
package/dist/memory.d.ts
ADDED
|
@@ -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
|
|
175
|
-
if (!QUANTS.includes(
|
|
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
|
-
|
|
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.
|
|
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",
|
|
Binary file
|
|
Binary file
|
|
Binary file
|