webslm 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/models.js CHANGED
@@ -5,6 +5,7 @@ import { recommendedSampling } from "./curated.js";
5
5
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
6
6
  import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
7
7
  import { checkModel, isGgufFile } from "./hub.js";
8
+ import { messageParts, prepareMessages, wireMessage } from "./media.js";
8
9
  import { isNode } from "./runtime.js";
9
10
  const QUANTS = ["q8", "q4", "f32"];
10
11
  const ADAPTER_MODES = ["unmerged", "merged"];
@@ -192,6 +193,20 @@ function checkScale(scale) {
192
193
  throw new WebslmError("INVALID_ARGUMENT", "the adapter scale must be a finite number");
193
194
  }
194
195
  }
196
+ const KV_CACHE_TYPES = ["f32", "int8"];
197
+ /** Smallest `kvBudget` (`MIN_KV_BUDGET` in Rust). */
198
+ const MIN_KV_BUDGET = 16;
199
+ function checkKvOptions(options) {
200
+ if (options.kvCache !== undefined && !KV_CACHE_TYPES.includes(options.kvCache)) {
201
+ throw new WebslmError("INVALID_ARGUMENT", `kvCache must be one of ${KV_CACHE_TYPES.join(", ")}`);
202
+ }
203
+ if (options.kvResidual !== undefined && !(Number.isInteger(options.kvResidual) && options.kvResidual >= 0)) {
204
+ throw new WebslmError("INVALID_ARGUMENT", "kvResidual must be a non-negative integer");
205
+ }
206
+ if (options.kvBudget !== undefined && !(Number.isInteger(options.kvBudget) && options.kvBudget >= MIN_KV_BUDGET)) {
207
+ throw new WebslmError("INVALID_ARGUMENT", `kvBudget must be an integer of at least ${MIN_KV_BUDGET}`);
208
+ }
209
+ }
195
210
  let persistRequested = false;
196
211
  /** Asks the browser to keep the cache under storage pressure (once per page). */
