webslm 0.7.0 → 0.9.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 +85 -2
- package/dist/ai-sdk/embedding-model.d.ts +52 -0
- package/dist/ai-sdk/embedding-model.js +112 -0
- package/dist/ai-sdk/image-model.d.ts +53 -0
- package/dist/ai-sdk/image-model.js +148 -0
- package/dist/ai-sdk/index.d.ts +39 -0
- package/dist/ai-sdk/index.js +66 -11
- package/dist/client.d.ts +6 -0
- package/dist/client.js +8 -1
- package/dist/download.js +2 -2
- package/dist/engine.js +181 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +1 -0
- package/dist/hub.d.ts +38 -3
- package/dist/hub.js +87 -8
- package/dist/image.d.ts +201 -0
- package/dist/image.js +353 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +4 -2
- package/dist/models.d.ts +19 -1
- package/dist/models.js +45 -6
- package/dist/native.d.ts +28 -0
- package/dist/protocol.d.ts +75 -2
- package/dist/simple.d.ts +4 -1
- package/dist/simple.js +9 -2
- package/dist/types.d.ts +39 -1
- package/dist/wasm.d.ts +2 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +70 -6
- package/wasm/relaxed/webslm_wasm.js +163 -18
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +10 -3
- package/wasm/simd/webslm_wasm.d.ts +70 -6
- package/wasm/simd/webslm_wasm.js +163 -18
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +10 -3
- package/wasm/threads/webslm_wasm.d.ts +71 -7
- package/wasm/threads/webslm_wasm.js +168 -23
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +11 -4
package/dist/ai-sdk/index.js
CHANGED
|
@@ -13,21 +13,55 @@
|
|
|
13
13
|
* });
|
|
14
14
|
* ```
|
|
15
15
|
*
|
|
16
|
+
* Encoders (BERT, ModernBERT, model2vec) are embedding models, behind
|
|
17
|
+
* `embed` and `embedMany`:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { embedMany } from "ai";
|
|
21
|
+
*
|
|
22
|
+
* const { embeddings } = await embedMany({
|
|
23
|
+
* model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
|
|
24
|
+
* values: ["sunny day at the beach", "rainy afternoon in the city"],
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Text-to-image models come from `webslm.imageModel(id)`, for the AI SDK's
|
|
29
|
+
* `generateImage`:
|
|
30
|
+
*
|
|
31
|
+
* ```ts
|
|
32
|
+
* import { generateImage } from "ai";
|
|
33
|
+
*
|
|
34
|
+
* const { image } = await generateImage({
|
|
35
|
+
* model: webslm.imageModel("IDKiro/sdxs-512-dreamshaper"),
|
|
36
|
+
* prompt: "a lighthouse at dusk",
|
|
37
|
+
* seed: 42,
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
16
41
|
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
17
42
|
* `webslm`: install them to use this entry point.
|
|
18
43
|
*
|
|
19
44
|
* @packageDocumentation
|
|
20
45
|
*/
|
|
21
46
|
import { WebslmError } from "../errors.js";
|
|
47
|
+
import { loadImageModel } from "../image.js";
|
|
22
48
|
import { loadModel } from "../models.js";
|
|
49
|
+
import { EMBEDDING_SETTING_KEYS, WebslmEmbeddingModel, } from "./embedding-model.js";
|
|
50
|
+
import { ImageModelSlot, WebslmImageModel, } from "./image-model.js";
|
|
23
51
|
import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
|
|
24
52
|
import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
|
|
25
53
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "../curated.js";
|
|
26
54
|
export { searchModels } from "../hub.js";
|
|
27
55
|
export { DEFAULT_MODEL } from "../simple.js";
|
|
28
56
|
export { WebslmLanguageModel, } from "./language-model.js";
|
|
29
|
-
|
|
30
|
-
|
|
57
|
+
export { WebslmEmbeddingModel, } from "./embedding-model.js";
|
|
58
|
+
export { MAX_IMAGES_PER_CALL, WebslmImageModel, } from "./image-model.js";
|
|
59
|
+
export { DEFAULT_IMAGE_MODEL } from "../image.js";
|
|
60
|
+
function checkModelId(modelId) {
|
|
61
|
+
if (typeof modelId !== "string" || modelId.trim() === "") {
|
|
62
|
+
throw new WebslmError("INVALID_ARGUMENT", "the model id must be a Hugging Face repository id");
|
|
63
|
+
}
|
|
64
|
+
return modelId.trim();
|
|
31
65
|
}
|
|
32
66
|
/**
|
|
33
67
|
* Creates a provider with its own load options and model cache.
|
|
@@ -42,29 +76,50 @@ function unsupportedModel(kind) {
|
|
|
42
76
|
export function createWebslm(options = {}) {
|
|
43
77
|
const engine = options.engine ?? { loadModel };
|
|
44
78
|
const slots = new Map();
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
79
|
+
const imageEngine = options.imageEngine ?? { loadImageModel };
|
|
80
|
+
const imageSlots = new Map();
|
|
81
|
+
const imageModel = (modelId, settings = {}) => {
|
|
82
|
+
const id = checkModelId(modelId);
|
|
83
|
+
const { steps: _steps, guidance: _guidance, negativePrompt: _negative, onProgress, ...load } = settings;
|
|
84
|
+
void _steps;
|
|
85
|
+
void _guidance;
|
|
86
|
+
void _negative;
|
|
87
|
+
const key = JSON.stringify([id, Object.entries(load).sort(([a], [b]) => a.localeCompare(b))]);
|
|
88
|
+
let slot = imageSlots.get(key);
|
|
89
|
+
if (slot === undefined) {
|
|
90
|
+
slot = new ImageModelSlot(imageEngine, id, { ...load, ...(onProgress === undefined ? {} : { onProgress }) });
|
|
91
|
+
imageSlots.set(key, slot);
|
|
48
92
|
}
|
|
49
|
-
|
|
50
|
-
|
|
93
|
+
return new WebslmImageModel(id, slot, settings);
|
|
94
|
+
};
|
|
95
|
+
const slotFor = (id, loadOptions) => {
|
|
51
96
|
const key = slotKey(id, loadOptions);
|
|
52
97
|
let slot = slots.get(key);
|
|
53
98
|
if (slot === undefined) {
|
|
54
99
|
slot = new ModelSlot(engine, id, loadOptions);
|
|
55
100
|
slots.set(key, slot);
|
|
56
101
|
}
|
|
57
|
-
return
|
|
102
|
+
return slot;
|
|
103
|
+
};
|
|
104
|
+
const languageModel = (modelId, settings = {}) => {
|
|
105
|
+
const id = checkModelId(modelId);
|
|
106
|
+
const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, CALL_SETTING_KEYS) };
|
|
107
|
+
return new WebslmLanguageModel(id, slotFor(id, loadOptions), settings);
|
|
108
|
+
};
|
|
109
|
+
const embeddingModel = (modelId, settings = {}) => {
|
|
110
|
+
const id = checkModelId(modelId);
|
|
111
|
+
const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, EMBEDDING_SETTING_KEYS) };
|
|
112
|
+
return new WebslmEmbeddingModel(id, slotFor(id, loadOptions), settings);
|
|
58
113
|
};
|
|
59
114
|
const provider = (modelId, settings) => languageModel(modelId, settings);
|
|
60
115
|
return Object.assign(provider, {
|
|
61
116
|
specificationVersion: "v4",
|
|
62
117
|
languageModel,
|
|
63
|
-
embeddingModel
|
|
64
|
-
imageModel
|
|
118
|
+
embeddingModel,
|
|
119
|
+
imageModel,
|
|
65
120
|
unloadAll: async () => {
|
|
66
121
|
const all = [...slots.values()];
|
|
67
|
-
await Promise.all(all.map((slot) => slot.unload()));
|
|
122
|
+
await Promise.all([...all.map((slot) => slot.unload()), ...[...imageSlots.values()].map((slot) => slot.unload())]);
|
|
68
123
|
},
|
|
69
124
|
});
|
|
70
125
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -35,6 +35,12 @@ export interface RequestHooks {
|
|
|
35
35
|
readonly onRead?: FetchFile;
|
|
36
36
|
/** Serves reads of a `fetch` LoRA adapter source. */
|
|
37
37
|
readonly onAdapterRead?: FetchFile;
|
|
38
|
+
/** Serves reads of a `fetch` image decoder source. */
|
|
39
|
+
readonly onDecoderRead?: FetchFile;
|
|
40
|
+
/** Progress of an image generation. */
|
|
41
|
+
readonly onImageProgress?: (progress: Extract<Response, {
|
|
42
|
+
type: "imageProgress";
|
|
43
|
+
}>) => void;
|
|
38
44
|
readonly signal?: AbortSignal;
|
|
39
45
|
readonly transfer?: Transferable[];
|
|
40
46
|
}
|
package/dist/client.js
CHANGED
|
@@ -87,8 +87,15 @@ export class EngineClient {
|
|
|
87
87
|
case "prefill":
|
|
88
88
|
pending.hooks.onPrefill?.(message.done, message.total);
|
|
89
89
|
break;
|
|
90
|
+
case "imageProgress":
|
|
91
|
+
pending.hooks.onImageProgress?.(message);
|
|
92
|
+
break;
|
|
90
93
|
case "read":
|
|
91
|
-
void this.#serveRead(message.target === "adapter"
|
|
94
|
+
void this.#serveRead(message.target === "adapter"
|
|
95
|
+
? pending.hooks.onAdapterRead
|
|
96
|
+
: message.target === "decoder"
|
|
97
|
+
? pending.hooks.onDecoderRead
|
|
98
|
+
: pending.hooks.onRead, message);
|
|
92
99
|
break;
|
|
93
100
|
}
|
|
94
101
|
}
|
package/dist/download.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { checkRepoId, filePath, readCliManifest, readManifest, readRef, writeCliManifest, writeManifest, writeRef, } from "./cache/models.js";
|
|
16
16
|
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
17
|
-
import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, selectCheckpointFiles, } from "./hub.js";
|
|
17
|
+
import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, isImagePipelineListing, selectCheckpointFiles, } from "./hub.js";
|
|
18
18
|
const SHA_PATTERN = /^[0-9a-f]{40}$/;
|
|
19
19
|
/** Makes `repo@revision` available in `options.store` and returns a reader over it. */
|
|
20
20
|
export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
@@ -91,7 +91,7 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
|
|
|
91
91
|
: `${repo}@${rev} has no ${options.file}`);
|
|
92
92
|
}
|
|
93
93
|
const ggufWeights = selected.weights.some(isGgufFile);
|
|
94
|
-
if (!names.includes("config.json") && !isAdapterListing(names) && !ggufWeights) {
|
|
94
|
+
if (!names.includes("config.json") && !isAdapterListing(names) && !isImagePipelineListing(names) && !ggufWeights) {
|
|
95
95
|
throw new WebslmError("INVALID_CHECKPOINT", `${repo}@${rev} has no config.json`);
|
|
96
96
|
}
|
|
97
97
|
const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];
|
package/dist/engine.js
CHANGED
|
@@ -104,6 +104,7 @@ export function describeCpu(cpu, activations = "quantized") {
|
|
|
104
104
|
export class Engine {
|
|
105
105
|
#host;
|
|
106
106
|
#models = new Map();
|
|
107
|
+
#imageModels = new Map();
|
|
107
108
|
#controllers = new Map();
|
|
108
109
|
#pendingReads = new Map();
|
|
109
110
|
#nextModel = 1;
|
|
@@ -219,7 +220,27 @@ export class Engine {
|
|
|
219
220
|
return [
|
|
220
221
|
await this.#model(request.model).handle.model.renderChat(JSON.stringify(request.messages), JSON.stringify(request.templateKwargs)),
|
|
221
222
|
];
|
|
223
|
+
case "embed": {
|
|
224
|
+
const { handle } = this.#model(request.model);
|
|
225
|
+
const result = (await handle.model.embed(JSON.stringify(request.texts), JSON.stringify(request.options)));
|
|
226
|
+
const data = transferable(result.data, handle.runtime);
|
|
227
|
+
const tokens = transferable(result.tokens, handle.runtime);
|
|
228
|
+
const value = { data, dimensions: result.dimensions, tokens };
|
|
229
|
+
return [value, [data.buffer, tokens.buffer]];
|
|
230
|
+
}
|
|
231
|
+
case "loadImage":
|
|
232
|
+
return [await this.#loadImage(request, signal)];
|
|
233
|
+
case "generateImage": {
|
|
234
|
+
const result = await this.#generateImage(request, signal);
|
|
235
|
+
return [result, result.rgba.buffer instanceof ArrayBuffer ? [result.rgba.buffer] : []];
|
|
236
|
+
}
|
|
222
237
|
case "unload": {
|
|
238
|
+
const image = this.#imageModels.get(request.model);
|
|
239
|
+
if (image !== undefined) {
|
|
240
|
+
image.handle.model.free();
|
|
241
|
+
this.#imageModels.delete(request.model);
|
|
242
|
+
return [true];
|
|
243
|
+
}
|
|
223
244
|
const model = this.#models.get(request.model);
|
|
224
245
|
if (model !== undefined) {
|
|
225
246
|
for (const session of model.sessions.values())
|
|
@@ -547,6 +568,7 @@ export class Engine {
|
|
|
547
568
|
wasm = await WasmModel.load(jsSource, JSON.stringify({
|
|
548
569
|
// `auto` on a GGUF file: the engine keeps the file's own format.
|
|
549
570
|
...(options.quant === "auto" ? {} : { format: options.quant }),
|
|
571
|
+
...(options.defaultQuant === true || options.autoQuant === true ? { defaultFormat: true } : {}),
|
|
550
572
|
...(gguf === undefined ? {} : { ggufFile: gguf }),
|
|
551
573
|
device: options.device ?? "auto",
|
|
552
574
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
@@ -664,6 +686,7 @@ export class Engine {
|
|
|
664
686
|
try {
|
|
665
687
|
model = await addon.NativeModel.load(dir, JSON.stringify({
|
|
666
688
|
format: options.autoQuant === true ? "auto" : options.quant,
|
|
689
|
+
...(options.defaultQuant === true ? { defaultFormat: true } : {}),
|
|
667
690
|
device: options.device ?? "auto",
|
|
668
691
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
669
692
|
...(options.kvCache === undefined ? {} : { kvCache: options.kvCache }),
|
|
@@ -757,6 +780,136 @@ export class Engine {
|
|
|
757
780
|
return removed === null ? null : (lora ?? removed);
|
|
758
781
|
});
|
|
759
782
|
}
|
|
783
|
+
/**
|
|
784
|
+
* Loads a text-to-image pipeline (and a standalone decoder): on the
|
|
785
|
+
* native engine from the snapshot directories the download wrote, else
|
|
786
|
+
* on the WebAssembly engine. Image models are compute-bound: `auto` takes
|
|
787
|
+
* the GPU whenever there is one.
|
|
788
|
+
*/
|
|
789
|
+
async #loadImage(request, signal) {
|
|
790
|
+
const started = now();
|
|
791
|
+
const { options } = request;
|
|
792
|
+
const active = { id: request.id, signal };
|
|
793
|
+
const progress = (p) => this.#host.post({ type: "progress", id: active.id, progress: p });
|
|
794
|
+
let native = await chooseNative(options.backend ?? "auto", request.source, options.wasmFlavour, options.cacheDir);
|
|
795
|
+
if (native.addon !== undefined && request.decoder !== undefined && request.decoder.kind !== "hub") {
|
|
796
|
+
if (options.backend === "native") {
|
|
797
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", 'backend "native": the native engine loads hub decoders only');
|
|
798
|
+
}
|
|
799
|
+
native = { note: "auto: WebAssembly (the native engine loads hub decoders only)" };
|
|
800
|
+
}
|
|
801
|
+
if (native.addon !== undefined && native.addon.NativeImageModel === undefined) {
|
|
802
|
+
if (options.backend === "native") {
|
|
803
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", 'backend "native": this native engine has no image models');
|
|
804
|
+
}
|
|
805
|
+
native = { note: "auto: WebAssembly (this native engine has no image models)" };
|
|
806
|
+
}
|
|
807
|
+
let handle;
|
|
808
|
+
let raw;
|
|
809
|
+
let opened;
|
|
810
|
+
const loadOptions = JSON.stringify({ format: options.quant, device: options.device ?? "auto" });
|
|
811
|
+
if (native.addon?.NativeImageModel !== undefined) {
|
|
812
|
+
const createHasher = await nodeSha256();
|
|
813
|
+
opened = await this.#openSource(active, request.source, options.cacheDir, progress, createHasher);
|
|
814
|
+
const decoder = request.decoder === undefined
|
|
815
|
+
? undefined
|
|
816
|
+
: await this.#openSource(active, request.decoder, options.cacheDir, progress, createHasher, "decoder");
|
|
817
|
+
const dir = await snapshotDirectory(opened);
|
|
818
|
+
const decoderDir = decoder === undefined ? undefined : await snapshotDirectory(decoder);
|
|
819
|
+
if (dir === undefined || (decoder !== undefined && decoderDir === undefined)) {
|
|
820
|
+
throw new WebslmError("ENGINE", "the native engine needs the model in the cache directory");
|
|
821
|
+
}
|
|
822
|
+
const model = await native.addon.NativeImageModel.load(dir, loadOptions, {
|
|
823
|
+
...(decoderDir === undefined ? {} : { decoderDir }),
|
|
824
|
+
...(options.threads === undefined ? {} : { threads: options.threads }),
|
|
825
|
+
});
|
|
826
|
+
handle = { runtime: "native", model, addon: native.addon };
|
|
827
|
+
raw = model.info();
|
|
828
|
+
}
|
|
829
|
+
else {
|
|
830
|
+
const engine = await initEngineWasm({
|
|
831
|
+
...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
|
|
832
|
+
...(options.threads === undefined ? {} : { threads: options.threads }),
|
|
833
|
+
});
|
|
834
|
+
const createHasher = () => new engine.bindings.Sha256Hasher();
|
|
835
|
+
opened = await this.#openSource(active, request.source, options.cacheDir, progress, createHasher);
|
|
836
|
+
const decoder = request.decoder === undefined
|
|
837
|
+
? undefined
|
|
838
|
+
: await this.#openSource(active, request.decoder, options.cacheDir, progress, createHasher, "decoder");
|
|
839
|
+
const { source } = this.#jsSource(opened, active, progress, engine.bindings);
|
|
840
|
+
const decoderSource = decoder === undefined ? undefined : this.#jsSource(decoder, active, () => { }, engine.bindings).source;
|
|
841
|
+
const model = await engine.bindings.WasmImageModel.load(source, loadOptions, decoderSource);
|
|
842
|
+
handle = { runtime: "wasm", model };
|
|
843
|
+
raw = model.info();
|
|
844
|
+
}
|
|
845
|
+
if (signal.aborted) {
|
|
846
|
+
handle.model.free();
|
|
847
|
+
throw abortError(signal);
|
|
848
|
+
}
|
|
849
|
+
const info = imageModelInfo(raw, handle.runtime, opened, native.note, now() - started);
|
|
850
|
+
const id = this.#nextModel++;
|
|
851
|
+
this.#imageModels.set(id, { handle, queue: Promise.resolve() });
|
|
852
|
+
progress({ phase: "ready", loadedBytes: 0, totalBytes: 0, overallLoadedBytes: 0, overallTotalBytes: 0 });
|
|
853
|
+
return { model: id, info };
|
|
854
|
+
}
|
|
855
|
+
/** Generates an image, after the model's earlier generations. */
|
|
856
|
+
async #generateImage(request, signal) {
|
|
857
|
+
const model = this.#imageModels.get(request.model);
|
|
858
|
+
if (model === undefined)
|
|
859
|
+
throw new WebslmError("DISPOSED", "this image model was unloaded");
|
|
860
|
+
const run = async () => {
|
|
861
|
+
if (signal.aborted)
|
|
862
|
+
throw abortError(signal);
|
|
863
|
+
const started = now();
|
|
864
|
+
const options = JSON.stringify(request.options);
|
|
865
|
+
// The native engine's progress events and its result come through
|
|
866
|
+
// different queues: a successful result waits for all of them
|
|
867
|
+
// (encoding, one per step, decoding).
|
|
868
|
+
let received = 0;
|
|
869
|
+
const expected = (request.options.steps ?? 1) + 2;
|
|
870
|
+
let allReceived = () => { };
|
|
871
|
+
const done = new Promise((resolve) => {
|
|
872
|
+
allReceived = resolve;
|
|
873
|
+
});
|
|
874
|
+
const onProgress = (phase, step, steps) => {
|
|
875
|
+
received += 1;
|
|
876
|
+
if (received >= expected)
|
|
877
|
+
allReceived();
|
|
878
|
+
this.#host.post({
|
|
879
|
+
type: "imageProgress",
|
|
880
|
+
id: request.id,
|
|
881
|
+
phase: phase,
|
|
882
|
+
step,
|
|
883
|
+
steps,
|
|
884
|
+
});
|
|
885
|
+
return !signal.aborted;
|
|
886
|
+
};
|
|
887
|
+
const { handle } = model;
|
|
888
|
+
let image;
|
|
889
|
+
if (handle.runtime === "native") {
|
|
890
|
+
const cancel = new handle.addon.CancelToken();
|
|
891
|
+
const onAbort = () => cancel.cancel();
|
|
892
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
893
|
+
try {
|
|
894
|
+
image = await handle.model.generate(request.prompt, options, onProgress, cancel);
|
|
895
|
+
if (received < expected)
|
|
896
|
+
await done;
|
|
897
|
+
}
|
|
898
|
+
finally {
|
|
899
|
+
signal.removeEventListener("abort", onAbort);
|
|
900
|
+
}
|
|
901
|
+
// Node-API memory cannot be transferred to another thread.
|
|
902
|
+
image = { ...image, rgba: image.rgba.slice() };
|
|
903
|
+
}
|
|
904
|
+
else {
|
|
905
|
+
image = (await handle.model.generate(request.prompt, options, onProgress));
|
|
906
|
+
}
|
|
907
|
+
return { ...image, timeMs: now() - started };
|
|
908
|
+
};
|
|
909
|
+
const next = model.queue.then(run);
|
|
910
|
+
model.queue = next.catch(() => { });
|
|
911
|
+
return next;
|
|
912
|
+
}
|
|
760
913
|
#remoteRead(requestId, path, start, end, target) {
|
|
761
914
|
const readId = this.#nextRead++;
|
|
762
915
|
return new Promise((resolve, reject) => {
|
|
@@ -773,6 +926,34 @@ export class Engine {
|
|
|
773
926
|
});
|
|
774
927
|
}
|
|
775
928
|
}
|
|
929
|
+
/** What `loadImage` reports, from what the engine describes. */
|
|
930
|
+
function imageModelInfo(raw, runtime, opened, runtimeNote, loadTimeMs) {
|
|
931
|
+
const str = (key) => (typeof raw[key] === "string" ? raw[key] : undefined);
|
|
932
|
+
const device = str("device") === "cpu" ? "cpu" : runtime === "native" ? "gpu" : "webgpu";
|
|
933
|
+
const adapter = str("adapter");
|
|
934
|
+
const deviceNote = str("deviceNote");
|
|
935
|
+
const backend = runtime === "native"
|
|
936
|
+
? (adapter ?? device)
|
|
937
|
+
: device === "cpu"
|
|
938
|
+
? "WebAssembly CPU"
|
|
939
|
+
: `WebGPU${adapter === undefined ? "" : ` (${adapter})`}`;
|
|
940
|
+
return {
|
|
941
|
+
pipeline: str("pipeline") ?? "",
|
|
942
|
+
decoder: str("decoder") === "kl" ? "kl" : "tiny",
|
|
943
|
+
scheduler: str("scheduler") ?? "",
|
|
944
|
+
sizeMultiple: typeof raw["sizeMultiple"] === "number" ? raw["sizeMultiple"] : 8,
|
|
945
|
+
device,
|
|
946
|
+
backend,
|
|
947
|
+
runtime,
|
|
948
|
+
quant: str("weightFormat") ?? "f16",
|
|
949
|
+
...(opened.repo === undefined ? {} : { repo: opened.repo }),
|
|
950
|
+
...(opened.revision === undefined ? {} : { revision: opened.revision }),
|
|
951
|
+
...(deviceNote === undefined ? {} : { deviceNote }),
|
|
952
|
+
...(runtimeNote === undefined ? {} : { runtimeNote }),
|
|
953
|
+
fromCache: opened.fromCache,
|
|
954
|
+
loadTimeMs,
|
|
955
|
+
};
|
|
956
|
+
}
|
|
776
957
|
/** `lora` with the hub repository and revision it came from, when known. */
|
|
777
958
|
function withOrigin(lora, source) {
|
|
778
959
|
return {
|
package/dist/errors.d.ts
CHANGED
|
@@ -11,6 +11,11 @@ export type WebslmErrorCode =
|
|
|
11
11
|
| "NETWORK"
|
|
12
12
|
/** The checkpoint's architecture (or format) is not supported by this build. */
|
|
13
13
|
| "UNSUPPORTED_MODEL"
|
|
14
|
+
/**
|
|
15
|
+
* The model cannot do what was asked: generating text with an embedding model (an encoder),
|
|
16
|
+
* or `embed` on a language model.
|
|
17
|
+
*/
|
|
18
|
+
| "UNSUPPORTED_TASK"
|
|
14
19
|
/** The requested device is not available. */
|
|
15
20
|
| "UNSUPPORTED_DEVICE"
|
|
16
21
|
/** Malformed checkpoint files (config, safetensors header, tokenizer...). */
|
package/dist/errors.js
CHANGED
package/dist/hub.d.ts
CHANGED
|
@@ -12,6 +12,11 @@ export declare const DEFAULT_HUB_URL = "https://huggingface.co";
|
|
|
12
12
|
* runs. Kept in sync with the engine's `supportedModelTypes()` by a test.
|
|
13
13
|
*/
|
|
14
14
|
export declare const SUPPORTED_MODEL_TYPES: readonly string[];
|
|
15
|
+
/**
|
|
16
|
+
* `model_type` values of the encoders the engine embeds with (BERT and
|
|
17
|
+
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
18
|
+
*/
|
|
19
|
+
export declare const ENCODER_MODEL_TYPES: readonly string[];
|
|
15
20
|
/** Files read besides the weights, when the repository has them. */
|
|
16
21
|
export declare const CHECKPOINT_SIDE_FILES: readonly string[];
|
|
17
22
|
export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
@@ -38,6 +43,22 @@ export declare const ADAPTER_WEIGHTS = "adapter_model.safetensors";
|
|
|
38
43
|
* `adapter_config.json` and `adapter_model.safetensors`, no `config.json`.
|
|
39
44
|
*/
|
|
40
45
|
export declare function isAdapterListing(names: readonly string[]): boolean;
|
|
46
|
+
/** The pipeline description at the root of a `diffusers` repository. */
|
|
47
|
+
export declare const MODEL_INDEX = "model_index.json";
|
|
48
|
+
/** Whether a repository file list is a `diffusers` text-to-image pipeline. */
|
|
49
|
+
export declare function isImagePipelineListing(names: readonly string[]): boolean;
|
|
50
|
+
/**
|
|
51
|
+
* The files of a `diffusers` pipeline or standalone component to download
|
|
52
|
+
* (`diffusion::needed_files` in Rust): a pipeline needs its metadata and
|
|
53
|
+
* one weight file per component, preferring half precision; a standalone
|
|
54
|
+
* autoencoder (`madebyollin/taesd`: a `config.json`, no tokenizer, and
|
|
55
|
+
* `diffusion_pytorch_model.safetensors`) its config and weights. `undefined`
|
|
56
|
+
* for other repositories; `weights` is empty when a component has none.
|
|
57
|
+
*/
|
|
58
|
+
export declare function selectDiffusionFiles(names: readonly string[]): {
|
|
59
|
+
side: string[];
|
|
60
|
+
weights: string[];
|
|
61
|
+
} | undefined;
|
|
41
62
|
/** Options shared by the Hub helpers. */
|
|
42
63
|
export interface HubOptions {
|
|
43
64
|
/** Hub endpoint (mirrors, self-hosting). Defaults to `https://huggingface.co`. */
|
|
@@ -90,7 +111,8 @@ export declare function fetchRevision(repo: string, revision: string, options?:
|
|
|
90
111
|
* weights (the shards named by the index, `model.safetensors`, or every
|
|
91
112
|
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
92
113
|
* With `gguf`, or for a repository without safetensors weights, the weights
|
|
93
|
-
* are one GGUF file ({@link pickGgufFile}).
|
|
114
|
+
* are one GGUF file ({@link pickGgufFile}). A text-to-image pipeline gets
|
|
115
|
+
* the files {@link selectDiffusionFiles} picks.
|
|
94
116
|
*/
|
|
95
117
|
export declare function selectCheckpointFiles(names: readonly string[], index?: {
|
|
96
118
|
weight_map?: Record<string, string>;
|
|
@@ -124,6 +146,11 @@ export interface HubModel {
|
|
|
124
146
|
readonly supported: boolean;
|
|
125
147
|
/** Whether it runs from its GGUF files (their architecture is supported). */
|
|
126
148
|
readonly gguf?: boolean;
|
|
149
|
+
/**
|
|
150
|
+
* Whether it is an embedding model: supported when it is one of
|
|
151
|
+
* {@link ENCODER_MODEL_TYPES} (load it and call `embed`), refused otherwise.
|
|
152
|
+
*/
|
|
153
|
+
readonly embedding?: boolean;
|
|
127
154
|
/** Why it is not supported. */
|
|
128
155
|
readonly reason?: string;
|
|
129
156
|
readonly downloads?: number;
|
|
@@ -137,8 +164,11 @@ export interface SearchModelsOptions extends HubOptions {
|
|
|
137
164
|
/** Drop unsupported repositories from the result (default `false`). */
|
|
138
165
|
readonly supportedOnly?: boolean;
|
|
139
166
|
}
|
|
140
|
-
/**
|
|
141
|
-
|
|
167
|
+
/**
|
|
168
|
+
* Why an embedding, reranker or classifier checkpoint of an architecture
|
|
169
|
+
* other than the supported encoders is refused.
|
|
170
|
+
*/
|
|
171
|
+
export declare const EMBEDDING_REASON = "embedding model of an unsupported architecture (webslm embeds with BERT, ModernBERT and model2vec)";
|
|
142
172
|
/**
|
|
143
173
|
* Whether a repository holds an embedding, reranker or classification model
|
|
144
174
|
* rather than one for text generation, even when its architecture is a
|
|
@@ -186,6 +216,11 @@ export interface ModelCheck {
|
|
|
186
216
|
readonly supported: boolean;
|
|
187
217
|
/** Everything that prevents loading (empty when supported). */
|
|
188
218
|
readonly reasons: readonly string[];
|
|
219
|
+
/**
|
|
220
|
+
* Whether it is an embedding model: supported when its `model_type` is
|
|
221
|
+
* one of {@link ENCODER_MODEL_TYPES} (load it and call `embed`).
|
|
222
|
+
*/
|
|
223
|
+
readonly embedding?: boolean;
|
|
189
224
|
readonly modelType?: string;
|
|
190
225
|
readonly gated: false | "auto" | "manual";
|
|
191
226
|
readonly hasTokenizer: boolean;
|