webslm 0.4.1 → 0.6.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.
Files changed (43) hide show
  1. package/README.md +35 -5
  2. package/dist/ai-sdk/language-model.d.ts +4 -1
  3. package/dist/ai-sdk/language-model.js +6 -3
  4. package/dist/ai-sdk/prompt.d.ts +5 -3
  5. package/dist/ai-sdk/prompt.js +57 -5
  6. package/dist/cache/models.d.ts +4 -3
  7. package/dist/cache/models.js +25 -12
  8. package/dist/client.d.ts +1 -2
  9. package/dist/curated.js +9 -0
  10. package/dist/download.d.ts +5 -0
  11. package/dist/download.js +11 -6
  12. package/dist/engine.js +50 -14
  13. package/dist/fit.d.ts +1 -1
  14. package/dist/fit.js +2 -1
  15. package/dist/hub.d.ts +22 -2
  16. package/dist/hub.js +60 -5
  17. package/dist/index.d.ts +1 -1
  18. package/dist/media.d.ts +72 -0
  19. package/dist/media.js +358 -0
  20. package/dist/memory.d.ts +5 -0
  21. package/dist/memory.js +47 -6
  22. package/dist/models.d.ts +13 -4
  23. package/dist/models.js +112 -20
  24. package/dist/native.d.ts +3 -0
  25. package/dist/protocol.d.ts +32 -1
  26. package/dist/recommended-sampling.js +6 -1
  27. package/dist/simple.d.ts +11 -2
  28. package/dist/simple.js +17 -8
  29. package/dist/types.d.ts +109 -2
  30. package/native-manifest.json +29 -29
  31. package/package.json +1 -1
  32. package/wasm/relaxed/webslm_wasm.d.ts +29 -4
  33. package/wasm/relaxed/webslm_wasm.js +75 -16
  34. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  35. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
  36. package/wasm/simd/webslm_wasm.d.ts +29 -4
  37. package/wasm/simd/webslm_wasm.js +75 -16
  38. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  39. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
  40. package/wasm/threads/webslm_wasm.d.ts +30 -5
  41. package/wasm/threads/webslm_wasm.js +80 -21
  42. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  43. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +6 -4
package/README.md CHANGED
@@ -103,6 +103,34 @@ await llm.unload();
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
 
