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/README.md +31 -3
- 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 +14 -2
- package/dist/fit.d.ts +2 -2
- package/dist/fit.js +6 -2
- package/dist/hub.js +7 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/media.d.ts +72 -0
- package/dist/media.js +358 -0
- package/dist/memory.d.ts +29 -7
- package/dist/memory.js +95 -16
- package/dist/models.d.ts +8 -4
- package/dist/models.js +87 -10
- 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 +144 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +24 -4
- package/wasm/relaxed/webslm_wasm.js +70 -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 +24 -4
- package/wasm/simd/webslm_wasm.js +70 -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 +25 -5
- package/wasm/threads/webslm_wasm.js +76 -22
- 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
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
* Memory a model needs, estimated from its `config.json` and safetensors
|
|
3
3
|
* headers before downloading it: a port of the Rust estimate
|
|
4
4
|
* (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
|
|
5
|
-
* KV cache layer by layer (full attention grows with the context,
|
|
6
|
-
*
|
|
7
|
-
* convolution and linear-attention layers a
|
|
8
|
-
* activations of a 512-token prefill. Both
|
|
9
|
-
* against the same cases
|
|
5
|
+
* KV cache layer by layer (full attention grows with the context, in f32
|
|
6
|
+
* or int8, up to the KV eviction budget; sliding-window layers keep a ring
|
|
7
|
+
* of `2 × window - 1` positions, convolution and linear-attention layers a
|
|
8
|
+
* fixed state) and the activations of a 512-token prefill. Both
|
|
9
|
+
* implementations are checked against the same cases
|
|
10
|
+
* (`fixtures/memory/estimates.json`).
|
|
10
11
|
*/
|
|
11
12
|
import type { HeaderTensors } from "./hub.js";
|
|
12
13
|
import type { Quant } from "./types.js";
|
|
@@ -24,11 +25,11 @@ export interface MemoryEstimate {
|
|
|
24
25
|
readonly weights: number;
|
|
25
26
|
/** KV caches and recurrent states of one sequence at `contextLength`. */
|
|
26
27
|
readonly kvCache: number;
|
|
27
|
-
/** What one more position adds to the KV cache. */
|
|
28
|
+
/** What one more position adds to the KV cache (0 once KV eviction caps it below the context). */
|
|
28
29
|
readonly kvPerToken: number;
|
|
29
30
|
/** Activations of a prefill batch. */
|
|
30
31
|
readonly activations: number;
|
|
31
|
-
/** The largest single buffer (
|
|
32
|
+
/** The largest single buffer: the widest activation (KV caches are paged below the device's limit). */
|
|
32
33
|
readonly largestBuffer: number;
|
|
33
34
|
/** Positions the estimate assumes. */
|
|
34
35
|
readonly contextLength: number;
|
|
@@ -47,12 +48,33 @@ export interface MemoryEstimate {
|
|
|
47
48
|
readonly linearAttention: KvLayers;
|
|
48
49
|
};
|
|
49
50
|
}
|
|
51
|
+
/** How full-attention layers store keys and values (`kvCache` load option). */
|
|
52
|
+
export type KvCacheType = "f32" | "int8";
|
|
50
53
|
export interface EstimateOptions {
|
|
51
54
|
/** Weight format (default `"q8"`). */
|
|
52
55
|
readonly quant?: EstimateFormat;
|
|
53
56
|
/** Positions of one sequence (default: min(4096, the model's maximum)). */
|
|
54
57
|
readonly contextLength?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Count the vision encoder and projector of a vision-language checkpoint
|
|
60
|
+
* (default `true`, as the load option `vision`).
|
|
61
|
+
*/
|
|
62
|
+
readonly vision?: boolean;
|
|
63
|
+
/** KV cache storage of full-attention layers (default `"f32"`). */
|
|
64
|
+
readonly kvCache?: KvCacheType;
|
|
65
|
+
/** Int8 KV cache: the most recent positions kept in f32 (default 128). */
|
|
66
|
+
readonly kvResidual?: number;
|
|
67
|
+
/** KV eviction: most positions a full-attention layer holds. */
|
|
68
|
+
readonly kvBudget?: number;
|
|
55
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Bytes of one full-attention cache holding `positions` positions: f32, or
|
|
72
|
+
* int8 in the KIVI layout (8-bit codes, a minimum and scale per channel
|
|
73
|
+
* and group of 32 positions for keys, per position and head for values,
|
|
74
|
+
* and an f32 ring of `residual + 32` positions). `KvCacheOptions::bytes`
|
|
75
|
+
* in Rust.
|
|
76
|
+
*/
|
|
77
|
+
export declare function kvCacheBytes(kvHeads: number, headDim: number, positions: number, type?: KvCacheType, residual?: number): number;
|
|
56
78
|
export type LayerType = "full" | "sliding" | "conv" | "linear";
|
|
57
79
|
/** The text decoder hyperparameters the estimate reads (see `TextConfig` in Rust). */
|
|
58
80
|
export interface TextConfig {
|
package/dist/memory.js
CHANGED
|
@@ -2,13 +2,39 @@
|
|
|
2
2
|
* Memory a model needs, estimated from its `config.json` and safetensors
|
|
3
3
|
* headers before downloading it: a port of the Rust estimate
|
|
4
4
|
* (`crates/webslm-models/src/memory.rs`). Weights in the load format, the
|
|
5
|
-
* KV cache layer by layer (full attention grows with the context,
|
|
6
|
-
*
|
|
7
|
-
* convolution and linear-attention layers a
|
|
8
|
-
* activations of a 512-token prefill. Both
|
|
9
|
-
* against the same cases
|
|
5
|
+
* KV cache layer by layer (full attention grows with the context, in f32
|
|
6
|
+
* or int8, up to the KV eviction budget; sliding-window layers keep a ring
|
|
7
|
+
* of `2 × window - 1` positions, convolution and linear-attention layers a
|
|
8
|
+
* fixed state) and the activations of a 512-token prefill. Both
|
|
9
|
+
* implementations are checked against the same cases
|
|
10
|
+
* (`fixtures/memory/estimates.json`).
|
|
10
11
|
*/
|
|
11
12
|
import { WebslmError } from "./errors.js";
|
|
13
|
+
/** Positions an int8 KV cache quantizes together. */
|
|
14
|
+
const KV_GROUP = 32;
|
|
15
|
+
/** Most recent positions an int8 KV cache keeps in f32 by default. */
|
|
16
|
+
const DEFAULT_KV_RESIDUAL = 128;
|
|
17
|
+
/**
|
|
18
|
+
* Bytes of one full-attention cache holding `positions` positions: f32, or
|
|
19
|
+
* int8 in the KIVI layout (8-bit codes, a minimum and scale per channel
|
|
20
|
+
* and group of 32 positions for keys, per position and head for values,
|
|
21
|
+
* and an f32 ring of `residual + 32` positions). `KvCacheOptions::bytes`
|
|
22
|
+
* in Rust.
|
|
23
|
+
*/
|
|
24
|
+
export function kvCacheBytes(kvHeads, headDim, positions, type = "f32", residual = DEFAULT_KV_RESIDUAL) {
|
|
25
|
+
const f32Position = 2 * kvHeads * headDim * 4;
|
|
26
|
+
if (type === "f32")
|
|
27
|
+
return positions * f32Position;
|
|
28
|
+
const residualPositions = Math.ceil(residual / KV_GROUP) * KV_GROUP;
|
|
29
|
+
const quantized = Math.floor(Math.max(positions - residualPositions, 0) / KV_GROUP) * KV_GROUP;
|
|
30
|
+
const ring = Math.min(residualPositions + KV_GROUP, positions);
|
|
31
|
+
return Math.ceil(int8BytesPerPosition(kvHeads, headDim) * quantized) + ring * f32Position;
|
|
32
|
+
}
|
|
33
|
+
/** Bytes of one quantized position of an int8 KV cache. */
|
|
34
|
+
function int8BytesPerPosition(kvHeads, headDim) {
|
|
35
|
+
const width = kvHeads * headDim;
|
|
36
|
+
return 2 * width + (width * 8) / KV_GROUP + kvHeads * 8;
|
|
37
|
+
}
|
|
12
38
|
/** Rows of the prefill batch the activation estimate assumes. */
|
|
13
39
|
const PREFILL_ROWS = 512;
|
|
14
40
|
/** Context length when none is given, capped by the model. */
|
|
@@ -140,9 +166,40 @@ export function matrixBytes(rows, cols, format) {
|
|
|
140
166
|
return values * 4;
|
|
141
167
|
return Math.floor(values / block) * bytes;
|
|
142
168
|
}
|
|
143
|
-
/** Tensors of
|
|
144
|
-
function
|
|
145
|
-
return ["vision", "visual", "multi_modal_projector", "
|
|
169
|
+
/** Tensors of the vision side of a vision-language checkpoint (encoder, projector, connector). */
|
|
170
|
+
function isVision(name) {
|
|
171
|
+
return ["vision", "visual", "multi_modal_projector", "connector."].some((part) => name.includes(part));
|
|
172
|
+
}
|
|
173
|
+
/** Whether the engine loads a vision side for `config` (`webslm_models::vision::has_vision`). */
|
|
174
|
+
function hasVision(config) {
|
|
175
|
+
if (typeof config !== "object" || config === null)
|
|
176
|
+
return false;
|
|
177
|
+
const c = config;
|
|
178
|
+
switch (c.model_type) {
|
|
179
|
+
case "idefics3":
|
|
180
|
+
case "smolvlm":
|
|
181
|
+
case "lfm2_vl":
|
|
182
|
+
return true;
|
|
183
|
+
case "qwen3_5":
|
|
184
|
+
return c.vision_config !== undefined && c.vision_config !== null;
|
|
185
|
+
default:
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Bytes of a vision tensor as the engine stores it: matrices (convolution
|
|
191
|
+
* filters flattened to `[out, in]`) in `format`, position tables, norms and
|
|
192
|
+
* biases in f32.
|
|
193
|
+
*/
|
|
194
|
+
function visionTensorBytes(name, shape, format) {
|
|
195
|
+
const elements = shape.reduce((n, d) => n * d, 1);
|
|
196
|
+
const [rows] = shape;
|
|
197
|
+
if (shape.length >= 2 && rows !== undefined && rows > 1 && !name.includes("norm") && !name.includes("pos")) {
|
|
198
|
+
const cols = elements / rows;
|
|
199
|
+
if (cols >= 16)
|
|
200
|
+
return matrixBytes(rows, cols, format);
|
|
201
|
+
}
|
|
202
|
+
return elements * 4;
|
|
146
203
|
}
|
|
147
204
|
const QUANT_NAMES = ["q8", "q4", "f32", "f16", "bf16"];
|
|
148
205
|
/**
|
|
@@ -159,15 +216,23 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
159
216
|
}
|
|
160
217
|
const text = textConfig(config);
|
|
161
218
|
const embedding = quant === "q4" ? "q8" : quant;
|
|
219
|
+
const vision = options.vision !== false && hasVision(config);
|
|
162
220
|
const tied = text.tieWordEmbeddings === true;
|
|
163
221
|
const entries = Symbol.iterator in tensors
|
|
164
222
|
? tensors
|
|
165
223
|
: Object.entries(tensors).map(([n, t]) => [n, t.shape]);
|
|
166
224
|
let weights = 0;
|
|
225
|
+
let visionWeights = 0;
|
|
167
226
|
let inputEmbedding = 0;
|
|
168
227
|
let widestMatrix = 0;
|
|
169
228
|
for (const [name, shape] of entries) {
|
|
170
|
-
if (
|
|
229
|
+
if (isVision(name)) {
|
|
230
|
+
if (vision)
|
|
231
|
+
visionWeights += visionTensorBytes(name, shape, embedding);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
// The multi-token prediction head is never loaded.
|
|
235
|
+
if (name.includes("mtp.") || (tied && name.startsWith("lm_head")))
|
|
171
236
|
continue;
|
|
172
237
|
const elements = shape.reduce((n, d) => n * d, 1);
|
|
173
238
|
const [rows, cols] = shape;
|
|
@@ -190,7 +255,18 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
190
255
|
const context = options.contextLength ?? Math.min(text.maxPositionEmbeddings ?? DEFAULT_CONTEXT, DEFAULT_CONTEXT);
|
|
191
256
|
const kvWidth = text.numKeyValueHeads * text.headDim;
|
|
192
257
|
const hidden = text.hiddenSize;
|
|
193
|
-
const
|
|
258
|
+
const f32PerToken = 2 * kvWidth * 4;
|
|
259
|
+
const kvType = options.kvCache ?? "f32";
|
|
260
|
+
if (kvType !== "f32" && kvType !== "int8") {
|
|
261
|
+
throw new WebslmError("INVALID_ARGUMENT", "kvCache must be f32 or int8");
|
|
262
|
+
}
|
|
263
|
+
const held = options.kvBudget === undefined ? context : Math.min(context, options.kvBudget);
|
|
264
|
+
const fullBytes = kvCacheBytes(text.numKeyValueHeads, text.headDim, held, kvType, options.kvResidual ?? DEFAULT_KV_RESIDUAL);
|
|
265
|
+
const fullPerToken = held < context
|
|
266
|
+
? 0
|
|
267
|
+
: kvType === "f32"
|
|
268
|
+
? f32PerToken
|
|
269
|
+
: Math.ceil(int8BytesPerPosition(text.numKeyValueHeads, text.headDim));
|
|
194
270
|
const kv = {
|
|
195
271
|
fullAttention: { layers: 0, bytes: 0 },
|
|
196
272
|
slidingAttention: { layers: 0, bytes: 0 },
|
|
@@ -203,7 +279,7 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
203
279
|
case "sliding": {
|
|
204
280
|
const window = text.slidingWindow ?? context;
|
|
205
281
|
kv.slidingAttention.layers += 1;
|
|
206
|
-
kv.slidingAttention.bytes +=
|
|
282
|
+
kv.slidingAttention.bytes += f32PerToken * Math.min(Math.max(2 * window - 1, 0), context);
|
|
207
283
|
break;
|
|
208
284
|
}
|
|
209
285
|
case "conv":
|
|
@@ -220,7 +296,7 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
220
296
|
case "full":
|
|
221
297
|
kvPerToken += fullPerToken;
|
|
222
298
|
kv.fullAttention.layers += 1;
|
|
223
|
-
kv.fullAttention.bytes +=
|
|
299
|
+
kv.fullAttention.bytes += fullBytes;
|
|
224
300
|
break;
|
|
225
301
|
}
|
|
226
302
|
}
|
|
@@ -229,18 +305,21 @@ export function estimateModelMemory(config, tensors, options = {}) {
|
|
|
229
305
|
const vocab = text.vocabSize ?? 0;
|
|
230
306
|
const rows = Math.min(PREFILL_ROWS, Math.max(context, 1));
|
|
231
307
|
const activations = rows * (6 * hidden + 3 * intermediate) * 4 + vocab * 4;
|
|
232
|
-
const largestBuffer = Math.max(
|
|
233
|
-
|
|
308
|
+
const largestBuffer = Math.max(rows * 2 * intermediate * 4, rows * Math.max(widestMatrix, hidden) * 4);
|
|
309
|
+
// The full-attention caches at half the context, on average; the vision
|
|
310
|
+
// encoder is not read to decode a token.
|
|
311
|
+
const decodeBytes = weights - inputEmbedding + kvCache - Math.floor(kv.fullAttention.bytes / 2);
|
|
312
|
+
const allWeights = weights + visionWeights;
|
|
234
313
|
return {
|
|
235
314
|
quant,
|
|
236
|
-
weights,
|
|
315
|
+
weights: allWeights,
|
|
237
316
|
kvCache,
|
|
238
317
|
kvPerToken,
|
|
239
318
|
activations,
|
|
240
319
|
largestBuffer,
|
|
241
320
|
contextLength: context,
|
|
242
321
|
decodeBytes,
|
|
243
|
-
total:
|
|
322
|
+
total: allWeights + kvCache + activations,
|
|
244
323
|
kvLayers: kv,
|
|
245
324
|
};
|
|
246
325
|
}
|
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;
|