webslm 0.5.0 → 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 +30 -2
- 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/client.d.ts +1 -2
- package/dist/curated.js +9 -0
- package/dist/engine.js +8 -2
- package/dist/fit.d.ts +1 -1
- package/dist/fit.js +2 -1
- package/dist/hub.js +7 -0
- 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 +8 -4
- package/dist/models.js +69 -10
- package/dist/native.d.ts +3 -0
- package/dist/protocol.d.ts +28 -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 +95 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +23 -4
- package/wasm/relaxed/webslm_wasm.js +69 -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 +23 -4
- package/wasm/simd/webslm_wasm.js +69 -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 +24 -5
- package/wasm/threads/webslm_wasm.js +74 -21
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +6 -4
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
|
}
|
package/dist/models.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
|
|
2
2
|
import { EngineClient } from "./client.js";
|
|
3
3
|
import { type CheckpointTraits } from "./curated.js";
|
|
4
|
-
import type { AdapterSource, Backend, ApplyAdapterOptions,
|
|
4
|
+
import type { AdapterSource, Backend, ApplyAdapterOptions, ChatInputMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
|
|
5
5
|
/**
|
|
6
6
|
* An engine (a worker, or the calling thread) that several models can share
|
|
7
7
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -112,6 +112,8 @@ declare abstract class Conversation {
|
|
|
112
112
|
protected abstract readonly hasChatTemplate: boolean;
|
|
113
113
|
/** What picks the model's recommended sampling. */
|
|
114
114
|
protected abstract readonly checkpoint: CheckpointTraits;
|
|
115
|
+
/** The images and videos the model takes (`undefined`: text only). */
|
|
116
|
+
protected abstract readonly vision: ModelInfo["vision"];
|
|
115
117
|
protected abstract onLength(length: number): void;
|
|
116
118
|
constructor(client: EngineClient, modelId: number);
|
|
117
119
|
/**
|
|
@@ -119,14 +121,14 @@ declare abstract class Conversation {
|
|
|
119
121
|
* the session's cache are not recomputed. Stopping (`stop()`, `break`, or
|
|
120
122
|
* the signal) ends the stream normally with `finishReason: "aborted"`.
|
|
121
123
|
*/
|
|
122
|
-
chat(messages: readonly
|
|
124
|
+
chat(messages: readonly ChatInputMessage[], options?: GenerateOptions): ChatStream;
|
|
123
125
|
/**
|
|
124
126
|
* Generates a whole answer. A string prompt is sent as a user message when
|
|
125
127
|
* the checkpoint has a chat template (pass `raw: true` to complete it as
|
|
126
128
|
* plain text); an array is a conversation. Rejects with `ABORTED` when the
|
|
127
129
|
* signal fires.
|
|
128
130
|
*/
|
|
129
|
-
generate(prompt: string | readonly
|
|
131
|
+
generate(prompt: string | readonly ChatInputMessage[], options?: CompletionOptions): Promise<string>;
|
|
130
132
|
/** Encodes text into token ids. */
|
|
131
133
|
tokenize(text: string, options?: {
|
|
132
134
|
addSpecialTokens?: boolean;
|
|
@@ -140,7 +142,7 @@ declare abstract class Conversation {
|
|
|
140
142
|
* a new assistant turn. `templateKwargs` are passed to the template (e.g.
|
|
141
143
|
* `{ enable_thinking: false }`).
|
|
142
144
|
*/
|
|
143
|
-
renderChat(messages: readonly
|
|
145
|
+
renderChat(messages: readonly ChatInputMessage[], templateKwargs?: Readonly<Record<string, unknown>>): Promise<string>;
|
|
144
146
|
}
|
|
145
147
|
/** A loaded model. Its own `chat`/`generate` use a default session. */
|
|
146
148
|
export declare class Model extends Conversation {
|
|
@@ -157,6 +159,7 @@ export declare class Model extends Conversation {
|
|
|
157
159
|
}, ownsEngine?: boolean);
|
|
158
160
|
protected get hasChatTemplate(): boolean;
|
|
159
161
|
protected get checkpoint(): CheckpointTraits;
|
|
162
|
+
protected get vision(): ModelInfo["vision"];
|
|
160
163
|
protected onLength(): void;
|
|
161
164
|
/** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
|
|
162
165
|
info(): ModelInfo;
|
|
@@ -210,6 +213,7 @@ export declare class Session extends Conversation {
|
|
|
210
213
|
constructor(client: EngineClient, modelId: number, sessionId: number, info: ModelInfo, onDispose: () => void);
|
|
211
214
|
protected get hasChatTemplate(): boolean;
|
|
212
215
|
protected get checkpoint(): CheckpointTraits;
|
|
216
|
+
protected get vision(): ModelInfo["vision"];
|
|
213
217
|
protected onLength(length: number): void;
|
|
214
218
|
/** Positions in the cache (as of the last completed call). */
|
|
215
219
|
get length(): number;
|