106
+ ## Images and video
107
+
108
+ Vision-language models (SmolVLM and SmolVLM2, LFM2-VL and LFM2.5-VL, Qwen3.5) answer about images; SmolVLM2 and Qwen3.5 also about videos. `info().vision` is `{ images, videos }` for them, `undefined` for text-only models.
109
+
110
+ ```ts
111
+ const llm = await load("HuggingFaceTB/SmolVLM2-256M-Video-Instruct");
112
+ await llm.ask("What is in this picture?", { images: [imageElement] });
113
+ await llm.ask("What happens here?", { video: videoElement, media: { fps: 1, maxFrames: 16 } });
114
+
115
+ const chat = llm.chat();
116
+ await chat.send("Describe this chart.", { images: [file] });
117
+ await chat.send("Which bar is the tallest?"); // the image stays in the history
118
+ chat.history[0]; // { role: "user", content: "Describe this chart.", media: [{ type: "image", image: file }] }
119
+
120
+ // Messages carry images and videos in `media`, before their text:
121
+ model.chat([{ role: "user", content: "What is this?", media: [{ type: "image", image: "https://example.com/cat.jpg" }] }]);
122
+ // or interleave them with text in `content` (a `MultimodalMessage`, taken by `chat`, `generate` and `renderChat`):
123
+ model.chat([{ role: "user", content: [{ type: "text", text: "Compare" }, { type: "image", image: a }, { type: "text", text: "and" }, { type: "image", image: b }] }]);
124
+ ```
125
+
126
+ A `ChatMessage`'s `content` is always a string, so code that renders `message.content` (from `chat.history` or `useChat`) keeps working; its images and videos are in the optional `media` (`MediaPart[]`).
127
+
128
+ - **Images** (`ImageInput`): a URL (`data:`, `blob:`, `http(s):`), bytes (`Uint8Array`, `ArrayBuffer`) or a `Blob` of a PNG, JPEG, WebP or GIF file, an `ImageBitmap`, `ImageData`, an `<img>`, `<canvas>` or `<video>` element (its current frame), an `OffscreenCanvas`, or raw pixels `{ data, width, height, channels? }` (`channels` 1, 3 or 4, default 4). Files are decoded with `createImageBitmap` where it exists (browsers, workers); in Node the native engine decodes them, and on WebAssembly without `createImageBitmap` pass pixels. Transparent pixels are composited on white, as `transformers` does.
129
+ - **Videos** (`VideoInput`): a `<video>` element, a URL or a `Blob`, sampled by seeking a `<video>` element (browsers), or frames you sampled yourself, `{ frames, fps }` or `{ frames, timestamps, duration }`, anywhere.
130
+ - **`media`** (`MediaOptions`, in the generation options): `fps` (frames sampled per second of video, default 2; each model's processor then keeps what it keeps), `maxFrames` (default 32), `longestEdge` (SmolVLM's image size: smaller gives fewer tiles and tokens) and `processor` (keys of the checkpoint's `preprocessor_config.json`, e.g. `{ max_image_tokens: 64 }` for LFM2-VL).
131
+
132
+ Images and videos sent to a text-only model are an `INVALID_ARGUMENT` error. The load option `vision: false` loads a vision-language checkpoint as a text-only model, without the memory of its vision encoder (100M parameters for Qwen3.5-0.8B). Memory estimates (`fitModel`, `quant: "auto"`) count the encoder unless `vision: false`. The prefix cache tells images apart by their pixels, so a follow-up about the same image only runs the new tokens.
133
+
106
134
  ## React
107
135
 
108
136
  ```tsx
@@ -160,7 +188,7 @@ await model.unload(); // or webslm.unloadAll()
160
188
  | `tools` with `toolChoice` forcing one function tool (`{ type: "tool" }`, or `"required"` with a single tool) | the tool's input, constrained to its schema, comes back as a tool call (`finishReason: "tool-calls"`), so `generateText` runs the tool |
161
189
  | other `tools` (`"auto"`, several tools, a schema the engine cannot enforce) | an `unsupported` warning, the model answers with text; `toolChoice: "none"` ignores them |
162
190
 
163
- Prompts are text: user and assistant text parts, and text documents (`file` parts whose data is text). Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
191
+ Prompts are user and assistant text parts, text documents (`file` parts whose data is text), and images and videos for [vision-language models](#images-and-video): `file` parts of type `image/*` or `video/*` whose data is bytes, base64 or a URL. Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
164
192
 
165
193
  `CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, with the sampling their model cards recommend, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
166
194
 
@@ -273,15 +301,17 @@ await engine.terminate();
273
301
 
274
302
  ```ts
275
303
  type ModelSource =
276
- | { hub: string; revision?: string; hubUrl?: string } // a plain string is a hub repo id
277
- | { files: Record<string, Blob | ArrayBuffer | Uint8Array> } // "config.json", "tokenizer.json", "model.safetensors"...
278
- | { fetch: (path: string, range?: [number, number]) => Promise<ArrayBuffer | Uint8Array | null> };
304
+ | { hub: string; revision?: string; hubUrl?: string; file?: string } // a plain string is a hub repo id
305
+ | { files: Record<string, Blob | ArrayBuffer | Uint8Array>; file?: string } // "config.json", "tokenizer.json", "model.safetensors", "model.gguf"...
306
+ | { fetch: (path: string, range?: [number, number]) => Promise<ArrayBuffer | Uint8Array | null>; file?: string };
279
307
  ```
280
308
 
281
309
  - **Hub**: the revision (default `main`) is resolved to a commit sha, every needed file is downloaded fully into the cache under `webslm/{repo}/{sha}/`, and the engine reads ranges from there. A later load of the same revision makes no request at all; delete the cached model (or pass a newer revision) to pick up new commits. Pass `token` in the options for gated or private repositories; it is only sent to `hubUrl`.
282
310
  - **Files**: bytes the page already holds (an upload, IndexedDB, a training job's output).
283
311
  - **Fetch**: a custom store. `range` is `[start, end)`. Return `null` for a missing file: optional files such as `generation_config.json` are probed.
284
312
 
313
+ `file` names a GGUF file of the source to load instead of safetensors weights, e.g. `{ hub: "bartowski/SmolLM2-135M-Instruct-GGUF", file: "SmolLM2-135M-Instruct-Q8_0.gguf" }`: only that file (and the repository's tokenizer files, if any) is downloaded, its metadata gives the configuration, the tokenizer (unless a `tokenizer.json` sits next to it) and the chat template. A hub repository or `files` holding GGUF files and no safetensors loads its preferred GGUF file (Q8_0, else Q4_K_M, Q4_0...) without `file`; a `fetch` source needs it. A GGUF source loads in the format of its matrices unless `quant` says otherwise: a Q8_0 file runs as Q8_0 with its blocks unchanged. Checkpoints written by `webslm export --quant q8` (Q8_0 matrices stored as an `I8` and an `F16` tensor each) load the same way, at Q8_0 size. See [GGUF and pre-quantized checkpoints](../../README.md#gguf-and-pre-quantized-checkpoints) for the tensor types and architectures. `searchModels` lists GGUF repositories of supported architectures (`gguf: true`).
314
+
285
315
  `model.info()` lists every file read with its SHA-256, so an application can check what it runs.
286
316
 
287
317
  ## LoRA adapters
@@ -428,7 +458,7 @@ export default defineConfig({
428
458
  });
429
459
  ```
430
460
 
431
- 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.4.1/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
461
+ 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.6.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>.
432
462
 
433
463
  ## Errors
434
464
 
@@ -55,7 +55,10 @@ export declare class WebslmLanguageModel implements LanguageModelV4 {
55
55
  readonly specificationVersion = "v4";
56
56
  readonly provider = "webslm";
57
57
  readonly modelId: string;
58
- /** Text-only models: no URL is read by the model itself. */
58
+ /**
59
+ * No URL is read by the model itself: the AI SDK downloads image and
60
+ * video URLs and passes their bytes (vision-language models).
61
+ */
59
62
  readonly supportedUrls: Record<string, RegExp[]>;
60
63
  /** @internal Created by a provider: `webslm(modelId)` or `createWebslm(...)(modelId)`. */
61
64
  constructor(modelId: string, slot: ModelSlot, settings: WebslmModelSettings);
@@ -3,7 +3,7 @@ import { toWebslmError } from "../errors.js";
3
3
  import { DEFAULT_TEMPERATURE, ReasoningSplitter } from "../simple.js";
4
4
  import { abortReason, raceAbort } from "./loader.js";
5
5
  import { prepareOutput, thinkingBudgetOf, toolCallId } from "./output.js";
6
- import { convertPrompt, promptText } from "./prompt.js";
6
+ import { contentText, convertPrompt, promptText } from "./prompt.js";
7
7
  const PROVIDER = "webslm";
8
8
  /** The fields of {@link WebslmCallSettings}: the settings that are not load options. */
9
9
  export const CALL_SETTING_KEYS = [
@@ -61,7 +61,7 @@ function thinkOf(options, settings) {
61
61
  function withSystem(messages, instruction) {
62
62
  const first = messages[0];
63
63
  if (first?.role === "system") {
64
- return [{ role: "system", content: `${first.content}\n\n${instruction}` }, ...messages.slice(1)];
64
+ return [{ role: "system", content: `${contentText(first.content)}\n\n${instruction}` }, ...messages.slice(1)];
65
65
  }
66
66
  return [{ role: "system", content: instruction }, ...messages];
67
67
  }
@@ -185,7 +185,10 @@ export class WebslmLanguageModel {
185
185
  specificationVersion = "v4";
186
186
  provider = PROVIDER;
187
187
  modelId;
188
- /** Text-only models: no URL is read by the model itself. */
188
+ /**
189
+ * No URL is read by the model itself: the AI SDK downloads image and
190
+ * video URLs and passes their bytes (vision-language models).
191
+ */
189
192
  supportedUrls = {};
190
193
  #slot;
191
194
  #settings;
@@ -1,11 +1,13 @@
1
1
  /** Turns an AI SDK prompt into the chat messages a chat template renders. */
2
2
  import type { LanguageModelV4Prompt, SharedV4Warning } from "@ai-sdk/provider";
3
- import type { ChatMessage } from "../types.js";
3
+ import type { ChatInputMessage } from "../types.js";
4
4
  /** The chat messages of a prompt, and what could only be approximated. */
5
5
  export interface ConvertedPrompt {
6
- readonly messages: ChatMessage[];
6
+ readonly messages: ChatInputMessage[];
7
7
  readonly warnings: SharedV4Warning[];
8
8
  }
9
+ /** The text of message content (image and video parts left out). */
10
+ export declare function contentText(content: ChatInputMessage["content"]): string;
9
11
  /**
10
12
  * Converts the prompt. Consecutive messages of one role are merged (some
11
13
  * templates require alternating turns). Reasoning of earlier answers is
@@ -18,4 +20,4 @@ export declare function convertPrompt(prompt: LanguageModelV4Prompt): ConvertedP
18
20
  * A prompt as plain text, for checkpoints without a chat template (base
19
21
  * models complete text): the contents one after the other.
20
22
  */
21
- export declare function promptText(messages: readonly ChatMessage[]): string;
23
+ export declare function promptText(messages: readonly ChatInputMessage[]): string;
@@ -4,7 +4,46 @@ import { WebslmError } from "../errors.js";
4
4
  function fileText(part) {
5
5
  if (part.data.type === "text")
6
6
  return part.data.text;
7
- throw new WebslmError("INVALID_ARGUMENT", `webslm runs text-only models: file parts (${part.mediaType}) are not supported`);
7
+ throw new WebslmError("INVALID_ARGUMENT", `file parts of type ${part.mediaType} are not supported (text documents are, and images and videos for vision-language models)`);
8
+ }
9
+ function base64Bytes(data) {
10
+ const binary = atob(data);
11
+ const bytes = new Uint8Array(binary.length);
12
+ for (let i = 0; i < binary.length; i += 1)
13
+ bytes[i] = binary.charCodeAt(i);
14
+ return bytes;
15
+ }
16
+ /**
17
+ * A file part as message content: an image or a video for vision-language
18
+ * models (`image/*`, `video/*`), else its inline text.
19
+ */
20
+ function filePart(part) {
21
+ const kind = part.mediaType.split("/")[0];
22
+ if ((kind === "image" || kind === "video") && part.data.type !== "text") {
23
+ let source;
24
+ switch (part.data.type) {
25
+ case "data":
26
+ source = typeof part.data.data === "string" ? base64Bytes(part.data.data) : part.data.data;
27
+ break;
28
+ case "url":
29
+ source = part.data.url;
30
+ break;
31
+ default:
32
+ throw new WebslmError("INVALID_ARGUMENT", "provider file references are not supported");
33
+ }
34
+ if (kind === "image")
35
+ return { type: "image", image: source };
36
+ // Videos are sampled from a URL or a Blob (in browsers).
37
+ const video = source instanceof URL ? source : new Blob([source], { type: part.mediaType });
38
+ return { type: "video", video };
39
+ }
40
+ return { type: "text", text: fileText(part) };
41
+ }
42
+ /** The text of message content (image and video parts left out). */
43
+ export function contentText(content) {
44
+ if (typeof content === "string")
45
+ return content;
46
+ return content.map((p) => (p.type === "text" ? p.text : "")).join("");
8
47
  }
9
48
  function toolOutputText(output) {
10
49
  switch (output.type) {
@@ -40,10 +79,13 @@ export function convertPrompt(prompt) {
40
79
  const push = (role, content) => {
41
80
  const last = messages.at(-1);
42
81
  if (last !== undefined && last.role === role && role !== "system") {
43
- messages[messages.length - 1] = { role, content: `${last.content}\n\n${content}` };
82
+ const merged = typeof last.content === "string" && typeof content === "string"
83
+ ? `${last.content}\n\n${content}`
84
+ : [...asParts(last.content), { type: "text", text: "\n\n" }, ...asParts(content)];
85
+ messages[messages.length - 1] = message(role, merged);
44
86
  }
45
87
  else {
46
- messages.push({ role, content });
88
+ messages.push(message(role, content));
47
89
  }
48
90
  };
49
91
  for (const message of prompt) {
@@ -52,7 +94,11 @@ export function convertPrompt(prompt) {
52
94
  push("system", message.content);
53
95
  break;
54
96
  case "user":
55
- push("user", message.content.map((part) => (part.type === "text" ? part.text : fileText(part))).join(""));
97
+ {
98
+ const parts = message.content.map((part) => (part.type === "text" ? { type: "text", text: part.text } : filePart(part)));
99
+ // Text-only content stays a string.
100
+ push("user", parts.every((p) => p.type === "text") ? parts.map((p) => p.text).join("") : parts);
101
+ }
56
102
  break;
57
103
  case "assistant": {
58
104
  let text = "";
@@ -107,5 +153,11 @@ export function convertPrompt(prompt) {
107
153
  * models complete text): the contents one after the other.
108
154
  */
109
155
  export function promptText(messages) {
110
- return messages.map((m) => m.content).join("\n\n");
156
+ return messages.map((m) => contentText(m.content)).join("\n\n");
157
+ }
158
+ function message(role, content) {
159
+ return typeof content === "string" ? { role, content } : { role, content };
160
+ }
161
+ function asParts(content) {
162
+ return typeof content === "string" ? [{ type: "text", text: content }] : content;
111
163
  }
@@ -83,9 +83,10 @@ export declare function writeManifest(store: CacheStore, manifest: CacheManifest
83
83
  */
84
84
  export declare function readCliManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
85
85
  /**
86
- * Writes the command-line tool's manifest of a complete snapshot, unless it
87
- * has one, so that `webslm` (the command-line tool) uses the files without
88
- * pulling them again.
86
+ * Writes the command-line tool's manifest of a complete snapshot, so that
87
+ * `webslm` (the command-line tool) uses the files without pulling them
88
+ * again. A manifest it already has keeps its entries and gains the files it
89
+ * lacks (another GGUF file of the same commit).
89
90
  */
90
91
  export declare function writeCliManifest(store: CacheStore, manifest: CacheManifest, revision: string): Promise<void>;
91
92
  /** Every cached repository of `store`. */
@@ -121,25 +121,38 @@ export async function readCliManifest(store, repo, sha) {
121
121
  return { version: 1, repo, sha, files, complete: true, updatedAt: new Date(created).toISOString() };
122
122
  }
123
123
  /**
124
- * Writes the command-line tool's manifest of a complete snapshot, unless it
125
- * has one, so that `webslm` (the command-line tool) uses the files without
126
- * pulling them again.
124
+ * Writes the command-line tool's manifest of a complete snapshot, so that
125
+ * `webslm` (the command-line tool) uses the files without pulling them
126
+ * again. A manifest it already has keeps its entries and gains the files it
127
+ * lacks (another GGUF file of the same commit).
127
128
  */
128
129
  export async function writeCliManifest(store, manifest, revision) {
130
+ if (!manifest.complete)
131
+ return;
129
132
  const path = cliManifestPath(manifest.repo, manifest.sha);
130
- if (!manifest.complete || (await store.size(path)) !== undefined)
133
+ let existing;
134
+ if ((await store.size(path)) !== undefined) {
135
+ try {
136
+ existing = JSON.parse((await readText(store, path)) ?? "");
137
+ }
138
+ catch {
139
+ return; // not ours to repair
140
+ }
141
+ if (!Array.isArray(existing?.files))
142
+ return;
143
+ }
144
+ const known = new Set((existing?.files ?? []).map((f) => f.name));
145
+ const added = Object.entries(manifest.files)
146
+ .filter(([name]) => !known.has(name))
147
+ .map(([name, info]) => ({ name, size: info.size, sha256: info.sha256 ?? null, blob_id: null }));
148
+ if (existing !== undefined && added.length === 0)
131
149
  return;
132
150
  const cli = {
133
151
  repo: manifest.repo,
134
- revision,
152
+ revision: existing?.revision ?? revision,
135
153
  sha: manifest.sha,
136
- files: Object.entries(manifest.files).map(([name, info]) => ({
137
- name,
138
- size: info.size,
139
- sha256: info.sha256 ?? null,
140
- blob_id: null,
141
- })),
142
- created_unix: Math.floor(Date.now() / 1000),
154
+ files: [...(existing?.files ?? []), ...added],
155
+ created_unix: existing?.created_unix ?? Math.floor(Date.now() / 1000),
143
156
  };
144
157
  await writeText(store, path, JSON.stringify(cli, null, 2));
145
158
  }
package/dist/client.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { WebslmError } from "./errors.js";
6
6
  import type { Request, Response } from "./protocol.js";
7
7
  import type { FetchFile, LoadProgress } from "./types.js";
8
- type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
8
+ export type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
9
9
  /** A bidirectional message channel to an engine. */
10
10
  export interface Channel {
11
11
  post(message: Request, transfer?: Transferable[]): void;
@@ -58,4 +58,3 @@ export declare class EngineClient {
58
58
  export declare function browserWorkerChannel(): (handlers: ChannelHandlers) => Channel;
59
59
  /** @internal Appended to errors of a Node worker that fails to start. */
60
60
  export declare const NODE_WORKER_HINT: string;
61
- export {};
package/dist/curated.js CHANGED
@@ -7,6 +7,7 @@ const LFM2 = SETS["lfm2"];
7
7
  const LFM3 = SETS["lfm3"];
8
8
  const QWEN3 = SETS["qwen3"];
9
9
  const QWEN3_5 = SETS["qwen3_5"];
10
+ const LFM2_VL = SETS["lfm2_vl"];
10
11
  /**
11
12
  * Checkpoints validated against `transformers`, smallest first: the first
12
13
  * ones are quick on a laptop CPU, the largest (LFM3 1.7B) wants WebGPU. Any supported repository works too: see
@@ -40,6 +41,14 @@ export const CURATED_MODELS = [
40
41
  note: "Best small model here; follows a conversation well.",
41
42
  sampling: LFM2,
42
43
  },
44
+ {
45
+ repo: "LiquidAI/LFM2.5-VL-450M",
46
+ name: "LFM2.5-VL 450M",
47
+ params: "450M",
48
+ sizeBytes: 897_484_568,
49
+ note: "Sees images: attach a picture and ask about it.",
50
+ sampling: LFM2_VL,
51
+ },
43
52
  {
44
53
  repo: "Qwen/Qwen3-0.6B",
45
54
  name: "Qwen3 0.6B",
@@ -30,6 +30,11 @@ export interface HubDownloadOptions extends HubOptions {
30
30
  readonly retries?: number;
31
31
  /** Minimum delay between two progress events of the same file, in ms (default 50). */
32
32
  readonly progressIntervalMs?: number;
33
+ /**
34
+ * A GGUF file of the repository to download as the weights (a repository
35
+ * without safetensors weights gets its preferred one anyway).
36
+ */
37
+ readonly file?: string;
33
38
  }
34
39
  /** A checkpoint ready to be read from the cache. */
35
40
  export interface CachedCheckpoint {
package/dist/download.js CHANGED
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { checkRepoId, filePath, readCliManifest, readManifest, readRef, writeCliManifest, writeManifest, writeRef, } from "./cache/models.js";
16
16
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
17
- import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, selectCheckpointFiles, } from "./hub.js";
17
+ import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, selectCheckpointFiles, } from "./hub.js";
18
18
  const SHA_PATTERN = /^[0-9a-f]{40}$/;
19
19
  /** Makes `repo@revision` available in `options.store` and returns a reader over it. */
20
20
  export async function prepareHubCheckpoint(repoId, revision, options) {
@@ -26,10 +26,12 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
26
26
  const knownSha = SHA_PATTERN.test(rev) ? rev : await readRef(store, repo, rev);
27
27
  if (knownSha !== undefined) {
28
28
  const ours = await readManifest(store, repo, knownSha);
29
- const manifest = ours?.complete === true && (await filesPresent(store, ours))
29
+ // A named GGUF file must be in the snapshot (another one may be).
30
+ const holds = (m) => options.file === undefined || m?.files[options.file] !== undefined;
31
+ const manifest = ours?.complete === true && holds(ours) && (await filesPresent(store, ours))
30
32
  ? ours
31
33
  : await readCliManifest(store, repo, knownSha);
32
- if (manifest !== undefined) {
34
+ if (manifest !== undefined && holds(manifest)) {
33
35
  await shareWithCli(store, manifest, rev);
34
36
  emitCachedProgress(manifest, emit);
35
37
  return reader(store, manifest, true);
@@ -82,11 +84,14 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
82
84
  throw new WebslmError("INVALID_CHECKPOINT", `invalid ${SAFETENSORS_INDEX}`, { cause: error });
83
85
  }
84
86
  }
85
- const selected = selectCheckpointFiles(names, index);
87
+ const selected = selectCheckpointFiles(names, index, options.file);
86
88
  if (selected.weights.length === 0) {
87
- throw new WebslmError("UNSUPPORTED_MODEL", `${repo}@${rev} has no safetensors weights`);
89
+ throw new WebslmError("UNSUPPORTED_MODEL", options.file === undefined
90
+ ? `${repo}@${rev} has no safetensors weights or GGUF files`
91
+ : `${repo}@${rev} has no ${options.file}`);
88
92
  }
89
- if (!names.includes("config.json") && !isAdapterListing(names)) {
93
+ const ggufWeights = selected.weights.some(isGgufFile);
94
+ if (!names.includes("config.json") && !isAdapterListing(names) && !ggufWeights) {
90
95
  throw new WebslmError("INVALID_CHECKPOINT", `${repo}@${rev} has no config.json`);
91
96
  }
92
97
  const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];
package/dist/engine.js CHANGED
@@ -19,7 +19,21 @@ import { openStore } from "./cache/index.js";
19
19
  import { weightCachePath } from "./cache/models.js";
20
20
  import { prepareHubCheckpoint } from "./download.js";
21
21
  import { WebslmError, abortError, deserializeError, serializeError } from "./errors.js";
22
- import { SAFETENSORS_INDEX } from "./hub.js";
22
+ import { SAFETENSORS_INDEX, isGgufFile, pickGgufFile } from "./hub.js";
23
+ /** Whether a read is of the weights (safetensors or GGUF), for progress. */
24
+ function isWeightFile(path) {
25
+ return (path.endsWith(".safetensors") && path !== SAFETENSORS_INDEX) || isGgufFile(path);
26
+ }
27
+ /**
28
+ * The GGUF file a source loads: the one it names, else the preferred one of
29
+ * a file list without safetensors weights (a GGUF repository).
30
+ */
31
+ function ggufFileOf(source, opened) {
32
+ if (source.file !== undefined)
33
+ return source.file;
34
+ const list = opened.list ?? [];
35
+ return list.some((f) => f.endsWith(".safetensors")) ? undefined : pickGgufFile(list);
36
+ }
23
37
  import { scoreTransferables } from "./protocol.js";
24
38
  import { installNodeWebWorker, nodePoolAvailable } from "./node-web-worker.js";
25
39
  import { installPoolWorkerFactory } from "./pool.js";
@@ -263,7 +277,9 @@ export class Engine {
263
277
  };
264
278
  const options = JSON.stringify(request.options);
265
279
  const summary = (await (request.type === "chat"
266
- ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
280
+ ? request.media === undefined
281
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
282
+ : target.chatWithMedia(JSON.stringify(request.messages), options, request.media.meta, request.media.data, onDelta, onPrefill)
267
283
  : target.generate(request.prompt, options, onDelta, onPrefill)));
268
284
  return withTimings(summary, started, first, last);
269
285
  }
@@ -312,7 +328,9 @@ export class Engine {
312
328
  const options = JSON.stringify(request.options);
313
329
  try {
314
330
  const summary = (await (request.type === "chat"
315
- ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill, cancel)
331
+ ? request.media === undefined
332
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill, cancel)
333
+ : target.chatWithMedia(JSON.stringify(request.messages), options, request.media.meta, request.media.data, onDelta, onPrefill, cancel)
316
334
  : target.generate(request.prompt, options, onDelta, onPrefill, cancel)));
317
335
  expected = summary.tokens.length;
318
336
  if (received < expected)
@@ -342,7 +360,10 @@ export class Engine {
342
360
  ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
343
361
  ...(source.token === undefined ? {} : { token: source.token }),
344
362
  };
345
- const checkpoint = await prepareHubCheckpoint(source.repo, source.revision, hubOptions);
363
+ const checkpoint = await prepareHubCheckpoint(source.repo, source.revision, {
364
+ ...hubOptions,
365
+ ...(source.file === undefined ? {} : { file: source.file }),
366
+ });
346
367
  for (const [file, info] of Object.entries(checkpoint.info)) {
347
368
  sizes.set(file, info.size);
348
369
  if (info.sha256 !== undefined)
@@ -392,7 +413,7 @@ export class Engine {
392
413
  * signal and reports the weight bytes read as the `"load"` phase.
393
414
  */
394
415
  #jsSource(opened, active, progress, bindings) {
395
- const weightFiles = (opened.list ?? []).filter((f) => f.endsWith(".safetensors"));
416
+ const weightFiles = (opened.list ?? []).filter(isWeightFile);
396
417
  const weightTotal = weightFiles.reduce((n, f) => n + (opened.sizes.get(f) ?? 0), 0);
397
418
  let weightRead = 0;
398
419
  let lastReport = 0;
@@ -400,7 +421,7 @@ export class Engine {
400
421
  if (active.signal.aborted)
401
422
  throw abortError(active.signal);
402
423
  const bytes = await opened.read(path, start, end);
403
- if (bytes !== null && path.endsWith(".safetensors") && path !== SAFETENSORS_INDEX) {
424
+ if (bytes !== null && isWeightFile(path)) {
404
425
  weightRead += bytes.length;
405
426
  const t = now();
406
427
  if (t - lastReport > 50) {
@@ -504,7 +525,7 @@ export class Engine {
504
525
  const adapter = adapterSource === undefined
505
526
  ? undefined
506
527
  : await this.#openSource(active, adapterSource, options.cacheDir, progress, createHasher, "adapter");
507
- return this.#loadNative(native.addon, opened, adapter, options, active, started, progress);
528
+ return this.#loadNative(native.addon, opened, adapter, options, active, started, progress, ggufFileOf(source, opened));
508
529
  }
509
530
  const engine = await initEngineWasm({
510
531
  ...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
@@ -517,14 +538,20 @@ export class Engine {
517
538
  ? undefined
518
539
  : await this.#openSource(active, adapterSource, options.cacheDir, progress, wasmHasher, "adapter");
519
540
  const { source: jsSource, weightTotal } = this.#jsSource(opened, active, progress, engine.bindings);
520
- const weightCache = await this.#openWeightCache(opened, options, progress, engine.bindings);
541
+ const gguf = ggufFileOf(source, opened);
542
+ // A GGUF file usually holds its weights in the format they load in: no
543
+ // converted-weight cache (whose files are keyed by repository).
544
+ const weightCache = gguf === undefined ? await this.#openWeightCache(opened, options, progress, engine.bindings) : undefined;
521
545
  let wasm;
522
546
  try {
523
547
  wasm = await WasmModel.load(jsSource, JSON.stringify({
524
- format: options.quant,
548
+ // `auto` on a GGUF file: the engine keeps the file's own format.
549
+ ...(options.quant === "auto" ? {} : { format: options.quant }),
550
+ ...(gguf === undefined ? {} : { ggufFile: gguf }),
525
551
  device: options.device ?? "auto",
526
552
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
527
553
  ...(options.deterministic === true ? { deterministic: true } : {}),
554
+ ...(options.vision === false ? { vision: false } : {}),
528
555
  ...(options.activations === undefined ? {} : { activations: options.activations }),
529
556
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
530
557
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
@@ -604,10 +631,13 @@ export class Engine {
604
631
  * the download wrote (the command-line tool's layout), with its
605
632
  * converted-weight cache next to it.
606
633
  */
607
- async #loadNative(addon, opened, adapter, options, active, started, progress) {
608
- const dir = await snapshotDirectory(opened);
609
- if (dir === undefined)
634
+ async #loadNative(addon, opened, adapter, options, active, started, progress, gguf) {
635
+ const snapshot = await snapshotDirectory(opened);
636
+ if (snapshot === undefined) {
610
637
  throw new WebslmError("ENGINE", "the native engine needs the model in the cache directory");
638
+ }
639
+ // A GGUF file is loaded by its path (its directory holds the tokenizer files).
640
+ const dir = gguf === undefined ? snapshot : await joinFsPath(snapshot, gguf);
611
641
  // Block-quantized weights only, as the WebAssembly engine keeps them
612
642
  // (float formats convert quickly).
613
643
  const cache = options.weightCache !== false &&
@@ -615,11 +645,16 @@ export class Engine {
615
645
  (options.autoQuant === true || options.quant !== "f32") &&
616
646
  opened.repo !== undefined &&
617
647
  opened.revision !== undefined
618
- ? { weightCacheDir: await joinFsPath(dir, "quantized"), weightCacheKey: `${opened.repo}@${opened.revision}` }
648
+ ? gguf === undefined
649
+ ? { weightCacheDir: await joinFsPath(dir, "quantized"), weightCacheKey: `${opened.repo}@${opened.revision}` }
650
+ : {
651
+ weightCacheDir: await joinFsPath(snapshot, "quantized", gguf),
652
+ weightCacheKey: `${opened.repo}@${opened.revision}/${gguf}`,
653
+ }
619
654
  : {};
620
655
  const adapterDir = adapter === undefined ? undefined : await adapterDirectory(adapter);
621
656
  const weightTotal = [...opened.sizes]
622
- .filter(([file]) => file.endsWith(".safetensors"))
657
+ .filter(([file]) => isWeightFile(file))
623
658
  .reduce((n, [, size]) => n + size, 0);
624
659
  progress({ phase: "load", loadedBytes: 0, totalBytes: weightTotal, overallLoadedBytes: 0, overallTotalBytes: weightTotal });
625
660
  let model;
@@ -629,6 +664,7 @@ export class Engine {
629
664
  device: options.device ?? "auto",
630
665
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
631
666
  ...(options.deterministic === true ? { deterministic: true } : {}),
667
+ ...(options.vision === false ? { vision: false } : {}),
632
668
  ...(options.activations === undefined ? {} : { activations: options.activations }),
633
669
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
634
670
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
package/dist/fit.d.ts CHANGED
@@ -166,7 +166,7 @@ export interface CheckpointShapes {
166
166
  /** Reads `config.json` and the safetensors headers (no weights) through `read`. */
167
167
  export declare function readCheckpointShapes(read: CheckpointReader): Promise<CheckpointShapes>;
168
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): {
169
+ export declare function autoQuant(shapes: CheckpointShapes, resources: BrowserResources, contextLength?: number, vision?: boolean): {
170
170
  readonly quant: Quant;
171
171
  readonly note?: string;
172
172
  };
package/dist/fit.js CHANGED
@@ -271,10 +271,11 @@ export async function readCheckpointShapes(read) {
271
271
  return { config, tensors, params };
272
272
  }
273
273
  /** What `quant: "auto"` picks for a checkpoint, and why when it is not Q8_0. */
274
- export function autoQuant(shapes, resources, contextLength) {
274
+ export function autoQuant(shapes, resources, contextLength, vision) {
275
275
  const estimates = AUTO_QUANTS.map((quant) => estimateModelMemory(shapes.config, shapes.tensors, {
276
276
  quant,
277
277
  ...(contextLength === undefined ? {} : { contextLength }),
278
+ ...(vision === undefined ? {} : { vision }),
278
279
  }));
279
280
  const all = deviceLimits(resources);
280
281
  const devices = shapes.params > AUTO_GPU_MIN_PARAMS ? all : all.filter((d) => d.device === "cpu");
package/dist/hub.d.ts CHANGED
@@ -16,6 +16,19 @@ export declare const SUPPORTED_MODEL_TYPES: readonly string[];
16
16
  export declare const CHECKPOINT_SIDE_FILES: readonly string[];
17
17
  export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
18
18
  export declare const SAFETENSORS_SINGLE = "model.safetensors";
19
+ /**
20
+ * GGUF architectures the engine runs (`general.architecture`), with the
21
+ * `model_type` each runs as.
22
+ */
23
+ export declare const GGUF_ARCHITECTURES: Readonly<Record<string, string>>;
24
+ /** Whether `name` is a GGUF file. */
25
+ export declare function isGgufFile(name: string): boolean;
26
+ /**
27
+ * The GGUF file a repository runs when none is named: Q8_0, else Q4_K_M,
28
+ * Q4_0, Q4_K_S, F16, BF16, else the first by name (split files and
29
+ * multimodal projectors left out). The engine's `pick_gguf`.
30
+ */
31
+ export declare function pickGgufFile(names: readonly string[]): string | undefined;
19
32
  /** Configuration of a PEFT LoRA adapter. */
20
33
  export declare const ADAPTER_CONFIG = "adapter_config.json";
21
34
  /** Weights of a PEFT LoRA adapter. */
@@ -76,10 +89,12 @@ export declare function fetchRevision(repo: string, revision: string, options?:
76
89
  * Picks the files to download: the side files the repository has, plus the
77
90
  * weights (the shards named by the index, `model.safetensors`, or every
78
91
  * top-level `*.safetensors`). `index` is the parsed index when there is one.
92
+ * With `gguf`, or for a repository without safetensors weights, the weights
93
+ * are one GGUF file ({@link pickGgufFile}).
79
94
  */
80
95
  export declare function selectCheckpointFiles(names: readonly string[], index?: {
81
96
  weight_map?: Record<string, string>;
82
- }): {
97
+ }, gguf?: string): {
83
98
  side: string[];
84
99
  weights: string[];
85
100
  index?: string;
@@ -102,8 +117,13 @@ export interface HubModel {
102
117
  };
103
118
  /** Whether a token with accepted terms is needed to download it. */
104
119
  readonly gated: false | "auto" | "manual";
105
- /** Whether webslm can run it (architecture supported, safetensors weights, under `maxParams`). */
120
+ /**
121
+ * Whether webslm can run it (architecture supported, safetensors weights
122
+ * or GGUF files, under `maxParams`).
123
+ */
106
124
  readonly supported: boolean;
125
+ /** Whether it runs from its GGUF files (their architecture is supported). */
126
+ readonly gguf?: boolean;
107
127
  /** Why it is not supported. */
108
128
  readonly reason?: string;
109
129
  readonly downloads?: number;