webslm 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +373 -2
- package/dist/ai-sdk/index.d.ts +81 -0
- package/dist/ai-sdk/index.js +90 -0
- package/dist/ai-sdk/language-model.d.ts +77 -0
- package/dist/ai-sdk/language-model.js +422 -0
- package/dist/ai-sdk/loader.d.ts +54 -0
- package/dist/ai-sdk/loader.js +170 -0
- package/dist/ai-sdk/output.d.ts +43 -0
- package/dist/ai-sdk/output.js +152 -0
- package/dist/ai-sdk/prompt.d.ts +21 -0
- package/dist/ai-sdk/prompt.js +111 -0
- package/dist/async-queue.d.ts +22 -0
- package/dist/async-queue.js +70 -0
- package/dist/cache/cache-api.d.ts +29 -0
- package/dist/cache/cache-api.js +115 -0
- package/dist/cache/index.d.ts +21 -0
- package/dist/cache/index.js +42 -0
- package/dist/cache/memory.d.ts +12 -0
- package/dist/cache/memory.js +61 -0
- package/dist/cache/models.d.ts +67 -0
- package/dist/cache/models.js +107 -0
- package/dist/cache/node-fs.d.ts +21 -0
- package/dist/cache/node-fs.js +147 -0
- package/dist/cache/opfs.d.ts +69 -0
- package/dist/cache/opfs.js +181 -0
- package/dist/cache/store.d.ts +53 -0
- package/dist/cache/store.js +64 -0
- package/dist/cache-management.d.ts +23 -0
- package/dist/cache-management.js +58 -0
- package/dist/capabilities.d.ts +67 -0
- package/dist/capabilities.js +55 -0
- package/dist/client.d.ts +61 -0
- package/dist/client.js +256 -0
- package/dist/curated.d.ts +22 -0
- package/dist/curated.js +53 -0
- package/dist/download.d.ts +51 -0
- package/dist/download.js +289 -0
- package/dist/engine.d.ts +54 -0
- package/dist/engine.js +510 -0
- package/dist/errors.d.ts +81 -0
- package/dist/errors.js +89 -0
- package/dist/hub.d.ts +185 -0
- package/dist/hub.js +409 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +41 -0
- package/dist/models.d.ts +225 -0
- package/dist/models.js +730 -0
- package/dist/node-pool-worker.d.ts +6 -0
- package/dist/node-pool-worker.js +32 -0
- package/dist/node-web-worker.d.ts +23 -0
- package/dist/node-web-worker.js +84 -0
- package/dist/node-worker.d.ts +2 -0
- package/dist/node-worker.js +9 -0
- package/dist/pool-worker.d.ts +36 -0
- package/dist/pool-worker.js +30 -0
- package/dist/pool.d.ts +17 -0
- package/dist/pool.js +41 -0
- package/dist/protocol.d.ts +246 -0
- package/dist/protocol.js +19 -0
- package/dist/runtime.d.ts +21 -0
- package/dist/runtime.js +53 -0
- package/dist/safetensors.d.ts +20 -0
- package/dist/safetensors.js +2 -0
- package/dist/simple.d.ts +310 -0
- package/dist/simple.js +553 -0
- package/dist/types.d.ts +412 -0
- package/dist/types.js +2 -0
- package/dist/wasm-flavour.d.ts +85 -0
- package/dist/wasm-flavour.js +169 -0
- package/dist/wasm.d.ts +34 -0
- package/dist/wasm.js +38 -0
- package/dist/worker.d.ts +6 -0
- package/dist/worker.js +11 -0
- package/package.json +92 -3
- package/wasm/relaxed/webslm_wasm.d.ts +325 -0
- package/wasm/relaxed/webslm_wasm.js +1899 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/simd/webslm_wasm.d.ts +325 -0
- package/wasm/simd/webslm_wasm.js +1899 -0
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
- package/wasm/threads/webslm_wasm.d.ts +357 -0
- package/wasm/threads/webslm_wasm.js +2100 -0
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage for downloaded checkpoints.
|
|
3
|
+
*
|
|
4
|
+
* Paths are relative to the cache root and use `/`:
|
|
5
|
+
* `{repo}/{sha}/{file}` for files, `{repo}/{sha}/.webslm.json` for the
|
|
6
|
+
* manifest and `{repo}/refs/{revision}` for resolved revisions. Each backend
|
|
7
|
+
* places that tree somewhere of its own: the `webslm/` directory of OPFS, a
|
|
8
|
+
* Cache API cache, a directory in Node, or memory.
|
|
9
|
+
*/
|
|
10
|
+
/** Splits a cache path into its segments, refusing anything that could escape the root. */
|
|
11
|
+
export function pathSegments(path) {
|
|
12
|
+
const segments = path.split("/").filter((s) => s !== "");
|
|
13
|
+
for (const segment of segments) {
|
|
14
|
+
if (segment === "." || segment === ".." || segment.includes("\\")) {
|
|
15
|
+
throw new Error(`invalid cache path "${path}"`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return segments;
|
|
19
|
+
}
|
|
20
|
+
/** Joins path segments with `/`. */
|
|
21
|
+
export function joinPath(...parts) {
|
|
22
|
+
return parts
|
|
23
|
+
.flatMap((p) => p.split("/"))
|
|
24
|
+
.filter((p) => p !== "")
|
|
25
|
+
.join("/");
|
|
26
|
+
}
|
|
27
|
+
/** Reads a stored UTF-8 text file, `undefined` when absent. */
|
|
28
|
+
export async function readText(store, path) {
|
|
29
|
+
if ((await store.size(path)) === undefined)
|
|
30
|
+
return undefined;
|
|
31
|
+
return new TextDecoder().decode(await store.read(path));
|
|
32
|
+
}
|
|
33
|
+
/** Writes a whole UTF-8 text file. */
|
|
34
|
+
export async function writeText(store, path, text) {
|
|
35
|
+
const writer = await store.openWriter(path, 0);
|
|
36
|
+
try {
|
|
37
|
+
await writer.write(new TextEncoder().encode(text));
|
|
38
|
+
await writer.close();
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
await writer.abort();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Concatenates chunks into one array. */
|
|
46
|
+
export function concatChunks(chunks, total) {
|
|
47
|
+
const length = total ?? chunks.reduce((n, c) => n + c.length, 0);
|
|
48
|
+
const out = new Uint8Array(length);
|
|
49
|
+
let offset = 0;
|
|
50
|
+
for (const chunk of chunks) {
|
|
51
|
+
out.set(chunk, offset);
|
|
52
|
+
offset += chunk.length;
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
/** Validates a `[start, end)` range against a file size and returns it resolved. */
|
|
57
|
+
export function resolveRange(path, size, start, end) {
|
|
58
|
+
const s = start ?? 0;
|
|
59
|
+
const e = end ?? size;
|
|
60
|
+
if (!Number.isInteger(s) || !Number.isInteger(e) || s < 0 || e < s || e > size) {
|
|
61
|
+
throw new RangeError(`range ${s}..${e} is outside "${path}" (${size} bytes)`);
|
|
62
|
+
}
|
|
63
|
+
return [s, e];
|
|
64
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Listing and removing cached models, and reporting storage use. */
|
|
2
|
+
import { type CachedModel } from "./cache/models.js";
|
|
3
|
+
export type { CachedModel, CachedRevision } from "./cache/models.js";
|
|
4
|
+
export interface CacheOptions {
|
|
5
|
+
/** Cache directory in Node (default `WEBSLM_CACHE_DIR` or `~/.cache/webslm`). */
|
|
6
|
+
readonly cacheDir?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Models downloaded into the cache (OPFS and Cache API in browsers, the cache directory in Node). */
|
|
9
|
+
export declare function listCachedModels(options?: CacheOptions): Promise<CachedModel[]>;
|
|
10
|
+
/** Removes every cached revision of `repo`. Resolves even when it was not cached. */
|
|
11
|
+
export declare function deleteCachedModel(repo: string, options?: CacheOptions): Promise<void>;
|
|
12
|
+
/** Storage used by webslm and, in browsers, the origin's usage and quota. */
|
|
13
|
+
export interface CacheUsage {
|
|
14
|
+
/** Bytes held by webslm's cache. */
|
|
15
|
+
readonly usedBytes: number;
|
|
16
|
+
/** Bytes used by the whole origin (browsers), from `navigator.storage.estimate()`. */
|
|
17
|
+
readonly originUsageBytes?: number;
|
|
18
|
+
/** Bytes the origin may use (browsers). */
|
|
19
|
+
readonly quotaBytes?: number;
|
|
20
|
+
/** Whether the browser granted persistent storage. */
|
|
21
|
+
readonly persisted?: boolean;
|
|
22
|
+
}
|
|
23
|
+
export declare function cacheUsage(options?: CacheOptions): Promise<CacheUsage>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Listing and removing cached models, and reporting storage use. */
|
|
2
|
+
import { openAllStores } from "./cache/index.js";
|
|
3
|
+
import { cacheBytesIn, checkRepoId, deleteCachedModelIn, listCachedModelsIn, } from "./cache/models.js";
|
|
4
|
+
import { toWebslmError, WebslmError } from "./errors.js";
|
|
5
|
+
/** Models downloaded into the cache (OPFS and Cache API in browsers, the cache directory in Node). */
|
|
6
|
+
export async function listCachedModels(options = {}) {
|
|
7
|
+
try {
|
|
8
|
+
const stores = await openAllStores(options);
|
|
9
|
+
const lists = await Promise.all(stores.map((s) => listCachedModelsIn(s)));
|
|
10
|
+
return lists.flat().sort((a, b) => a.repo.localeCompare(b.repo));
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
throw toWebslmError(error, "CACHE");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Removes every cached revision of `repo`. Resolves even when it was not cached. */
|
|
17
|
+
export async function deleteCachedModel(repo, options = {}) {
|
|
18
|
+
let id;
|
|
19
|
+
try {
|
|
20
|
+
id = checkRepoId(repo);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
throw new WebslmError("INVALID_ARGUMENT", error.message);
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
for (const store of await openAllStores(options))
|
|
27
|
+
await deleteCachedModelIn(store, id);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw toWebslmError(error, "CACHE");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export async function cacheUsage(options = {}) {
|
|
34
|
+
let usedBytes = 0;
|
|
35
|
+
try {
|
|
36
|
+
for (const store of await openAllStores(options))
|
|
37
|
+
usedBytes += await cacheBytesIn(store);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw toWebslmError(error, "CACHE");
|
|
41
|
+
}
|
|
42
|
+
const storage = globalThis.navigator?.storage;
|
|
43
|
+
const usage = { usedBytes };
|
|
44
|
+
try {
|
|
45
|
+
const estimate = await storage?.estimate?.();
|
|
46
|
+
if (estimate?.usage !== undefined)
|
|
47
|
+
usage.originUsageBytes = estimate.usage;
|
|
48
|
+
if (estimate?.quota !== undefined)
|
|
49
|
+
usage.quotaBytes = estimate.quota;
|
|
50
|
+
const persisted = await storage?.persisted?.();
|
|
51
|
+
if (persisted !== undefined)
|
|
52
|
+
usage.persisted = persisted;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Estimates are best effort.
|
|
56
|
+
}
|
|
57
|
+
return usage;
|
|
58
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime feature detection, used to pick the fastest available backend.
|
|
3
|
+
*/
|
|
4
|
+
/** What the current JavaScript environment can do. */
|
|
5
|
+
export interface Capabilities {
|
|
6
|
+
/** `navigator.gpu` is exposed. An adapter may still be unavailable. */
|
|
7
|
+
readonly webgpu: boolean;
|
|
8
|
+
/** The page is cross-origin isolated (COOP + COEP), enabling `SharedArrayBuffer`. */
|
|
9
|
+
readonly crossOriginIsolated: boolean;
|
|
10
|
+
/** WebAssembly SIMD128 is supported. Required by the CPU backend. */
|
|
11
|
+
readonly simd: boolean;
|
|
12
|
+
/** Multithreaded WebAssembly is possible (isolation + `SharedArrayBuffer`). */
|
|
13
|
+
readonly threads: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The globals read by {@link detectCapabilities}. Defaults to `globalThis`;
|
|
17
|
+
* tests pass a stub instead.
|
|
18
|
+
*/
|
|
19
|
+
export interface CapabilityEnvironment {
|
|
20
|
+
readonly navigator?: {
|
|
21
|
+
readonly gpu?: unknown;
|
|
22
|
+
} | undefined;
|
|
23
|
+
readonly crossOriginIsolated?: boolean | undefined;
|
|
24
|
+
readonly WebAssembly?: {
|
|
25
|
+
validate(bytes: BufferSource): boolean;
|
|
26
|
+
} | undefined;
|
|
27
|
+
readonly SharedArrayBuffer?: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Reports which acceleration features are available, synchronously. */
|
|
30
|
+
export declare function detectCapabilities(env?: CapabilityEnvironment): Capabilities;
|
|
31
|
+
/** The adapter returned by {@link GpuLike.requestAdapter}. */
|
|
32
|
+
export interface GpuAdapterLike {
|
|
33
|
+
readonly info: {
|
|
34
|
+
readonly vendor: string;
|
|
35
|
+
readonly architecture: string;
|
|
36
|
+
readonly device: string;
|
|
37
|
+
readonly description: string;
|
|
38
|
+
};
|
|
39
|
+
readonly features: {
|
|
40
|
+
has(feature: string): boolean;
|
|
41
|
+
};
|
|
42
|
+
readonly limits: {
|
|
43
|
+
readonly maxStorageBufferBindingSize: number;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The subset of `GPU` (`navigator.gpu`) used here, so consumers need no WebGPU typings. */
|
|
47
|
+
export interface GpuLike {
|
|
48
|
+
requestAdapter(options?: {
|
|
49
|
+
powerPreference?: "low-power" | "high-performance";
|
|
50
|
+
}): Promise<GpuAdapterLike | null>;
|
|
51
|
+
}
|
|
52
|
+
/** Description of the WebGPU adapter the browser would hand out. */
|
|
53
|
+
export interface WebGpuAdapterSummary {
|
|
54
|
+
readonly vendor: string;
|
|
55
|
+
readonly architecture: string;
|
|
56
|
+
readonly device: string;
|
|
57
|
+
readonly description: string;
|
|
58
|
+
/** Whether `shader-f16` is available, which halves weight bandwidth. */
|
|
59
|
+
readonly shaderF16: boolean;
|
|
60
|
+
/** Largest storage buffer binding, which bounds the size of a weight matrix. */
|
|
61
|
+
readonly maxStorageBufferBindingSize: number;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Requests a high-performance WebGPU adapter and summarizes it.
|
|
65
|
+
* Resolves to `null` when WebGPU is missing or no adapter is available.
|
|
66
|
+
*/
|
|
67
|
+
export declare function getWebGpuAdapterSummary(gpu?: GpuLike | undefined): Promise<WebGpuAdapterSummary | null>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime feature detection, used to pick the fastest available backend.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Smallest module using a SIMD128 instruction (`i8x16.splat` +
|
|
6
|
+
* `i8x16.popcnt`); it only validates when SIMD is supported.
|
|
7
|
+
*/
|
|
8
|
+
const SIMD_PROBE = new Uint8Array([
|
|
9
|
+
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b, 0x03,
|
|
10
|
+
0x02, 0x01, 0x00, 0x0a, 0x0a, 0x01, 0x08, 0x00, 0x41, 0x00, 0xfd, 0x0f, 0xfd, 0x62, 0x0b,
|
|
11
|
+
]);
|
|
12
|
+
/** Reports which acceleration features are available, synchronously. */
|
|
13
|
+
export function detectCapabilities(env = globalThis) {
|
|
14
|
+
const webgpu = env.navigator?.gpu != null;
|
|
15
|
+
const crossOriginIsolated = env.crossOriginIsolated === true;
|
|
16
|
+
const simd = supportsSimd(env.WebAssembly);
|
|
17
|
+
const threads = crossOriginIsolated && typeof env.SharedArrayBuffer === "function";
|
|
18
|
+
return { webgpu, crossOriginIsolated, simd, threads };
|
|
19
|
+
}
|
|
20
|
+
function supportsSimd(wasm) {
|
|
21
|
+
if (wasm === undefined)
|
|
22
|
+
return false;
|
|
23
|
+
try {
|
|
24
|
+
return wasm.validate(SIMD_PROBE);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Requests a high-performance WebGPU adapter and summarizes it.
|
|
32
|
+
* Resolves to `null` when WebGPU is missing or no adapter is available.
|
|
33
|
+
*/
|
|
34
|
+
export async function getWebGpuAdapterSummary(gpu = globalThis.navigator?.gpu) {
|
|
35
|
+
if (gpu === undefined)
|
|
36
|
+
return null;
|
|
37
|
+
let adapter;
|
|
38
|
+
try {
|
|
39
|
+
adapter = await gpu.requestAdapter({ powerPreference: "high-performance" });
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
if (adapter === null)
|
|
45
|
+
return null;
|
|
46
|
+
const { vendor, architecture, device, description } = adapter.info;
|
|
47
|
+
return {
|
|
48
|
+
vendor,
|
|
49
|
+
architecture,
|
|
50
|
+
device,
|
|
51
|
+
description,
|
|
52
|
+
shaderF16: adapter.features.has("shader-f16"),
|
|
53
|
+
maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of the worker protocol: starts the engine (module Worker,
|
|
3
|
+
* `worker_threads`, or in-thread), sends requests and routes answers.
|
|
4
|
+
*/
|
|
5
|
+
import { WebslmError } from "./errors.js";
|
|
6
|
+
import type { Request, Response } from "./protocol.js";
|
|
7
|
+
import type { FetchFile, LoadProgress } from "./types.js";
|
|
8
|
+
type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
|
|
9
|
+
/** A bidirectional message channel to an engine. */
|
|
10
|
+
export interface Channel {
|
|
11
|
+
post(message: Request, transfer?: Transferable[]): void;
|
|
12
|
+
/** Stops the engine. */
|
|
13
|
+
terminate(): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Called when the first request starts and when the last one ends. A Node
|
|
16
|
+
* worker only keeps the process alive while requests are pending, so a
|
|
17
|
+
* script that never unloads its model still exits.
|
|
18
|
+
*/
|
|
19
|
+
setBusy?(busy: boolean): void;
|
|
20
|
+
}
|
|
21
|
+
export interface ChannelHandlers {
|
|
22
|
+
message(message: Response): void;
|
|
23
|
+
/** The engine died: every pending request fails with `error`. */
|
|
24
|
+
fatal(error: WebslmError): void;
|
|
25
|
+
}
|
|
26
|
+
/** Hooks of one request. */
|
|
27
|
+
export interface RequestHooks {
|
|
28
|
+
readonly onProgress?: (progress: LoadProgress) => void;
|
|
29
|
+
readonly onDelta?: (delta: Extract<Response, {
|
|
30
|
+
type: "delta";
|
|
31
|
+
}>) => void;
|
|
32
|
+
/** Progress of the prompt of a generation. */
|
|
33
|
+
readonly onPrefill?: (done: number, total: number) => void;
|
|
34
|
+
/** Serves reads of a `fetch` model source. */
|
|
35
|
+
readonly onRead?: FetchFile;
|
|
36
|
+
/** Serves reads of a `fetch` LoRA adapter source. */
|
|
37
|
+
readonly onAdapterRead?: FetchFile;
|
|
38
|
+
readonly signal?: AbortSignal;
|
|
39
|
+
readonly transfer?: Transferable[];
|
|
40
|
+
}
|
|
41
|
+
/** Sends requests to an engine and matches the answers. */
|
|
42
|
+
export declare class EngineClient {
|
|
43
|
+
#private;
|
|
44
|
+
private constructor();
|
|
45
|
+
/** Starts an engine: a worker unless `worker` is `false`. */
|
|
46
|
+
static start(options?: {
|
|
47
|
+
worker?: boolean;
|
|
48
|
+
}): Promise<EngineClient>;
|
|
49
|
+
/** @internal Wraps a custom channel (tests, custom transports). */
|
|
50
|
+
static fromChannel(start: (handlers: ChannelHandlers) => Channel): EngineClient;
|
|
51
|
+
/** Sends a request; resolves with its result. */
|
|
52
|
+
request<T>(body: RequestBody, hooks?: RequestHooks): Promise<T>;
|
|
53
|
+
/** Asks the engine to cancel request `id`. */
|
|
54
|
+
abort(id: number): void;
|
|
55
|
+
terminate(): Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
/** @internal The module Worker of browsers (exported for tests). */
|
|
58
|
+
export declare function browserWorkerChannel(): (handlers: ChannelHandlers) => Channel;
|
|
59
|
+
/** @internal Appended to errors of a Node worker that fails to start. */
|
|
60
|
+
export declare const NODE_WORKER_HINT: string;
|
|
61
|
+
export {};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of the worker protocol: starts the engine (module Worker,
|
|
3
|
+
* `worker_threads`, or in-thread), sends requests and routes answers.
|
|
4
|
+
*/
|
|
5
|
+
import { WebslmError, abortError, deserializeError, serializeError } from "./errors.js";
|
|
6
|
+
import { importingWorkerUrl, importNode, isNode, isSecurityError } from "./runtime.js";
|
|
7
|
+
/** Sends requests to an engine and matches the answers. */
|
|
8
|
+
export class EngineClient {
|
|
9
|
+
#channel;
|
|
10
|
+
#pending = new Map();
|
|
11
|
+
#nextId = 1;
|
|
12
|
+
#dead;
|
|
13
|
+
constructor(start) {
|
|
14
|
+
this.#channel = start({
|
|
15
|
+
message: (message) => this.#receive(message),
|
|
16
|
+
fatal: (error) => this.#fail(error),
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** Starts an engine: a worker unless `worker` is `false`. */
|
|
20
|
+
static async start(options = {}) {
|
|
21
|
+
const factory = options.worker === false
|
|
22
|
+
? await inThreadChannel()
|
|
23
|
+
: isNode()
|
|
24
|
+
? await nodeWorkerChannel()
|
|
25
|
+
: browserWorkerChannel();
|
|
26
|
+
return new EngineClient(factory);
|
|
27
|
+
}
|
|
28
|
+
/** @internal Wraps a custom channel (tests, custom transports). */
|
|
29
|
+
static fromChannel(start) {
|
|
30
|
+
return new EngineClient(start);
|
|
31
|
+
}
|
|
32
|
+
/** Sends a request; resolves with its result. */
|
|
33
|
+
request(body, hooks = {}) {
|
|
34
|
+
if (this.#dead !== undefined)
|
|
35
|
+
return Promise.reject(this.#dead);
|
|
36
|
+
const { signal } = hooks;
|
|
37
|
+
if (signal?.aborted === true)
|
|
38
|
+
return Promise.reject(abortError(signal));
|
|
39
|
+
const id = this.#nextId++;
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const onAbort = () => this.abort(id);
|
|
42
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
43
|
+
this.#pending.set(id, {
|
|
44
|
+
resolve: (value) => {
|
|
45
|
+
signal?.removeEventListener("abort", onAbort);
|
|
46
|
+
resolve(value);
|
|
47
|
+
},
|
|
48
|
+
reject: (error) => {
|
|
49
|
+
signal?.removeEventListener("abort", onAbort);
|
|
50
|
+
reject(error);
|
|
51
|
+
},
|
|
52
|
+
hooks,
|
|
53
|
+
});
|
|
54
|
+
if (this.#pending.size === 1)
|
|
55
|
+
this.#channel.setBusy?.(true);
|
|
56
|
+
this.#channel.post({ ...body, id }, hooks.transfer);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/** Asks the engine to cancel request `id`. */
|
|
60
|
+
abort(id) {
|
|
61
|
+
if (this.#dead === undefined)
|
|
62
|
+
this.#channel.post({ type: "abort", id: 0, target: id });
|
|
63
|
+
}
|
|
64
|
+
async terminate() {
|
|
65
|
+
this.#fail(new WebslmError("DISPOSED", "the model was unloaded"));
|
|
66
|
+
await this.#channel.terminate();
|
|
67
|
+
}
|
|
68
|
+
#receive(message) {
|
|
69
|
+
const pending = this.#pending.get(message.id);
|
|
70
|
+
if (pending === undefined)
|
|
71
|
+
return;
|
|
72
|
+
switch (message.type) {
|
|
73
|
+
case "result":
|
|
74
|
+
this.#settled(message.id);
|
|
75
|
+
pending.resolve(message.value);
|
|
76
|
+
break;
|
|
77
|
+
case "error":
|
|
78
|
+
this.#settled(message.id);
|
|
79
|
+
pending.reject(deserializeError(message.error));
|
|
80
|
+
break;
|
|
81
|
+
case "progress":
|
|
82
|
+
pending.hooks.onProgress?.(message.progress);
|
|
83
|
+
break;
|
|
84
|
+
case "delta":
|
|
85
|
+
pending.hooks.onDelta?.(message);
|
|
86
|
+
break;
|
|
87
|
+
case "prefill":
|
|
88
|
+
pending.hooks.onPrefill?.(message.done, message.total);
|
|
89
|
+
break;
|
|
90
|
+
case "read":
|
|
91
|
+
void this.#serveRead(message.target === "adapter" ? pending.hooks.onAdapterRead : pending.hooks.onRead, message);
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async #serveRead(fetchFile, message) {
|
|
96
|
+
const reply = (body) => {
|
|
97
|
+
const transfer = body.bytes instanceof Uint8Array && body.bytes.buffer instanceof ArrayBuffer
|
|
98
|
+
? [body.bytes.buffer]
|
|
99
|
+
: undefined;
|
|
100
|
+
if (this.#dead === undefined) {
|
|
101
|
+
this.#channel.post({ type: "readResult", id: 0, readId: message.readId, ...body }, transfer);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
try {
|
|
105
|
+
if (fetchFile === undefined)
|
|
106
|
+
throw new WebslmError("ENGINE", "no source to read from");
|
|
107
|
+
const range = message.start === undefined || message.end === undefined
|
|
108
|
+
? undefined
|
|
109
|
+
: [message.start, message.end];
|
|
110
|
+
const result = await fetchFile(message.path, range);
|
|
111
|
+
if (result === null || result === undefined) {
|
|
112
|
+
reply({ bytes: null });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// Copy so transferring never detaches the caller's own buffer.
|
|
116
|
+
const bytes = result instanceof Uint8Array ? result.slice() : new Uint8Array(result.slice(0));
|
|
117
|
+
reply({ bytes });
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
reply({ error: serializeError(error) });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
#settled(id) {
|
|
124
|
+
this.#pending.delete(id);
|
|
125
|
+
if (this.#pending.size === 0)
|
|
126
|
+
this.#channel.setBusy?.(false);
|
|
127
|
+
}
|
|
128
|
+
#fail(error) {
|
|
129
|
+
this.#dead ??= error;
|
|
130
|
+
const pending = [...this.#pending.values()];
|
|
131
|
+
this.#pending.clear();
|
|
132
|
+
if (pending.length > 0)
|
|
133
|
+
this.#channel.setBusy?.(false);
|
|
134
|
+
for (const p of pending)
|
|
135
|
+
p.reject(error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// Channels
|
|
140
|
+
/** @internal The module Worker of browsers (exported for tests). */
|
|
141
|
+
export function browserWorkerChannel() {
|
|
142
|
+
return (handlers) => {
|
|
143
|
+
let worker;
|
|
144
|
+
let blobUrl;
|
|
145
|
+
try {
|
|
146
|
+
try {
|
|
147
|
+
// Bundlers recognize this exact pattern and emit the worker as its own chunk.
|
|
148
|
+
worker = new Worker(new URL("./worker.js", import.meta.url), {
|
|
149
|
+
type: "module",
|
|
150
|
+
name: "webslm",
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
// Browsers refuse worker scripts from another origin, as when the
|
|
155
|
+
// package is imported from a CDN: start a same-origin worker that
|
|
156
|
+
// imports the script instead.
|
|
157
|
+
if (!isSecurityError(error))
|
|
158
|
+
throw error;
|
|
159
|
+
// Not `new URL(…, import.meta.url)`: bundlers would emit the file twice.
|
|
160
|
+
const base = import.meta.url;
|
|
161
|
+
blobUrl = importingWorkerUrl(new URL("./worker.js", base).href);
|
|
162
|
+
worker = new Worker(blobUrl, { type: "module", name: "webslm" });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
throw new WebslmError("WORKER", `cannot start the webslm worker: ${String(error)}`, {
|
|
167
|
+
cause: error,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
worker.addEventListener("message", (event) => handlers.message(event.data));
|
|
171
|
+
worker.addEventListener("error", (event) => {
|
|
172
|
+
event.preventDefault();
|
|
173
|
+
handlers.fatal(new WebslmError("WORKER", `the webslm worker failed: ${event.message || "unknown error"}`));
|
|
174
|
+
});
|
|
175
|
+
worker.addEventListener("messageerror", () => {
|
|
176
|
+
handlers.fatal(new WebslmError("WORKER", "a message to the webslm worker could not be decoded"));
|
|
177
|
+
});
|
|
178
|
+
return {
|
|
179
|
+
post: (message, transfer) => worker.postMessage(message, transfer ?? []),
|
|
180
|
+
terminate: async () => {
|
|
181
|
+
worker.terminate();
|
|
182
|
+
if (blobUrl !== undefined)
|
|
183
|
+
URL.revokeObjectURL(blobUrl);
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/** @internal Appended to errors of a Node worker that fails to start. */
|
|
189
|
+
export const NODE_WORKER_HINT = "webslm must run from its own files in node_modules: if a bundler builds it into a server bundle, " +
|
|
190
|
+
'mark it external (Next.js: `serverExternalPackages: ["webslm"]` in next.config)';
|
|
191
|
+
async function nodeWorkerChannel() {
|
|
192
|
+
const { Worker } = await importNode("worker_threads");
|
|
193
|
+
return (handlers) => {
|
|
194
|
+
// Not written as `new URL(…, import.meta.url)` so browser bundlers do not
|
|
195
|
+
// emit the Node worker as an asset.
|
|
196
|
+
const base = import.meta.url;
|
|
197
|
+
const worker = new Worker(new URL("./node-worker.js", base));
|
|
198
|
+
// Idle until the first request (see `Channel.setBusy`).
|
|
199
|
+
worker.unref();
|
|
200
|
+
let terminated = false;
|
|
201
|
+
let answered = false;
|
|
202
|
+
worker.on("message", (message) => {
|
|
203
|
+
answered = true;
|
|
204
|
+
handlers.message(message);
|
|
205
|
+
});
|
|
206
|
+
worker.on("error", (error) => {
|
|
207
|
+
// Failing before any answer means the worker's modules did not load,
|
|
208
|
+
// typically because a bundler copied webslm into a server bundle.
|
|
209
|
+
const hint = answered ? "" : ` (${NODE_WORKER_HINT})`;
|
|
210
|
+
handlers.fatal(new WebslmError("WORKER", `the webslm worker failed: ${error.message}${hint}`, { cause: error }));
|
|
211
|
+
});
|
|
212
|
+
worker.on("exit", (code) => {
|
|
213
|
+
if (!terminated)
|
|
214
|
+
handlers.fatal(new WebslmError("WORKER", `the webslm worker exited with code ${code}`));
|
|
215
|
+
});
|
|
216
|
+
return {
|
|
217
|
+
post: (message, transfer) => worker.postMessage(message, transfer),
|
|
218
|
+
terminate: async () => {
|
|
219
|
+
terminated = true;
|
|
220
|
+
await worker.terminate();
|
|
221
|
+
},
|
|
222
|
+
setBusy: (busy) => {
|
|
223
|
+
if (terminated)
|
|
224
|
+
return;
|
|
225
|
+
if (busy)
|
|
226
|
+
worker.ref();
|
|
227
|
+
else
|
|
228
|
+
worker.unref();
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** Engines run in-thread share one WebAssembly instance (and its models). */
|
|
234
|
+
async function inThreadChannel() {
|
|
235
|
+
const { Engine } = await import("./engine.js");
|
|
236
|
+
return (handlers) => {
|
|
237
|
+
let closed = false;
|
|
238
|
+
const engine = new Engine({
|
|
239
|
+
post: (message) => {
|
|
240
|
+
// Deliver asynchronously, as a worker would.
|
|
241
|
+
if (!closed)
|
|
242
|
+
queueMicrotask(() => handlers.message(message));
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
return {
|
|
246
|
+
post: (message) => {
|
|
247
|
+
if (!closed)
|
|
248
|
+
queueMicrotask(() => engine.handle(message));
|
|
249
|
+
},
|
|
250
|
+
terminate: async () => {
|
|
251
|
+
// Models were freed by their `unload` request.
|
|
252
|
+
closed = true;
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** A short list of checkpoints known to run well, for model pickers. */
|
|
2
|
+
/** A checkpoint of {@link CURATED_MODELS}. */
|
|
3
|
+
export interface CuratedModel {
|
|
4
|
+
/** Hugging Face repository id, to pass to `load`, `loadModel` or `webslm()`. */
|
|
5
|
+
readonly repo: string;
|
|
6
|
+
/** Display name. */
|
|
7
|
+
readonly name: string;
|
|
8
|
+
/** Parameter count, formatted (`"360M"`). */
|
|
9
|
+
readonly params: string;
|
|
10
|
+
/** Download size of the weights, in bytes (approximate). */
|
|
11
|
+
readonly sizeBytes: number;
|
|
12
|
+
/** One line on what it is good for. */
|
|
13
|
+
readonly note: string;
|
|
14
|
+
/** Whether it can reason before answering (`think`, the AI SDK's `reasoning`). */
|
|
15
|
+
readonly thinking?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checkpoints validated against `transformers`, smallest first: the first
|
|
19
|
+
* ones are quick on a laptop CPU, the largest (LFM3 1.7B) wants WebGPU. Any supported repository works too: see
|
|
20
|
+
* `searchModels` and `checkModel` for the others.
|
|
21
|
+
*/
|
|
22
|
+
export declare const CURATED_MODELS: readonly CuratedModel[];
|
package/dist/curated.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** A short list of checkpoints known to run well, for model pickers. */
|
|
2
|
+
/**
|
|
3
|
+
* Checkpoints validated against `transformers`, smallest first: the first
|
|
4
|
+
* ones are quick on a laptop CPU, the largest (LFM3 1.7B) wants WebGPU. Any supported repository works too: see
|
|
5
|
+
* `searchModels` and `checkModel` for the others.
|
|
6
|
+
*/
|
|
7
|
+
export const CURATED_MODELS = [
|
|
8
|
+
{
|
|
9
|
+
repo: "HuggingFaceTB/SmolLM2-135M-Instruct",
|
|
10
|
+
name: "SmolLM2 135M",
|
|
11
|
+
params: "135M",
|
|
12
|
+
sizeBytes: 269_060_552,
|
|
13
|
+
note: "Fastest. Good for trying things out.",
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
repo: "HuggingFaceTB/SmolLM2-360M-Instruct",
|
|
17
|
+
name: "SmolLM2 360M",
|
|
18
|
+
params: "360M",
|
|
19
|
+
sizeBytes: 723_674_912,
|
|
20
|
+
note: "Better answers, still quick.",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
repo: "LiquidAI/LFM2.5-350M",
|
|
24
|
+
name: "LFM2.5 350M",
|
|
25
|
+
params: "350M",
|
|
26
|
+
sizeBytes: 708_984_464,
|
|
27
|
+
note: "Convolution and attention hybrid.",
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
repo: "Qwen/Qwen3-0.6B",
|
|
31
|
+
name: "Qwen3 0.6B",
|
|
32
|
+
params: "0.6B",
|
|
33
|
+
sizeBytes: 1_503_300_328,
|
|
34
|
+
note: "Can think step by step.",
|
|
35
|
+
thinking: true,
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
repo: "Qwen/Qwen3.5-0.8B",
|
|
39
|
+
name: "Qwen3.5 0.8B",
|
|
40
|
+
params: "0.8B",
|
|
41
|
+
sizeBytes: 1_746_942_600,
|
|
42
|
+
note: "Linear-attention (Gated DeltaNet) hybrid. Thinks when asked.",
|
|
43
|
+
thinking: true,
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
repo: "LiquidAI/LFM3-1.7B",
|
|
47
|
+
name: "LFM3 1.7B",
|
|
48
|
+
params: "1.7B",
|
|
49
|
+
sizeBytes: 3_457_635_448,
|
|
50
|
+
note: "Strongest here, best on WebGPU. Thinks by default.",
|
|
51
|
+
thinking: true,
|
|
52
|
+
},
|
|
53
|
+
];
|