197
212
  function requestPersistentStorage() {
@@ -231,6 +246,7 @@ export async function loadModel(source, options = {}) {
231
246
  if (options.adapterMode !== undefined && !ADAPTER_MODES.includes(options.adapterMode)) {
232
247
  throw new WebslmError("INVALID_ARGUMENT", `adapterMode must be one of ${ADAPTER_MODES.join(", ")}`);
233
248
  }
249
+ checkKvOptions(options);
234
250
  if (isAborted(options.signal))
235
251
  throw abortError(options.signal);
236
252
  if (normalized.kind === "hub" && !isNode())
@@ -260,9 +276,13 @@ export async function loadModel(source, options = {}) {
260
276
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
261
277
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
262
278
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
279
+ ...(options.kvCache === undefined ? {} : { kvCache: options.kvCache }),
280
+ ...(options.kvResidual === undefined ? {} : { kvResidual: options.kvResidual }),
281
+ ...(options.kvBudget === undefined ? {} : { kvBudget: options.kvBudget }),
263
282
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
264
283
  ...(options.weightCache === false ? { weightCache: false } : {}),
265
284
  ...(options.deterministic === true ? { deterministic: true } : {}),
285
+ ...(options.vision === false ? { vision: false } : {}),
266
286
  ...(options.activations === undefined ? {} : { activations: options.activations }),
267
287
  ...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
268
288
  ...(options.threads === undefined ? {} : { threads: options.threads }),
@@ -314,7 +334,7 @@ export async function resolveAutoQuant(source, options) {
314
334
  else {
315
335
  shapes = await readCheckpointShapes(checkpointReader(source));
316
336
  }
317
- return autoQuant(shapes, resources, options.contextLength);
337
+ return autoQuant(shapes, resources, options.contextLength, options.vision, options);
318
338
  }
319
339
  catch (error) {
320
340
  if (isAborted(options.signal))
@@ -387,6 +407,15 @@ function wireOptions(options) {
387
407
  out.loopDetection = options.loopDetection;
388
408
  if (options.contextShift !== undefined)
389
409
  out.contextShift = options.contextShift;
410
+ if (options.media !== undefined) {
411
+ const { maxFrames, fps, longestEdge, processor } = options.media;
412
+ out.media = {
413
+ ...(maxFrames === undefined ? {} : { maxFrames }),
414
+ ...(fps === undefined ? {} : { fps }),
415
+ ...(longestEdge === undefined ? {} : { longestEdge }),
416
+ ...(processor === undefined ? {} : { processor }),
417
+ };
418
+ }
390
419
  return out;
391
420
  }
392
421
  /**
@@ -412,6 +441,16 @@ export function withRecommendedSampling(options, checkpoint) {
412
441
  return out;
413
442
  }
414
443
  /** What picks a loaded model's recommended sampling. */
444
+ /** Refuses images and videos a model does not take, before they are read. */
445
+ function checkMediaSupport(messages, vision) {
446
+ const parts = messages.flatMap(messageParts);
447
+ if (vision?.images !== true && parts.some((p) => p.type === "image")) {
448
+ throw new WebslmError("INVALID_ARGUMENT", "this model does not take images (see `info().vision`)");
449
+ }
450
+ if (vision?.videos !== true && parts.some((p) => p.type === "video")) {
451
+ throw new WebslmError("INVALID_ARGUMENT", "this model does not take videos (see `info().vision`)");
452
+ }
453
+ }
415
454
  function checkpointTraits(info) {
416
455
  return { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
417
456
  }
@@ -432,12 +471,21 @@ function checkMessages(messages) {
432
471
  throw new WebslmError("INVALID_ARGUMENT", "messages must be a non-empty array");
433
472
  }
434
473
  return messages.map((m) => {
435
- if (typeof m?.role !== "string" || typeof m.content !== "string") {
436
- throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role` and `content`");
474
+ if (typeof m?.role !== "string" || (typeof m.content !== "string" && !Array.isArray(m.content))) {
475
+ throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role` and a string or array `content`");
437
476
  }
438
- return { role: m.role, content: m.content };
477
+ // Checks the parts (the images and videos are read when sent).
478
+ wireMessage(m, []);
479
+ if (typeof m.content !== "string")
480
+ return { role: m.role, content: m.content };
481
+ const media = "media" in m ? m.media : undefined;
482
+ return media === undefined ? { role: m.role, content: m.content } : { role: m.role, content: m.content, media };
439
483
  });
440
484
  }
485
+ /** The messages as the engine reads them, images and videos left out. */
486
+ function wireMessages(messages) {
487
+ return messages.map((m) => wireMessage(m, []));
488
+ }
441
489
  /** Shared implementation of a streamed generation. */
442
490
  class GenerationStream {
443
491
  result;
@@ -517,6 +565,7 @@ class Conversation {
517
565
  */
518
566
  chat(messages, options = {}) {
519
567
  const checked = checkMessages(messages);
568
+ checkMediaSupport(checked, this.vision);
520
569
  return this.#stream({ type: "chat", messages: checked }, options);
521
570
  }
522
571
  /**
@@ -554,9 +603,23 @@ class Conversation {
554
603
  // normally, with `finishReason: "aborted"`.
555
604
  const controller = new AbortController();
556
605
  return new GenerationStream(async (onDelta) => {
557
- const result = await this.client.request({ ...body, model: this.modelId, ...session, options }, {
606
+ // Images and videos are read here, where the caller's objects live,
607
+ // and their pixels transferred to the engine.
608
+ let request;
609
+ let transfer = [];
610
+ if (body.type === "chat") {
611
+ const { messages, media } = await prepareMessages(body.messages, generateOptions.media);
612
+ request = { type: "chat", messages, ...(media === undefined ? {} : { media }), model: this.modelId, ...session, options };
613
+ if (media !== undefined)
614
+ transfer = [media.data.buffer];
615
+ }
616
+ else {
617
+ request = { ...body, model: this.modelId, ...session, options };
618
+ }
619
+ const result = await this.client.request(request, {
558
620
  onDelta,
559
621
  signal: controller.signal,
622
+ transfer,
560
623
  ...(onPrefill === undefined ? {} : { onPrefill: (done, total) => onPrefill({ done, total }) }),
561
624
  });
562
625
  this.onLength(result.length);
@@ -590,7 +653,7 @@ class Conversation {
590
653
  return this.client.request({
591
654
  type: "renderChat",
592
655
  model: this.modelId,
593
- messages: checkMessages(messages),
656
+ messages: wireMessages(checkMessages(messages)),
594
657
  templateKwargs,
595
658
  });
596
659
  }
@@ -620,6 +683,9 @@ export class Model extends Conversation {
620
683
  get checkpoint() {
621
684
  return checkpointTraits(this.#info);
622
685
  }
686
+ get vision() {
687
+ return this.#info.vision;
688
+ }
623
689
  onLength() { }
624
690
  /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
625
691
  info() {
@@ -731,6 +797,9 @@ export class Session extends Conversation {
731
797
  get checkpoint() {
732
798
  return checkpointTraits(this.#info);
733
799
  }
800
+ get vision() {
801
+ return this.#info.vision;
802
+ }
734
803
  onLength(length) {
735
804
  this.#length = length;
736
805
  }
@@ -864,7 +933,8 @@ export const MODEL_FAMILIES = [
864
933
  {
865
934
  name: "Qwen3.5",
866
935
  modelType: "qwen3_5",
867
- modality: "text",
936
+ // Images and videos too: its checkpoints hold the vision tower.
937
+ modality: "vision-language",
868
938
  exampleRepo: "Qwen/Qwen3.5-0.8B",
869
939
  status: "supported",
870
940
  },
@@ -876,10 +946,17 @@ export const MODEL_FAMILIES = [
876
946
  status: "supported",
877
947
  },
878
948
  {
879
- name: "SmolVLM",
949
+ name: "SmolVLM / SmolVLM2",
880
950
  modelType: "idefics3",
881
951
  modality: "vision-language",
882
- exampleRepo: "HuggingFaceTB/SmolVLM-256M-Instruct",
883
- status: "planned",
952
+ exampleRepo: "HuggingFaceTB/SmolVLM2-256M-Video-Instruct",
953
+ status: "supported",
954
+ },
955
+ {
956
+ name: "LFM2-VL / LFM2.5-VL",
957
+ modelType: "lfm2_vl",
958
+ modality: "vision-language",
959
+ exampleRepo: "LiquidAI/LFM2.5-VL-450M",
960
+ status: "supported",
884
961
  },
885
962
  ];
package/dist/native.d.ts CHANGED
@@ -35,6 +35,8 @@ export type NativePrefillCallback = (done: number, total: number) => void;
35
35
  /** A session of a native model; every call resolves on the model's thread. */
36
36
  export interface NativeSession {
37
37
  chat(messagesJson: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
38
+ /** `chat` with the images and videos of the messages' parts (see `media.ts`). */
39
+ chatWithMedia(messagesJson: string, optionsJson: string, mediaJson: string, mediaData: Uint8Array, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
38
40
  generate(prompt: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
39
41
  fork(): Promise<NativeSession>;
40
42
  scoreContinuations(prefix: Uint32Array, continuationsJson: string): Promise<Float32Array[]>;
@@ -60,6 +62,7 @@ export interface NativeModel {
60
62
  removeAdapter(): Promise<unknown>;
61
63
  createSession(): Promise<NativeSession>;
62
64
  chat: NativeSession["chat"];
65
+ chatWithMedia: NativeSession["chatWithMedia"];
63
66
  generate: NativeSession["generate"];
64
67
  reset(): Promise<void>;
65
68
  tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { SerializedError } from "./errors.js";
9
9
  import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
10
+ import type { KvCacheType } from "./memory.js";
10
11
  import type { WasmFlavour } from "./wasm-flavour.js";
11
12
  /** A model source in a form that can be posted to a worker. */
12
13
  export type WireSource = {
@@ -40,6 +41,9 @@ export interface WireLoadOptions {
40
41
  /** `"auto"` (default), `"native"` or `"wasm"`. */
41
42
  readonly backend?: Backend;
42
43
  readonly contextLength?: number;
44
+ readonly kvCache?: KvCacheType;
45
+ readonly kvResidual?: number;
46
+ readonly kvBudget?: number;
43
47
  /** Scale of the adapter of a `load` request. */
44
48
  readonly adapterScale?: number;
45
49
  readonly adapterMode?: AdapterMode;
@@ -47,6 +51,7 @@ export interface WireLoadOptions {
47
51
  /** `false` turns the converted-weight cache off. */
48
52
  readonly weightCache?: boolean;
49
53
  readonly deterministic?: boolean;
54
+ readonly vision?: boolean;
50
55
  readonly activations?: Activations;
51
56
  readonly wasmFlavour?: WasmFlavour;
52
57
  readonly threads?: number;
@@ -76,10 +81,35 @@ export interface WireGenerateOptions {
76
81
  readonly contextShift?: boolean | {
77
82
  readonly keep?: number;
78
83
  };
84
+ readonly media?: {
85
+ readonly maxFrames?: number;
86
+ readonly fps?: number;
87
+ readonly longestEdge?: number;
88
+ readonly processor?: Readonly<Record<string, unknown>>;
89
+ };
79
90
  }
80
91
  export interface WireMessage {
81
92
  readonly role: string;
82
- readonly content: string;
93
+ /** Text, or parts whose images and videos travel in {@link WireMedia}. */
94
+ readonly content: string | readonly WirePart[];
95
+ }
96
+ /** A content part as the engine reads it. */
97
+ export type WirePart = {
98
+ readonly type: "text";
99
+ readonly text: string;
100
+ } | {
101
+ readonly type: "image";
102
+ } | {
103
+ readonly type: "video";
104
+ };
105
+ /**
106
+ * The images and videos of a `chat` request, one per image or video part
107
+ * in order: `meta` is a JSON array describing each (see `media.ts`),
108
+ * `data` their pixels or image files back to back.
109
+ */
110
+ export interface WireMedia {
111
+ readonly meta: string;
112
+ readonly data: Uint8Array;
83
113
  }
84
114
  type WithId<T> = T & {
85
115
  readonly id: number;
@@ -106,6 +136,7 @@ export type Request = WithId<{
106
136
  readonly model: number;
107
137
  readonly session?: number;
108
138
  readonly messages: readonly WireMessage[];
139
+ readonly media?: WireMedia;
109
140
  readonly options: WireGenerateOptions;
110
141
  } | {
111
142
  readonly type: "generate";
@@ -8,7 +8,7 @@
8
8
  // Each model card: SmolLM2 (its usage example), LFM2.5 and LFM3
9
9
  // ("generation parameters", LFM3's "general" set), Qwen3 (best practices,
10
10
  // thinking and non-thinking), Qwen3.5 (the settings its benchmarks used in
11
- // each mode).
11
+ // each mode), LFM2.5-VL (its text generation parameters).
12
12
  export const RECOMMENDED_SAMPLING = {
13
13
  sets: {
14
14
  smollm2: {
@@ -30,6 +30,9 @@ export const RECOMMENDED_SAMPLING = {
30
30
  answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0, presencePenalty: 1.5 },
31
31
  thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0, presencePenalty: 1.5 },
32
32
  },
33
+ lfm2_vl: {
34
+ answer: { temperature: 0.1, minP: 0.15, repetitionPenalty: 1.05 },
35
+ },
33
36
  },
34
37
  repos: {
35
38
  "HuggingFaceTB/SmolLM2-135M-Instruct": "smollm2",
@@ -38,6 +41,7 @@ export const RECOMMENDED_SAMPLING = {
38
41
  "Qwen/Qwen3-0.6B": "qwen3",
39
42
  "Qwen/Qwen3.5-0.8B": "qwen3_5",
40
43
  "LiquidAI/LFM3-1.7B": "lfm3",
44
+ "LiquidAI/LFM2.5-VL-450M": "lfm2_vl",
41
45
  },
42
46
  modelTypes: {
43
47
  lfm2: "lfm2",
@@ -45,6 +49,7 @@ export const RECOMMENDED_SAMPLING = {
45
49
  qwen3: "qwen3",
46
50
  qwen3_5: "qwen3_5",
47
51
  qwen3_5_text: "qwen3_5",
52
+ lfm2_vl: "lfm2_vl",
48
53
  },
49
54
  };
50
55
  /**
package/dist/simple.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * {@link Session}.
5
5
  */
6
6
  import { type Model } from "./models.js";
7
- import type { ChatMessage, LoadModelOptions, ModelInfo, ModelSource } from "./types.js";
7
+ import type { ChatMessage, ImageInput, LoadModelOptions, MediaOptions, ModelInfo, ModelSource, VideoInput } from "./types.js";
8
8
  /**
9
9
  * The model {@link load}, {@link ask} and {@link stream} use when none is
10
10
  * given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
@@ -80,6 +80,15 @@ export interface PromptOptions {
80
80
  readonly onToken?: (text: string) => void;
81
81
  /** Called with each piece of the reasoning, for models that think before answering. */
82
82
  readonly onReasoning?: (text: string) => void;
83
+ /**
84
+ * Images sent with the prompt, before its text (vision-language models,
85
+ * see `ModelInfo.vision`).
86
+ */
87
+ readonly images?: readonly ImageInput[];
88
+ /** A video sent with the prompt, before its text (models with `vision.videos`). */
89
+ readonly video?: VideoInput;
90
+ /** How images and videos are read: video sampling, processor settings. */
91
+ readonly media?: MediaOptions;
83
92
  }
84
93
  /** Options of {@link LLM.ask} and {@link Chat.send}. */
85
94
  export interface AskOptions extends PromptOptions {
@@ -124,7 +133,7 @@ export interface ChatOptions {
124
133
  /** Turns to start from (user and assistant messages). */
125
134
  readonly messages?: readonly ChatMessage[];
126
135
  /** Default options of every turn; those given to `send` or `stream` take precedence. */
127
- readonly defaults?: Omit<AskOptions, "system" | "signal" | "onToken" | "onReasoning" | "withReasoning">;
136
+ readonly defaults?: Omit<AskOptions, "system" | "signal" | "onToken" | "onReasoning" | "withReasoning" | "images" | "video">;
128
137
  }
129
138
  /** Options of {@link Chat.send} and {@link Chat.stream}: the conversation sets the system prompt. */
130
139
  export type ChatTurnOptions = Omit<AskOptions, "system">;
package/dist/simple.js CHANGED
@@ -282,12 +282,12 @@ class LLMImpl {
282
282
  lock: this.#lock,
283
283
  // A bare string lets `generate` complete it as raw text when the
284
284
  // checkpoint has no chat template.
285
- input: () => system === undefined
286
- ? prompt
287
- : [
288
- { role: "system", content: system },
289
- { role: "user", content: prompt },
290
- ],
285
+ input: () => {
286
+ const user = userMessage(prompt, options);
287
+ if (system === undefined && user.media === undefined)
288
+ return prompt;
289
+ return [...(system === undefined ? [] : [{ role: "system", content: system }]), user];
290
+ },
291
291
  });
292
292
  }
293
293
  /** @internal Runs one generation into a stream. */
@@ -366,6 +366,7 @@ function passThrough(options) {
366
366
  "thinkingBudget",
367
367
  "loopDetection",
368
368
  "contextShift",
369
+ "media",
369
370
  ];
370
371
  const out = {};
371
372
  for (const key of keys)
@@ -373,6 +374,14 @@ function passThrough(options) {
373
374
  out[key] = options[key];
374
375
  return out;
375
376
  }
377
+ /** A user message: `text`, with the images and video of `options`. */
378
+ function userMessage(text, options) {
379
+ const media = [
380
+ ...(options.images ?? []).map((image) => ({ type: "image", image })),
381
+ ...(options.video === undefined ? [] : [{ type: "video", video: options.video }]),
382
+ ];
383
+ return media.length === 0 ? { role: "user", content: text } : { role: "user", content: text, media };
384
+ }
376
385
  /** `templateKwargs`, with `think` as `enable_thinking` when the template has that switch. */
377
386
  function templateKwargs(options, thinkingSwitch) {
378
387
  const kwargs = {
@@ -424,7 +433,7 @@ class ChatImpl {
424
433
  this.#llm = llm;
425
434
  this.system = options.system;
426
435
  this.#defaults = options.defaults;
427
- this.#history = (options.messages ?? []).map((m) => ({ role: m.role, content: m.content }));
436
+ this.#history = (options.messages ?? []).map((m) => m.media === undefined ? { role: m.role, content: m.content } : { role: m.role, content: m.content, media: m.media });
428
437
  }
429
438
  get history() {
430
439
  return this.#history.slice();
@@ -439,7 +448,7 @@ class ChatImpl {
439
448
  if (this.#disposed)
440
449
  throw new WebslmError("DISPOSED", "this chat was disposed");
441
450
  const epoch = this.#epoch;
442
- const user = { role: "user", content };
451
+ const user = userMessage(content, options);
443
452
  await this.#llm.run(context, merged, {
444
453
  target: () => this.#openSession(),
445
454
  lock: this.#lock,
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  /** Public types of the webslm API. */
2
+ import type { KvCacheType } from "./memory.js";
2
3
  import type { EngineHandle } from "./models.js";
3
4
  import type { WasmFlavour } from "./wasm-flavour.js";
4
5
  /**
@@ -177,6 +178,27 @@ export interface LoadModelOptions {
177
178
  readonly token?: string;
178
179
  /** Largest number of positions a session holds. Defaults to min(4096, model maximum). */
179
180
  readonly contextLength?: number;
181
+ /**
182
+ * How full-attention layers store keys and values (default `"f32"`).
183
+ * `"int8"` quantizes them in the KIVI layout (keys per channel, values
184
+ * per token, the most recent {@link LoadModelOptions.kvResidual} positions
185
+ * kept in f32): about 3 times less memory at 4096 positions, on the CPU
186
+ * and WebGPU, at a small cost in accuracy. Sliding-window and recurrent
187
+ * layers keep their own small states.
188
+ */
189
+ readonly kvCache?: KvCacheType;
190
+ /** Int8 KV cache: the most recent positions kept in f32 (default 128, rounded up to a multiple of 32). */
191
+ readonly kvResidual?: number;
192
+ /**
193
+ * Opt-in KV eviction: most positions a full-attention layer keeps (at
194
+ * least 16). Past it, the cache drops positions instead of growing: it
195
+ * keeps the first 4 (attention sinks), the most recent quarter of the
196
+ * budget, and the keys least similar to their head's mean key (KeyDiff),
197
+ * so generation goes on past the budget in bounded memory. Off by
198
+ * default; deterministic. Answers that need a detail from the middle of a
199
+ * long prompt may lose it.
200
+ */
201
+ readonly kvBudget?: number;
180
202
  /**
181
203
  * A PEFT LoRA adapter applied at load, in {@link LoadModelOptions.adapterMode}.
182
204
  * It can be swapped or removed later with {@link Model.applyAdapter} and
@@ -225,6 +247,12 @@ export interface LoadModelOptions {
225
247
  * same logits, whatever the browser, CPU or thread count.
226
248
  */
227
249
  readonly deterministic?: boolean;
250
+ /**
251
+ * `false` loads a vision-language checkpoint without its vision encoder,
252
+ * as a text-only model, to save its memory (Qwen3.5-0.8B's encoder has
253
+ * 100M parameters). Default `true`.
254
+ */
255
+ readonly vision?: boolean;
228
256
  /**
229
257
  * WebAssembly build to run (advanced; defaults to the fastest one the
230
258
  * environment supports: `"threads"` when the page is cross-origin
@@ -262,7 +290,86 @@ export interface CpuInfo {
262
290
  }
263
291
  export interface ChatMessage {
264
292
  readonly role: "system" | "user" | "assistant" | (string & {});
293
+ /** The text of the message. */
265
294
  readonly content: string;
295
+ /**
296
+ * Images and videos sent with the message, placed before its text
297
+ * (vision-language models, see `ModelInfo.vision`).
298
+ */
299
+ readonly media?: readonly MediaPart[];
300
+ }
301
+ /** An image or a video of a message. */
302
+ export type MediaPart = {
303
+ readonly type: "image";
304
+ readonly image: ImageInput;
305
+ } | {
306
+ readonly type: "video";
307
+ readonly video: VideoInput;
308
+ };
309
+ /** One part of a {@link MultimodalMessage}. */
310
+ export type ContentPart = {
311
+ readonly type: "text";
312
+ readonly text: string;
313
+ } | MediaPart;
314
+ /**
315
+ * A message whose content interleaves text, images and videos in any
316
+ * order, as `Model.chat`, `Session.chat` and `generate` also take.
317
+ */
318
+ export interface MultimodalMessage {
319
+ readonly role: "system" | "user" | "assistant" | (string & {});
320
+ readonly content: readonly ContentPart[];
321
+ }
322
+ /** What the chat methods take: a {@link ChatMessage} or a {@link MultimodalMessage}. */
323
+ export type ChatInputMessage = ChatMessage | MultimodalMessage;
324
+ /**
325
+ * Decoded RGBA pixels, row by row (`channels`: 4 by default; 3 for RGB, 1
326
+ * for gray).
327
+ */
328
+ export interface RawImage {
329
+ readonly data: Uint8Array | Uint8ClampedArray;
330
+ readonly width: number;
331
+ readonly height: number;
332
+ readonly channels?: 1 | 3 | 4;
333
+ }
334
+ /**
335
+ * An image: a URL (`https:`, `data:`, `blob:`), the bytes of a PNG, JPEG,
336
+ * WebP or GIF file, a `Blob`, an `ImageBitmap`, `ImageData`, an image,
337
+ * canvas or video element (its current frame), or decoded pixels. In Node,
338
+ * image files are decoded by the native engine; the WebAssembly engine
339
+ * takes pixels there.
340
+ */
341
+ export type ImageInput = string | URL | Uint8Array | ArrayBuffer | Blob | ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas | RawImage;
342
+ /** Frames of a video, already sampled. */
343
+ export interface VideoFrames {
344
+ readonly frames: readonly ImageInput[];
345
+ /** Frames per second of `frames` (the timestamps are `i / fps`). */
346
+ readonly fps?: number;
347
+ /** Time of each frame in seconds (in place of `fps`). */
348
+ readonly timestamps?: readonly number[];
349
+ /** Length of the whole video in seconds. */
350
+ readonly duration?: number;
351
+ }
352
+ /**
353
+ * A video: a `<video>` element, a URL or a `Blob` (sampled in the browser
354
+ * by seeking a `<video>` element, see {@link MediaOptions}), or frames.
355
+ */
356
+ export type VideoInput = HTMLVideoElement | string | URL | Blob | VideoFrames;
357
+ /** How the images and videos of a conversation are read. */
358
+ export interface MediaOptions {
359
+ /** Most frames sampled from a video (default 32). */
360
+ readonly maxFrames?: number;
361
+ /** Frames sampled per second of video (default 2; the model's processor may keep fewer). */
362
+ readonly fps?: number;
363
+ /**
364
+ * Longest image side the processor scales images to, in place of the
365
+ * checkpoint's (SmolVLM): smaller values give fewer tiles and tokens.
366
+ */
367
+ readonly longestEdge?: number;
368
+ /**
369
+ * Processor settings replacing the checkpoint's (`preprocessor_config.json`
370
+ * keys, e.g. `{ max_image_tokens: 64 }` for LFM2-VL).
371
+ */
372
+ readonly processor?: Readonly<Record<string, unknown>>;
266
373
  }
267
374
  /**
268
375
  * Options of a generation. Unset sampling options come from the model card's
@@ -329,6 +436,8 @@ export interface GenerateOptions {
329
436
  readonly contextShift?: boolean | {
330
437
  readonly keep?: number;
331
438
  };
439
+ /** How the images and videos of the messages are read (vision-language models). */
440
+ readonly media?: MediaOptions;
332
441
  /**
333
442
  * Called with every generated token. Returning `false` stops the
334
443
  * generation right there (`finishReason: "aborted"`): the output ends
@@ -461,6 +570,31 @@ export interface WeightCacheInfo {
461
570
  /** Bytes read from the cache, or stored in it. */
462
571
  readonly bytes: number;
463
572
  }
573
+ /** Memory of a loaded model ({@link ModelInfo.memory}), in bytes. */
574
+ export interface ModelMemory {
575
+ /** Weights in their stored formats. */
576
+ readonly weights: number;
577
+ /** KV caches and recurrent states of one session at {@link ModelMemory.contextLength} positions. */
578
+ readonly kvCache: number;
579
+ /** What one more position adds to the KV cache (0 once {@link LoadModelOptions.kvBudget} caps it). */
580
+ readonly kvPerToken: number;
581
+ /** How full-attention layers store keys and values ({@link LoadModelOptions.kvCache}). */
582
+ readonly kvCacheType: KvCacheType;
583
+ /** Positions an int8 KV cache keeps in f32. */
584
+ readonly kvResidual?: number;
585
+ /** The KV eviction budget ({@link LoadModelOptions.kvBudget}), when on. */
586
+ readonly kvBudget?: number;
587
+ /** Activations of a prefill batch. */
588
+ readonly scratch: number;
589
+ /** Weights, KV cache and scratch together. */
590
+ readonly total: number;
591
+ /** Positions {@link ModelMemory.kvCache} is sized for. */
592
+ readonly contextLength: number;
593
+ /** Bytes the device holds with good performance, when known. */
594
+ readonly deviceBudget?: number;
595
+ /** Largest single buffer the device allocates, when limited (KV caches are paged below it). */
596
+ readonly maxBuffer?: number;
597
+ }
464
598
  /** Description of a loaded model. */
465
599
  export interface ModelInfo {
466
600
  /** Hub repository id, when loaded from the hub. */
@@ -502,6 +636,14 @@ export interface ModelInfo {
502
636
  readonly tiesEmbeddings: boolean;
503
637
  readonly hasRecurrentState: boolean;
504
638
  readonly hasChatTemplate: boolean;
639
+ /**
640
+ * What a vision-language model takes besides text: images, and videos
641
+ * when its processor samples them (absent for text models).
642
+ */
643
+ readonly vision?: {
644
+ readonly images: boolean;
645
+ readonly videos: boolean;
646
+ };
505
647
  readonly stopTokens: readonly number[];
506
648
  readonly tokenizer: {
507
649
  readonly vocabSize: number;
@@ -514,6 +656,8 @@ export interface ModelInfo {
514
656
  readonly fromCache: boolean;
515
657
  /** What the load did with the converted-weight cache ({@link LoadModelOptions.weightCache}). */
516
658
  readonly weightCache: WeightCacheInfo;
659
+ /** Memory of the model, estimated at load: weights, KV cache and scratch, against the device's limits. */
660
+ readonly memory: ModelMemory;
517
661
  /** Milliseconds spent downloading and loading. */
518
662
  readonly loadTimeMs: number;
519
663
  }