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.
- package/README.md +35 -5
- package/dist/ai-sdk/language-model.d.ts +4 -1
- package/dist/ai-sdk/language-model.js +6 -3
- package/dist/ai-sdk/prompt.d.ts +5 -3
- package/dist/ai-sdk/prompt.js +57 -5
- package/dist/cache/models.d.ts +4 -3
- package/dist/cache/models.js +25 -12
- package/dist/client.d.ts +1 -2
- package/dist/curated.js +9 -0
- package/dist/download.d.ts +5 -0
- package/dist/download.js +11 -6
- package/dist/engine.js +50 -14
- package/dist/fit.d.ts +1 -1
- package/dist/fit.js +2 -1
- package/dist/hub.d.ts +22 -2
- package/dist/hub.js +60 -5
- package/dist/index.d.ts +1 -1
- package/dist/media.d.ts +72 -0
- package/dist/media.js +358 -0
- package/dist/memory.d.ts +5 -0
- package/dist/memory.js +47 -6
- package/dist/models.d.ts +13 -4
- package/dist/models.js +112 -20
- package/dist/native.d.ts +3 -0
- package/dist/protocol.d.ts +32 -1
- package/dist/recommended-sampling.js +6 -1
- package/dist/simple.d.ts +11 -2
- package/dist/simple.js +17 -8
- package/dist/types.d.ts +109 -2
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +29 -4
- package/wasm/relaxed/webslm_wasm.js +75 -16
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
- package/wasm/simd/webslm_wasm.d.ts +29 -4
- package/wasm/simd/webslm_wasm.js +75 -16
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
- package/wasm/threads/webslm_wasm.d.ts +30 -5
- package/wasm/threads/webslm_wasm.js +80 -21
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +6 -4
package/dist/hub.js
CHANGED
|
@@ -20,6 +20,9 @@ export const SUPPORTED_MODEL_TYPES = [
|
|
|
20
20
|
"lfm3",
|
|
21
21
|
"qwen3_5",
|
|
22
22
|
"qwen3_5_text",
|
|
23
|
+
"idefics3",
|
|
24
|
+
"smolvlm",
|
|
25
|
+
"lfm2_vl",
|
|
23
26
|
];
|
|
24
27
|
/** Files read besides the weights, when the repository has them. */
|
|
25
28
|
export const CHECKPOINT_SIDE_FILES = [
|
|
@@ -30,9 +33,46 @@ export const CHECKPOINT_SIDE_FILES = [
|
|
|
30
33
|
"special_tokens_map.json",
|
|
31
34
|
"chat_template.jinja",
|
|
32
35
|
"chat_template.json",
|
|
36
|
+
// Vision-language models: the image and video processors' settings.
|
|
37
|
+
"preprocessor_config.json",
|
|
38
|
+
"processor_config.json",
|
|
39
|
+
"video_preprocessor_config.json",
|
|
33
40
|
];
|
|
34
41
|
export const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
35
42
|
export const SAFETENSORS_SINGLE = "model.safetensors";
|
|
43
|
+
/**
|
|
44
|
+
* GGUF architectures the engine runs (`general.architecture`), with the
|
|
45
|
+
* `model_type` each runs as.
|
|
46
|
+
*/
|
|
47
|
+
export const GGUF_ARCHITECTURES = {
|
|
48
|
+
llama: "llama",
|
|
49
|
+
qwen2: "qwen2",
|
|
50
|
+
qwen3: "qwen3",
|
|
51
|
+
lfm2: "lfm2",
|
|
52
|
+
};
|
|
53
|
+
/** Whether `name` is a GGUF file. */
|
|
54
|
+
export function isGgufFile(name) {
|
|
55
|
+
return name.toLowerCase().endsWith(".gguf");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The GGUF file a repository runs when none is named: Q8_0, else Q4_K_M,
|
|
59
|
+
* Q4_0, Q4_K_S, F16, BF16, else the first by name (split files and
|
|
60
|
+
* multimodal projectors left out). The engine's `pick_gguf`.
|
|
61
|
+
*/
|
|
62
|
+
export function pickGgufFile(names) {
|
|
63
|
+
const candidates = names
|
|
64
|
+
.filter((n) => {
|
|
65
|
+
const lower = n.toLowerCase();
|
|
66
|
+
return isGgufFile(n) && !n.includes("/") && !lower.includes("mmproj") && !lower.includes("-of-0");
|
|
67
|
+
})
|
|
68
|
+
.sort();
|
|
69
|
+
for (const preferred of ["q8_0", "q4_k_m", "q4_0", "q4_k_s", "f16", "bf16"]) {
|
|
70
|
+
const found = candidates.find((n) => n.toLowerCase().includes(preferred));
|
|
71
|
+
if (found !== undefined)
|
|
72
|
+
return found;
|
|
73
|
+
}
|
|
74
|
+
return candidates[0];
|
|
75
|
+
}
|
|
36
76
|
/** Configuration of a PEFT LoRA adapter. */
|
|
37
77
|
export const ADAPTER_CONFIG = "adapter_config.json";
|
|
38
78
|
/** Weights of a PEFT LoRA adapter. */
|
|
@@ -156,13 +196,19 @@ function parseGated(value) {
|
|
|
156
196
|
* Picks the files to download: the side files the repository has, plus the
|
|
157
197
|
* weights (the shards named by the index, `model.safetensors`, or every
|
|
158
198
|
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
199
|
+
* With `gguf`, or for a repository without safetensors weights, the weights
|
|
200
|
+
* are one GGUF file ({@link pickGgufFile}).
|
|
159
201
|
*/
|
|
160
|
-
export function selectCheckpointFiles(names, index) {
|
|
202
|
+
export function selectCheckpointFiles(names, index, gguf) {
|
|
161
203
|
// A LoRA adapter needs only its two files.
|
|
162
204
|
if (isAdapterListing(names))
|
|
163
205
|
return { side: [ADAPTER_CONFIG], weights: [ADAPTER_WEIGHTS] };
|
|
164
206
|
const present = new Set(names);
|
|
165
207
|
const side = CHECKPOINT_SIDE_FILES.filter((f) => present.has(f));
|
|
208
|
+
const hasSafetensors = present.has(SAFETENSORS_INDEX) || names.some((n) => !n.includes("/") && n.endsWith(".safetensors"));
|
|
209
|
+
const ggufFile = gguf ?? (hasSafetensors ? undefined : pickGgufFile(names));
|
|
210
|
+
if (ggufFile !== undefined)
|
|
211
|
+
return { side, weights: present.has(ggufFile) ? [ggufFile] : [] };
|
|
166
212
|
if (present.has(SAFETENSORS_INDEX) && index !== undefined) {
|
|
167
213
|
const weights = [...new Set(Object.values(index.weight_map ?? {}))].sort();
|
|
168
214
|
return { side, weights, index: SAFETENSORS_INDEX };
|
|
@@ -258,7 +304,7 @@ export async function searchModels(query, options = {}) {
|
|
|
258
304
|
const maxParams = options.maxParams ?? 2e9;
|
|
259
305
|
const limit = Math.max(1, Math.min(options.limit ?? 20, 100));
|
|
260
306
|
const params = new URLSearchParams({ search: query.trim(), sort: "downloads", limit: String(limit) });
|
|
261
|
-
for (const field of ["safetensors", "config", "gated", "downloads", "pipeline_tag", "library_name", "tags"]) {
|
|
307
|
+
for (const field of ["safetensors", "gguf", "config", "gated", "downloads", "pipeline_tag", "library_name", "tags"]) {
|
|
262
308
|
params.append("expand[]", field);
|
|
263
309
|
}
|
|
264
310
|
const url = `${hubBase(options.hubUrl)}/api/models?${params.toString()}`;
|
|
@@ -285,17 +331,22 @@ function toHubModel(entry, maxParams) {
|
|
|
285
331
|
byDtype[dtype] = count;
|
|
286
332
|
}
|
|
287
333
|
const total = entry.safetensors?.total;
|
|
288
|
-
const
|
|
334
|
+
const ggufArchitecture = typeof entry.gguf?.architecture === "string" ? entry.gguf.architecture : undefined;
|
|
335
|
+
const ggufType = ggufArchitecture === undefined ? undefined : GGUF_ARCHITECTURES[ggufArchitecture];
|
|
336
|
+
const ggufTotal = entry.gguf?.total;
|
|
337
|
+
const params = typeof total === "number" ? total : typeof ggufTotal === "number" && ggufType !== undefined ? ggufTotal : undefined;
|
|
289
338
|
const embedding = isEmbeddingModel({
|
|
290
339
|
repo: entry.id,
|
|
291
340
|
pipelineTag: typeof entry.pipeline_tag === "string" ? entry.pipeline_tag : undefined,
|
|
292
341
|
libraryName: typeof entry.library_name === "string" ? entry.library_name : undefined,
|
|
293
342
|
tags: Array.isArray(entry.tags) ? entry.tags.filter((t) => typeof t === "string") : undefined,
|
|
294
343
|
});
|
|
295
|
-
|
|
344
|
+
// GGUF files of a supported architecture run whatever else the repository holds.
|
|
345
|
+
const gguf = ggufType !== undefined && SUPPORTED_MODEL_TYPES.includes(ggufType);
|
|
346
|
+
let reason = embedding ? EMBEDDING_REASON : gguf ? undefined : unsupportedReason(modelType);
|
|
296
347
|
if (reason === undefined && params === undefined)
|
|
297
348
|
reason = "no safetensors weights";
|
|
298
|
-
if (reason === undefined)
|
|
349
|
+
if (reason === undefined && !gguf)
|
|
299
350
|
reason = packedWeightsReason(byDtype);
|
|
300
351
|
if (reason === undefined && params !== undefined && params > maxParams) {
|
|
301
352
|
reason = `${formatParams(params)} parameters exceed the ${formatParams(maxParams)} limit`;
|
|
@@ -307,6 +358,10 @@ function toHubModel(entry, maxParams) {
|
|
|
307
358
|
};
|
|
308
359
|
if (modelType !== undefined)
|
|
309
360
|
model.modelType = modelType;
|
|
361
|
+
else if (gguf)
|
|
362
|
+
model.modelType = ggufType;
|
|
363
|
+
if (gguf)
|
|
364
|
+
model.gguf = true;
|
|
310
365
|
if (architectures !== undefined)
|
|
311
366
|
model.architectures = architectures;
|
|
312
367
|
if (params !== undefined) {
|
package/dist/index.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ import type { SafetensorsHeader } from "./safetensors.js";
|
|
|
18
18
|
export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, type Answer, type AskOptions, type Chat, type ChatOptions, type ChatTurnOptions, type LLM, type PromptOptions, type SharedAskOptions, type SharedStreamOptions, type TextStream, } from "./simple.js";
|
|
19
19
|
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
20
20
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
21
|
-
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
21
|
+
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
22
22
|
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
23
23
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
|
|
24
24
|
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
package/dist/media.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Images and videos of a conversation, turned into what the engine reads:
|
|
3
|
+
* the messages with their image and video parts reduced to placeholders
|
|
4
|
+
* (`{ type: "image" }`, `{ type: "video" }`), a JSON description of each
|
|
5
|
+
* image or video, and one buffer holding their pixels (or image files)
|
|
6
|
+
* back to back (see `webslm_bindings::media` in Rust).
|
|
7
|
+
*
|
|
8
|
+
* This runs where the caller's objects live (the page's main thread for an
|
|
9
|
+
* `HTMLVideoElement`): images are decoded with `createImageBitmap` and a
|
|
10
|
+
* canvas when the environment has them, and videos sampled by seeking a
|
|
11
|
+
* `<video>` element. In Node, image files go to the native engine as they
|
|
12
|
+
* are, which decodes PNG, JPEG, WebP and GIF; pass pixels
|
|
13
|
+
* (`{ data, width, height }`) to the WebAssembly engine.
|
|
14
|
+
*/
|
|
15
|
+
import type { WireMedia, WireMessage } from "./protocol.js";
|
|
16
|
+
import type { ChatInputMessage, ContentPart, MediaOptions, MediaPart } from "./types.js";
|
|
17
|
+
/** One image or video, described for the engine. */
|
|
18
|
+
export type WireMediaEntry = {
|
|
19
|
+
readonly kind: "image";
|
|
20
|
+
readonly encoding: "rgba";
|
|
21
|
+
readonly width: number;
|
|
22
|
+
readonly height: number;
|
|
23
|
+
readonly byteLength: number;
|
|
24
|
+
} | {
|
|
25
|
+
readonly kind: "image";
|
|
26
|
+
readonly encoding: "file";
|
|
27
|
+
readonly byteLength: number;
|
|
28
|
+
} | {
|
|
29
|
+
readonly kind: "video";
|
|
30
|
+
readonly encoding: "rgba";
|
|
31
|
+
readonly width: number;
|
|
32
|
+
readonly height: number;
|
|
33
|
+
readonly timestamps: readonly number[];
|
|
34
|
+
readonly duration?: number;
|
|
35
|
+
readonly byteLength: number;
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: "video";
|
|
38
|
+
readonly encoding: "file";
|
|
39
|
+
readonly frameByteLengths: readonly number[];
|
|
40
|
+
readonly timestamps: readonly number[];
|
|
41
|
+
readonly duration?: number;
|
|
42
|
+
readonly byteLength: number;
|
|
43
|
+
};
|
|
44
|
+
/** Video frames sampled per second when the caller sets no `media.fps`. */
|
|
45
|
+
export declare const DEFAULT_VIDEO_FPS = 2;
|
|
46
|
+
/** Most frames sampled from a video when the caller sets no `media.maxFrames`. */
|
|
47
|
+
export declare const DEFAULT_VIDEO_MAX_FRAMES = 32;
|
|
48
|
+
/**
|
|
49
|
+
* Longest side of the frames captured from a video: the processors scale
|
|
50
|
+
* frames down further (SmolVLM to 512 pixels), and full-size frames would
|
|
51
|
+
* take hundreds of megabytes.
|
|
52
|
+
*/
|
|
53
|
+
export declare const VIDEO_CAPTURE_EDGE = 768;
|
|
54
|
+
/** The parts of a message: its media then its text, or its content parts. */
|
|
55
|
+
export declare function messageParts(message: ChatInputMessage): readonly ContentPart[];
|
|
56
|
+
/** Whether a message holds images or videos. */
|
|
57
|
+
export declare function hasMedia(messages: readonly ChatInputMessage[]): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Checks a message and returns its wire form, with the images and videos
|
|
60
|
+
* of its parts appended to `media` in order.
|
|
61
|
+
*/
|
|
62
|
+
export declare function wireMessage(message: ChatInputMessage, media: MediaPart[]): WireMessage;
|
|
63
|
+
/**
|
|
64
|
+
* The wire form of a conversation and its images and videos (`media` is
|
|
65
|
+
* `undefined` without any).
|
|
66
|
+
*/
|
|
67
|
+
export declare function prepareMessages(messages: readonly ChatInputMessage[], options?: MediaOptions): Promise<{
|
|
68
|
+
messages: WireMessage[];
|
|
69
|
+
media?: WireMedia;
|
|
70
|
+
}>;
|
|
71
|
+
/** Sampling times of a `duration`-second video: `fps` per second, at most `maxFrames`, evenly spread. */
|
|
72
|
+
export declare function sampleTimes(duration: number, fps: number, maxFrames: number): number[];
|
package/dist/media.js
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Images and videos of a conversation, turned into what the engine reads:
|
|
3
|
+
* the messages with their image and video parts reduced to placeholders
|
|
4
|
+
* (`{ type: "image" }`, `{ type: "video" }`), a JSON description of each
|
|
5
|
+
* image or video, and one buffer holding their pixels (or image files)
|
|
6
|
+
* back to back (see `webslm_bindings::media` in Rust).
|
|
7
|
+
*
|
|
8
|
+
* This runs where the caller's objects live (the page's main thread for an
|
|
9
|
+
* `HTMLVideoElement`): images are decoded with `createImageBitmap` and a
|
|
10
|
+
* canvas when the environment has them, and videos sampled by seeking a
|
|
11
|
+
* `<video>` element. In Node, image files go to the native engine as they
|
|
12
|
+
* are, which decodes PNG, JPEG, WebP and GIF; pass pixels
|
|
13
|
+
* (`{ data, width, height }`) to the WebAssembly engine.
|
|
14
|
+
*/
|
|
15
|
+
import { WebslmError } from "./errors.js";
|
|
16
|
+
/** Video frames sampled per second when the caller sets no `media.fps`. */
|
|
17
|
+
export const DEFAULT_VIDEO_FPS = 2;
|
|
18
|
+
/** Most frames sampled from a video when the caller sets no `media.maxFrames`. */
|
|
19
|
+
export const DEFAULT_VIDEO_MAX_FRAMES = 32;
|
|
20
|
+
/**
|
|
21
|
+
* Longest side of the frames captured from a video: the processors scale
|
|
22
|
+
* frames down further (SmolVLM to 512 pixels), and full-size frames would
|
|
23
|
+
* take hundreds of megabytes.
|
|
24
|
+
*/
|
|
25
|
+
export const VIDEO_CAPTURE_EDGE = 768;
|
|
26
|
+
/** The parts of a message: its media then its text, or its content parts. */
|
|
27
|
+
export function messageParts(message) {
|
|
28
|
+
if (typeof message.content !== "string")
|
|
29
|
+
return message.content;
|
|
30
|
+
const media = "media" in message && message.media !== undefined ? message.media : [];
|
|
31
|
+
return message.content === "" && media.length > 0 ? media : [...media, { type: "text", text: message.content }];
|
|
32
|
+
}
|
|
33
|
+
/** Whether a message holds images or videos. */
|
|
34
|
+
export function hasMedia(messages) {
|
|
35
|
+
return messages.some((m) => messageParts(m).some((p) => p.type !== "text"));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Checks a message and returns its wire form, with the images and videos
|
|
39
|
+
* of its parts appended to `media` in order.
|
|
40
|
+
*/
|
|
41
|
+
export function wireMessage(message, media) {
|
|
42
|
+
if (typeof message?.role !== "string") {
|
|
43
|
+
throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role`");
|
|
44
|
+
}
|
|
45
|
+
const extra = "media" in message ? message.media : undefined;
|
|
46
|
+
if (typeof message.content === "string") {
|
|
47
|
+
if (extra === undefined || extra.length === 0)
|
|
48
|
+
return { role: message.role, content: message.content };
|
|
49
|
+
if (!Array.isArray(extra))
|
|
50
|
+
throw new WebslmError("INVALID_ARGUMENT", "a message's `media` is an array of parts");
|
|
51
|
+
for (const part of extra) {
|
|
52
|
+
if (part?.type === "text") {
|
|
53
|
+
throw new WebslmError("INVALID_ARGUMENT", "`media` holds image and video parts only");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else if (!Array.isArray(message.content)) {
|
|
58
|
+
throw new WebslmError("INVALID_ARGUMENT", "a message's `content` is a string or an array of parts");
|
|
59
|
+
}
|
|
60
|
+
else if (extra !== undefined) {
|
|
61
|
+
throw new WebslmError("INVALID_ARGUMENT", "`media` goes with string content; put the parts in `content` instead");
|
|
62
|
+
}
|
|
63
|
+
const parts = messageParts(message).map((part) => {
|
|
64
|
+
switch (part?.type) {
|
|
65
|
+
case "text":
|
|
66
|
+
if (typeof part.text !== "string")
|
|
67
|
+
throw new WebslmError("INVALID_ARGUMENT", "a text part needs a string `text`");
|
|
68
|
+
return { type: "text", text: part.text };
|
|
69
|
+
case "image":
|
|
70
|
+
if (part.image === undefined || part.image === null) {
|
|
71
|
+
throw new WebslmError("INVALID_ARGUMENT", "an image part needs an `image`");
|
|
72
|
+
}
|
|
73
|
+
media.push({ type: "image", image: part.image });
|
|
74
|
+
return { type: "image" };
|
|
75
|
+
case "video":
|
|
76
|
+
if (part.video === undefined || part.video === null) {
|
|
77
|
+
throw new WebslmError("INVALID_ARGUMENT", "a video part needs a `video`");
|
|
78
|
+
}
|
|
79
|
+
media.push({ type: "video", video: part.video });
|
|
80
|
+
return { type: "video" };
|
|
81
|
+
default:
|
|
82
|
+
throw new WebslmError("INVALID_ARGUMENT", `unsupported content part type "${String(part?.type)}" (expected text, image or video)`);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
// Text-only part lists are plain messages.
|
|
86
|
+
if (parts.every((p) => p.type === "text")) {
|
|
87
|
+
return { role: message.role, content: parts.map((p) => p.text).join("") };
|
|
88
|
+
}
|
|
89
|
+
return { role: message.role, content: parts };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The wire form of a conversation and its images and videos (`media` is
|
|
93
|
+
* `undefined` without any).
|
|
94
|
+
*/
|
|
95
|
+
export async function prepareMessages(messages, options = {}) {
|
|
96
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
97
|
+
throw new WebslmError("INVALID_ARGUMENT", "messages must be a non-empty array");
|
|
98
|
+
}
|
|
99
|
+
const items = [];
|
|
100
|
+
const wire = messages.map((m) => wireMessage(m, items));
|
|
101
|
+
if (items.length === 0)
|
|
102
|
+
return { messages: wire };
|
|
103
|
+
const entries = [];
|
|
104
|
+
const chunks = [];
|
|
105
|
+
for (const item of items) {
|
|
106
|
+
if (item.type === "image") {
|
|
107
|
+
const image = await readImage(item.image);
|
|
108
|
+
if (image.kind === "file") {
|
|
109
|
+
entries.push({ kind: "image", encoding: "file", byteLength: image.bytes.byteLength });
|
|
110
|
+
chunks.push(image.bytes);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
entries.push({
|
|
114
|
+
kind: "image",
|
|
115
|
+
encoding: "rgba",
|
|
116
|
+
width: image.width,
|
|
117
|
+
height: image.height,
|
|
118
|
+
byteLength: image.data.byteLength,
|
|
119
|
+
});
|
|
120
|
+
chunks.push(image.data);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
const { entry, bytes } = await readVideo(item.video, options);
|
|
125
|
+
entries.push(entry);
|
|
126
|
+
chunks.push(...bytes);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { messages: wire, media: { meta: JSON.stringify(entries), data: concat(chunks) } };
|
|
130
|
+
}
|
|
131
|
+
function concat(chunks) {
|
|
132
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + c.byteLength, 0));
|
|
133
|
+
let at = 0;
|
|
134
|
+
for (const chunk of chunks) {
|
|
135
|
+
out.set(chunk, at);
|
|
136
|
+
at += chunk.byteLength;
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
function isRawImage(value) {
|
|
141
|
+
return (typeof value === "object" &&
|
|
142
|
+
value !== null &&
|
|
143
|
+
"data" in value &&
|
|
144
|
+
"width" in value &&
|
|
145
|
+
"height" in value &&
|
|
146
|
+
typeof value.width === "number" &&
|
|
147
|
+
typeof value.height === "number");
|
|
148
|
+
}
|
|
149
|
+
function rgbaOf(raw) {
|
|
150
|
+
const { width, height } = raw;
|
|
151
|
+
const data = raw.data instanceof Uint8Array ? raw.data : new Uint8Array(raw.data.buffer, raw.data.byteOffset, raw.data.byteLength);
|
|
152
|
+
const channels = raw.channels ?? 4;
|
|
153
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
|
|
154
|
+
throw new WebslmError("INVALID_ARGUMENT", `invalid image size ${width}x${height}`);
|
|
155
|
+
}
|
|
156
|
+
if (![1, 3, 4].includes(channels) || data.byteLength !== width * height * channels) {
|
|
157
|
+
throw new WebslmError("INVALID_ARGUMENT", `${data.byteLength} bytes for a ${width}x${height} image with ${channels} channels`);
|
|
158
|
+
}
|
|
159
|
+
if (channels === 4)
|
|
160
|
+
return { kind: "rgba", width, height, data };
|
|
161
|
+
const rgba = new Uint8Array(width * height * 4);
|
|
162
|
+
for (let i = 0; i < width * height; i += 1) {
|
|
163
|
+
for (let c = 0; c < 3; c += 1)
|
|
164
|
+
rgba[i * 4 + c] = data[i * channels + (channels === 1 ? 0 : c)] ?? 0;
|
|
165
|
+
rgba[i * 4 + 3] = 255;
|
|
166
|
+
}
|
|
167
|
+
return { kind: "rgba", width, height, data: rgba };
|
|
168
|
+
}
|
|
169
|
+
const canDecode = () => typeof createImageBitmap === "function" && typeof OffscreenCanvas === "function";
|
|
170
|
+
/** RGBA pixels of something drawable. */
|
|
171
|
+
function pixelsOf(source, width, height, maxEdge) {
|
|
172
|
+
let w = width;
|
|
173
|
+
let h = height;
|
|
174
|
+
if (maxEdge !== undefined && Math.max(w, h) > maxEdge) {
|
|
175
|
+
const scale = maxEdge / Math.max(w, h);
|
|
176
|
+
w = Math.max(1, Math.round(w * scale));
|
|
177
|
+
h = Math.max(1, Math.round(h * scale));
|
|
178
|
+
}
|
|
179
|
+
const canvas = new OffscreenCanvas(w, h);
|
|
180
|
+
const context = canvas.getContext("2d", { willReadFrequently: true });
|
|
181
|
+
if (context === null)
|
|
182
|
+
throw new WebslmError("ENGINE", "no 2D canvas to read the image's pixels");
|
|
183
|
+
context.drawImage(source, 0, 0, w, h);
|
|
184
|
+
const data = context.getImageData(0, 0, w, h).data;
|
|
185
|
+
return { kind: "rgba", width: w, height: h, data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) };
|
|
186
|
+
}
|
|
187
|
+
async function decodeBytes(bytes, type = "") {
|
|
188
|
+
if (!canDecode())
|
|
189
|
+
return { kind: "file", bytes };
|
|
190
|
+
const bitmap = await createImageBitmap(new Blob([bytes], type === "" ? {} : { type }), {
|
|
191
|
+
premultiplyAlpha: "none",
|
|
192
|
+
colorSpaceConversion: "none",
|
|
193
|
+
});
|
|
194
|
+
try {
|
|
195
|
+
return pixelsOf(bitmap, bitmap.width, bitmap.height);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
bitmap.close();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** The bytes behind a URL (`data:`, `blob:`, `http(s):`). */
|
|
202
|
+
async function fetchBytes(url) {
|
|
203
|
+
const response = await fetch(url);
|
|
204
|
+
if (!response.ok)
|
|
205
|
+
throw new WebslmError("NETWORK", `fetching ${url.slice(0, 64)} failed: HTTP ${response.status}`);
|
|
206
|
+
return { bytes: new Uint8Array(await response.arrayBuffer()), type: response.headers.get("content-type") ?? "" };
|
|
207
|
+
}
|
|
208
|
+
async function readImage(input) {
|
|
209
|
+
if (typeof input === "string" || input instanceof URL) {
|
|
210
|
+
const { bytes, type } = await fetchBytes(String(input));
|
|
211
|
+
return decodeBytes(bytes, type);
|
|
212
|
+
}
|
|
213
|
+
if (input instanceof Uint8Array)
|
|
214
|
+
return decodeBytes(input);
|
|
215
|
+
if (input instanceof ArrayBuffer)
|
|
216
|
+
return decodeBytes(new Uint8Array(input));
|
|
217
|
+
if (typeof Blob !== "undefined" && input instanceof Blob) {
|
|
218
|
+
return decodeBytes(new Uint8Array(await input.arrayBuffer()), input.type);
|
|
219
|
+
}
|
|
220
|
+
if (typeof ImageData !== "undefined" && input instanceof ImageData) {
|
|
221
|
+
return rgbaOf({ data: input.data, width: input.width, height: input.height });
|
|
222
|
+
}
|
|
223
|
+
if (isRawImage(input))
|
|
224
|
+
return rgbaOf(input);
|
|
225
|
+
if (typeof ImageBitmap !== "undefined" && input instanceof ImageBitmap) {
|
|
226
|
+
return pixelsOf(input, input.width, input.height);
|
|
227
|
+
}
|
|
228
|
+
if (typeof HTMLImageElement !== "undefined" && input instanceof HTMLImageElement) {
|
|
229
|
+
if (!input.complete)
|
|
230
|
+
await input.decode();
|
|
231
|
+
return pixelsOf(input, input.naturalWidth, input.naturalHeight);
|
|
232
|
+
}
|
|
233
|
+
if (typeof HTMLVideoElement !== "undefined" && input instanceof HTMLVideoElement) {
|
|
234
|
+
return pixelsOf(input, input.videoWidth, input.videoHeight);
|
|
235
|
+
}
|
|
236
|
+
if ((typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement) ||
|
|
237
|
+
(typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas)) {
|
|
238
|
+
return pixelsOf(input, input.width, input.height);
|
|
239
|
+
}
|
|
240
|
+
throw new WebslmError("INVALID_ARGUMENT", "unsupported image: pass a URL, bytes, a Blob, an ImageBitmap, ImageData, an image, canvas or video element, or { data, width, height }");
|
|
241
|
+
}
|
|
242
|
+
function isVideoFrames(value) {
|
|
243
|
+
return typeof value === "object" && value !== null && Array.isArray(value.frames);
|
|
244
|
+
}
|
|
245
|
+
/** Sampling times of a `duration`-second video: `fps` per second, at most `maxFrames`, evenly spread. */
|
|
246
|
+
export function sampleTimes(duration, fps, maxFrames) {
|
|
247
|
+
const count = Math.max(1, Math.min(maxFrames, Math.round(duration * fps)));
|
|
248
|
+
if (count === 1 || !(duration > 0))
|
|
249
|
+
return [0];
|
|
250
|
+
const step = duration / count;
|
|
251
|
+
return Array.from({ length: count }, (_, i) => i * step);
|
|
252
|
+
}
|
|
253
|
+
async function readVideo(input, options) {
|
|
254
|
+
if (isVideoFrames(input))
|
|
255
|
+
return readFrames(input);
|
|
256
|
+
if (typeof document === "undefined" || typeof HTMLVideoElement === "undefined") {
|
|
257
|
+
throw new WebslmError("INVALID_ARGUMENT", "videos are sampled with a <video> element, in browsers; elsewhere pass { frames, fps } (the CLI samples files with ffmpeg)");
|
|
258
|
+
}
|
|
259
|
+
let video;
|
|
260
|
+
let objectUrl;
|
|
261
|
+
if (input instanceof HTMLVideoElement) {
|
|
262
|
+
video = input;
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
video = document.createElement("video");
|
|
266
|
+
video.muted = true;
|
|
267
|
+
video.preload = "auto";
|
|
268
|
+
video.crossOrigin = "anonymous";
|
|
269
|
+
if (typeof input === "string" || input instanceof URL)
|
|
270
|
+
video.src = String(input);
|
|
271
|
+
else {
|
|
272
|
+
objectUrl = URL.createObjectURL(input);
|
|
273
|
+
video.src = objectUrl;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
if (video.readyState < 1) {
|
|
278
|
+
await new Promise((resolve, reject) => {
|
|
279
|
+
video.addEventListener("loadedmetadata", () => resolve(), { once: true });
|
|
280
|
+
video.addEventListener("error", () => reject(new WebslmError("INVALID_ARGUMENT", "the video cannot be decoded")), {
|
|
281
|
+
once: true,
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
const duration = Number.isFinite(video.duration) ? video.duration : 0;
|
|
286
|
+
const times = sampleTimes(duration, options.fps ?? DEFAULT_VIDEO_FPS, options.maxFrames ?? DEFAULT_VIDEO_MAX_FRAMES);
|
|
287
|
+
const bytes = [];
|
|
288
|
+
let width = 0;
|
|
289
|
+
let height = 0;
|
|
290
|
+
for (const t of times) {
|
|
291
|
+
await seek(video, t);
|
|
292
|
+
const frame = pixelsOf(video, video.videoWidth, video.videoHeight, VIDEO_CAPTURE_EDGE);
|
|
293
|
+
if (frame.kind !== "rgba")
|
|
294
|
+
throw new WebslmError("ENGINE", "unexpected frame encoding");
|
|
295
|
+
width = frame.width;
|
|
296
|
+
height = frame.height;
|
|
297
|
+
bytes.push(frame.data);
|
|
298
|
+
}
|
|
299
|
+
const byteLength = bytes.reduce((n, b) => n + b.byteLength, 0);
|
|
300
|
+
return {
|
|
301
|
+
entry: { kind: "video", encoding: "rgba", width, height, timestamps: times, duration, byteLength },
|
|
302
|
+
bytes,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
finally {
|
|
306
|
+
if (objectUrl !== undefined)
|
|
307
|
+
URL.revokeObjectURL(objectUrl);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function seek(video, time) {
|
|
311
|
+
return new Promise((resolve, reject) => {
|
|
312
|
+
const done = () => {
|
|
313
|
+
video.removeEventListener("seeked", done);
|
|
314
|
+
video.removeEventListener("error", failed);
|
|
315
|
+
resolve();
|
|
316
|
+
};
|
|
317
|
+
const failed = () => {
|
|
318
|
+
video.removeEventListener("seeked", done);
|
|
319
|
+
reject(new WebslmError("INVALID_ARGUMENT", "the video cannot be decoded"));
|
|
320
|
+
};
|
|
321
|
+
video.addEventListener("seeked", done);
|
|
322
|
+
video.addEventListener("error", failed, { once: true });
|
|
323
|
+
video.currentTime = time;
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
async function readFrames(input) {
|
|
327
|
+
const n = input.frames.length;
|
|
328
|
+
if (n === 0)
|
|
329
|
+
throw new WebslmError("INVALID_ARGUMENT", "a video needs at least one frame");
|
|
330
|
+
const timestamps = input.timestamps !== undefined
|
|
331
|
+
? [...input.timestamps]
|
|
332
|
+
: Array.from({ length: n }, (_, i) => i / (input.fps ?? 1));
|
|
333
|
+
if (timestamps.length !== n) {
|
|
334
|
+
throw new WebslmError("INVALID_ARGUMENT", `${timestamps.length} timestamps for ${n} frames`);
|
|
335
|
+
}
|
|
336
|
+
const duration = input.duration ?? (input.fps !== undefined ? n / input.fps : undefined);
|
|
337
|
+
const frames = await Promise.all(input.frames.map((f) => readImage(f)));
|
|
338
|
+
const bytes = frames.map((f) => (f.kind === "file" ? f.bytes : f.data));
|
|
339
|
+
const byteLength = bytes.reduce((s, b) => s + b.byteLength, 0);
|
|
340
|
+
const extra = duration === undefined ? {} : { duration };
|
|
341
|
+
if (frames.every((f) => f.kind === "file")) {
|
|
342
|
+
return {
|
|
343
|
+
entry: { kind: "video", encoding: "file", frameByteLengths: bytes.map((b) => b.byteLength), timestamps, ...extra, byteLength },
|
|
344
|
+
bytes,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
const first = frames[0];
|
|
348
|
+
if (frames.some((f) => f.kind !== "rgba") || first === undefined || first.kind !== "rgba") {
|
|
349
|
+
throw new WebslmError("INVALID_ARGUMENT", "a video's frames are all pixels or all image files");
|
|
350
|
+
}
|
|
351
|
+
if (frames.some((f) => f.kind === "rgba" && (f.width !== first.width || f.height !== first.height))) {
|
|
352
|
+
throw new WebslmError("INVALID_ARGUMENT", "a video's frames must all be the same size");
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
entry: { kind: "video", encoding: "rgba", width: first.width, height: first.height, timestamps, ...extra, byteLength },
|
|
356
|
+
bytes,
|
|
357
|
+
};
|
|
358
|
+
}
|
package/dist/memory.d.ts
CHANGED
|
@@ -52,6 +52,11 @@ export interface EstimateOptions {
|
|
|
52
52
|
readonly quant?: EstimateFormat;
|
|
53
53
|
/** Positions of one sequence (default: min(4096, the model's maximum)). */
|
|
54
54
|
readonly contextLength?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Count the vision encoder and projector of a vision-language checkpoint
|
|
57
|
+
* (default `true`, as the load option `vision`).
|
|
58
|
+
*/
|
|
59
|
+
readonly vision?: boolean;
|
|
55
60
|
}
|
|
56
61
|
export type LayerType = "full" | "sliding" | "conv" | "linear";
|
|
57
62
|
/** The text decoder hyperparameters the estimate reads (see `TextConfig` in Rust). */
|
package/dist/memory.js
CHANGED
|
@@ -140,9 +140,40 @@ export function matrixBytes(rows, cols, format) {
|
|
|
140
140
|
return values * 4;
|
|
141
141
|
return Math.floor(values / block) * bytes;
|
|
142
142
|
}
|
|
143
|
-
/** Tensors of
|
|
144
|
-
function
|
|
145
|
-
return ["vision", "visual", "multi_modal_projector", "
|
|
143
|
+
/** Tensors of the vision side of a vision-language checkpoint (encoder, projector, connector). */
|
|
144
|
+
function isVision(name) {
|
|
145
|
+
return ["vision", "visual", "multi_modal_projector", "connector."].some((part) => name.includes(part));
|
|
146
|
+
}
|
|
147
|
+
/** Whether the engine loads a vision side for `config` (`webslm_models::vision::has_vision`). */
|
|
148
|
+
function hasVision(config) {
|
|
149
|
+
if (typeof config !== "object" || config === null)
|
|
150
|
+
return false;
|
|
151
|
+
const c = config;
|
|
152
|
+
switch (c.model_type) {
|
|
153
|
+
case "idefics3":
|
|
154
|
+
case "smolvlm":
|
|
155
|
+
case "lfm2_vl":
|
|
156
|
+
return true;
|
|
157
|
+
case "qwen3_5":
|
|
158
|
+
return c.vision_config !== undefined && c.vision_config !== null;
|
|
159
|
+
default:
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Bytes of a vision tensor as the engine stores it: matrices (convolution
|
|
165
|
+
* filters flattened to `[out, in]`) in `format`, position tables, norms and
|
|
166
|
+
* biases in f32.
|
|
167
|
+
*/
|
|
168
|
+
function visionTensorBytes(name, shape, format) {
|
|
169
|
+
const elements = shape.reduce((n, d) => n * d, 1);
|
|
170
|
+
const [rows] = shape;
|
|
171
|
+
if (shape.length >= 2 && rows !== undefined && rows > 1 && !name.includes("norm") && !name.includes("pos")) {
|
|
172
|
+
const cols = elements / rows;
|
|
173
|
+
if (cols >= 16)
|
|
174
|
+
return matrixBytes(rows, cols, format);
|
|
175
|
+
}
|
|
176
|
+
return elements * 4;
|
|
146
177
|
}
|
|
147
178
|
const QUANT_NAMES = ["q8", "q4", "f32", "f16", "bf16"];
|
|
148
179
|
/**
|
|
@@ -159,15 +190,23 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
159
190
|
}
|
|
160
191
|
const text = textConfig(config);
|
|
161
192
|
const embedding = quant === "q4" ? "q8" : quant;
|
|
193
|
+
const vision = options.vision !== false && hasVision(config);
|
|
162
194
|
const tied = text.tieWordEmbeddings === true;
|
|
163
195
|
const entries = Symbol.iterator in tensors
|
|
164
196
|
? tensors
|
|
165
197
|
: Object.entries(tensors).map(([n, t]) => [n, t.shape]);
|
|
166
198
|
let weights = 0;
|
|
199
|
+
let visionWeights = 0;
|
|
167
200
|
let inputEmbedding = 0;
|
|
168
201
|
let widestMatrix = 0;
|
|
169
202
|
for (const [name, shape] of entries) {
|
|
170
|
-
if (
|
|
203
|
+
if (isVision(name)) {
|
|
204
|
+
if (vision)
|
|
205
|
+
visionWeights += visionTensorBytes(name, shape, embedding);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
// The multi-token prediction head is never loaded.
|
|
209
|
+
if (name.includes("mtp.") || (tied && name.startsWith("lm_head")))
|
|
171
210
|
continue;
|
|
172
211
|
const elements = shape.reduce((n, d) => n * d, 1);
|
|
173
212
|
const [rows, cols] = shape;
|
|
@@ -230,17 +269,19 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
230
269
|
const rows = Math.min(PREFILL_ROWS, Math.max(context, 1));
|
|
231
270
|
const activations = rows * (6 * hidden + 3 * intermediate) * 4 + vocab * 4;
|
|
232
271
|
const largestBuffer = Math.max(context * kvWidth * 4, rows * 2 * intermediate * 4, rows * Math.max(widestMatrix, hidden) * 4);
|
|
272
|
+
// The vision encoder is not read to decode a token.
|
|
233
273
|
const decodeBytes = weights - inputEmbedding + kvCache - Math.floor((kvPerToken * context) / 2);
|
|
274
|
+
const allWeights = weights + visionWeights;
|
|
234
275
|
return {
|
|
235
276
|
quant,
|
|
236
|
-
weights,
|
|
277
|
+
weights: allWeights,
|
|
237
278
|
kvCache,
|
|
238
279
|
kvPerToken,
|
|
239
280
|
activations,
|
|
240
281
|
largestBuffer,
|
|
241
282
|
contextLength: context,
|
|
242
283
|
decodeBytes,
|
|
243
|
-
total:
|
|
284
|
+
total: allWeights + kvCache + activations,
|
|
244
285
|
kvLayers: kv,
|
|
245
286
|
};
|
|
246
287
|
}
|