webslm 0.7.0 → 0.10.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 +116 -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 +54 -0
- package/dist/ai-sdk/index.js +85 -11
- package/dist/ai-sdk/transcription-model.d.ts +48 -0
- package/dist/ai-sdk/transcription-model.js +115 -0
- package/dist/audio.d.ts +33 -0
- package/dist/audio.js +87 -0
- package/dist/client.d.ts +6 -0
- package/dist/client.js +8 -1
- package/dist/download.js +2 -2
- package/dist/engine.js +233 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +1 -0
- package/dist/hub.d.ts +47 -3
- package/dist/hub.js +97 -8
- package/dist/image.d.ts +201 -0
- package/dist/image.js +353 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +5 -2
- package/dist/models.d.ts +37 -1
- package/dist/models.js +99 -6
- package/dist/native.d.ts +34 -0
- package/dist/protocol.d.ts +106 -2
- package/dist/simple.d.ts +4 -1
- package/dist/simple.js +9 -2
- package/dist/types.d.ts +107 -1
- package/dist/wasm.d.ts +4 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +97 -6
- package/wasm/relaxed/webslm_wasm.js +223 -18
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +13 -3
- package/wasm/simd/webslm_wasm.d.ts +97 -6
- package/wasm/simd/webslm_wasm.js +223 -18
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +13 -3
- package/wasm/threads/webslm_wasm.d.ts +98 -7
- package/wasm/threads/webslm_wasm.js +228 -23
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +14 -4
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,29 @@ 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
|
+
}
|
|
237
|
+
case "transcribe":
|
|
238
|
+
return [await this.#transcribe(request, signal)];
|
|
222
239
|
case "unload": {
|
|
240
|
+
const image = this.#imageModels.get(request.model);
|
|
241
|
+
if (image !== undefined) {
|
|
242
|
+
image.handle.model.free();
|
|
243
|
+
this.#imageModels.delete(request.model);
|
|
244
|
+
return [true];
|
|
245
|
+
}
|
|
223
246
|
const model = this.#models.get(request.model);
|
|
224
247
|
if (model !== undefined) {
|
|
225
248
|
for (const session of model.sessions.values())
|
|
@@ -283,6 +306,56 @@ export class Engine {
|
|
|
283
306
|
: target.generate(request.prompt, options, onDelta, onPrefill)));
|
|
284
307
|
return withTimings(summary, started, first, last);
|
|
285
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Transcribes speech: pieces of text stream as `delta` messages (`token`
|
|
311
|
+
* -1), and the signal stops the transcription before its next token.
|
|
312
|
+
*/
|
|
313
|
+
async #transcribe(request, signal) {
|
|
314
|
+
const { handle } = this.#model(request.model);
|
|
315
|
+
const options = JSON.stringify(request.options);
|
|
316
|
+
const post = (text) => this.#host.post({ type: "delta", id: request.id, text, token: -1 });
|
|
317
|
+
if (handle.runtime === "wasm") {
|
|
318
|
+
const onText = async (text) => {
|
|
319
|
+
post(text);
|
|
320
|
+
// Let `abort` messages in before the next token.
|
|
321
|
+
await yieldToEventLoop();
|
|
322
|
+
return !signal.aborted;
|
|
323
|
+
};
|
|
324
|
+
return (await handle.model.transcribe(request.audio, options, onText));
|
|
325
|
+
}
|
|
326
|
+
if (handle.model.transcribe === undefined) {
|
|
327
|
+
throw new WebslmError("UNSUPPORTED_TASK", "this build of the native engine cannot transcribe");
|
|
328
|
+
}
|
|
329
|
+
const cancel = new handle.addon.CancelToken();
|
|
330
|
+
const onAbort = () => cancel.cancel();
|
|
331
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
332
|
+
if (signal.aborted)
|
|
333
|
+
cancel.cancel();
|
|
334
|
+
// The result and the text come through different queues: wait for
|
|
335
|
+
// every piece the result counts.
|
|
336
|
+
let received = 0;
|
|
337
|
+
let expected = Number.POSITIVE_INFINITY;
|
|
338
|
+
let allReceived = () => { };
|
|
339
|
+
const done = new Promise((resolve) => {
|
|
340
|
+
allReceived = resolve;
|
|
341
|
+
});
|
|
342
|
+
const onText = (text) => {
|
|
343
|
+
post(text);
|
|
344
|
+
received += 1;
|
|
345
|
+
if (received >= expected)
|
|
346
|
+
allReceived();
|
|
347
|
+
};
|
|
348
|
+
try {
|
|
349
|
+
const { pieces, ...result } = (await handle.model.transcribe(request.audio, options, onText, cancel));
|
|
350
|
+
expected = pieces;
|
|
351
|
+
if (received < expected)
|
|
352
|
+
await done;
|
|
353
|
+
return result;
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
signal.removeEventListener("abort", onAbort);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
286
359
|
/**
|
|
287
360
|
* A generation on the native engine: tokens arrive from the model's thread
|
|
288
361
|
* through a threadsafe function, and the signal cancels the call (before
|
|
@@ -547,6 +620,7 @@ export class Engine {
|
|
|
547
620
|
wasm = await WasmModel.load(jsSource, JSON.stringify({
|
|
548
621
|
// `auto` on a GGUF file: the engine keeps the file's own format.
|
|
549
622
|
...(options.quant === "auto" ? {} : { format: options.quant }),
|
|
623
|
+
...(options.defaultQuant === true || options.autoQuant === true ? { defaultFormat: true } : {}),
|
|
550
624
|
...(gguf === undefined ? {} : { ggufFile: gguf }),
|
|
551
625
|
device: options.device ?? "auto",
|
|
552
626
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
@@ -664,6 +738,7 @@ export class Engine {
|
|
|
664
738
|
try {
|
|
665
739
|
model = await addon.NativeModel.load(dir, JSON.stringify({
|
|
666
740
|
format: options.autoQuant === true ? "auto" : options.quant,
|
|
741
|
+
...(options.defaultQuant === true ? { defaultFormat: true } : {}),
|
|
667
742
|
device: options.device ?? "auto",
|
|
668
743
|
...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
|
|
669
744
|
...(options.kvCache === undefined ? {} : { kvCache: options.kvCache }),
|
|
@@ -757,6 +832,136 @@ export class Engine {
|
|
|
757
832
|
return removed === null ? null : (lora ?? removed);
|
|
758
833
|
});
|
|
759
834
|
}
|
|
835
|
+
/**
|
|
836
|
+
* Loads a text-to-image pipeline (and a standalone decoder): on the
|
|
837
|
+
* native engine from the snapshot directories the download wrote, else
|
|
838
|
+
* on the WebAssembly engine. Image models are compute-bound: `auto` takes
|
|
839
|
+
* the GPU whenever there is one.
|
|
840
|
+
*/
|
|
841
|
+
async #loadImage(request, signal) {
|
|
842
|
+
const started = now();
|
|
843
|
+
const { options } = request;
|
|
844
|
+
const active = { id: request.id, signal };
|
|
845
|
+
const progress = (p) => this.#host.post({ type: "progress", id: active.id, progress: p });
|
|
846
|
+
let native = await chooseNative(options.backend ?? "auto", request.source, options.wasmFlavour, options.cacheDir);
|
|
847
|
+
if (native.addon !== undefined && request.decoder !== undefined && request.decoder.kind !== "hub") {
|
|
848
|
+
if (options.backend === "native") {
|
|
849
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", 'backend "native": the native engine loads hub decoders only');
|
|
850
|
+
}
|
|
851
|
+
native = { note: "auto: WebAssembly (the native engine loads hub decoders only)" };
|
|
852
|
+
}
|
|
853
|
+
if (native.addon !== undefined && native.addon.NativeImageModel === undefined) {
|
|
854
|
+
if (options.backend === "native") {
|
|
855
|
+
throw new WebslmError("UNSUPPORTED_DEVICE", 'backend "native": this native engine has no image models');
|
|
856
|
+
}
|
|
857
|
+
native = { note: "auto: WebAssembly (this native engine has no image models)" };
|
|
858
|
+
}
|
|
859
|
+
let handle;
|
|
860
|
+
let raw;
|
|
861
|
+
let opened;
|
|
862
|
+
const loadOptions = JSON.stringify({ format: options.quant, device: options.device ?? "auto" });
|
|
863
|
+
if (native.addon?.NativeImageModel !== undefined) {
|
|
864
|
+
const createHasher = await nodeSha256();
|
|
865
|
+
opened = await this.#openSource(active, request.source, options.cacheDir, progress, createHasher);
|
|
866
|
+
const decoder = request.decoder === undefined
|
|
867
|
+
? undefined
|
|
868
|
+
: await this.#openSource(active, request.decoder, options.cacheDir, progress, createHasher, "decoder");
|
|
869
|
+
const dir = await snapshotDirectory(opened);
|
|
870
|
+
const decoderDir = decoder === undefined ? undefined : await snapshotDirectory(decoder);
|
|
871
|
+
if (dir === undefined || (decoder !== undefined && decoderDir === undefined)) {
|
|
872
|
+
throw new WebslmError("ENGINE", "the native engine needs the model in the cache directory");
|
|
873
|
+
}
|
|
874
|
+
const model = await native.addon.NativeImageModel.load(dir, loadOptions, {
|
|
875
|
+
...(decoderDir === undefined ? {} : { decoderDir }),
|
|
876
|
+
...(options.threads === undefined ? {} : { threads: options.threads }),
|
|
877
|
+
});
|
|
878
|
+
handle = { runtime: "native", model, addon: native.addon };
|
|
879
|
+
raw = model.info();
|
|
880
|
+
}
|
|
881
|
+
else {
|
|
882
|
+
const engine = await initEngineWasm({
|
|
883
|
+
...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
|
|
884
|
+
...(options.threads === undefined ? {} : { threads: options.threads }),
|
|
885
|
+
});
|
|
886
|
+
const createHasher = () => new engine.bindings.Sha256Hasher();
|
|
887
|
+
opened = await this.#openSource(active, request.source, options.cacheDir, progress, createHasher);
|
|
888
|
+
const decoder = request.decoder === undefined
|
|
889
|
+
? undefined
|
|
890
|
+
: await this.#openSource(active, request.decoder, options.cacheDir, progress, createHasher, "decoder");
|
|
891
|
+
const { source } = this.#jsSource(opened, active, progress, engine.bindings);
|
|
892
|
+
const decoderSource = decoder === undefined ? undefined : this.#jsSource(decoder, active, () => { }, engine.bindings).source;
|
|
893
|
+
const model = await engine.bindings.WasmImageModel.load(source, loadOptions, decoderSource);
|
|
894
|
+
handle = { runtime: "wasm", model };
|
|
895
|
+
raw = model.info();
|
|
896
|
+
}
|
|
897
|
+
if (signal.aborted) {
|
|
898
|
+
handle.model.free();
|
|
899
|
+
throw abortError(signal);
|
|
900
|
+
}
|
|
901
|
+
const info = imageModelInfo(raw, handle.runtime, opened, native.note, now() - started);
|
|
902
|
+
const id = this.#nextModel++;
|
|
903
|
+
this.#imageModels.set(id, { handle, queue: Promise.resolve() });
|
|
904
|
+
progress({ phase: "ready", loadedBytes: 0, totalBytes: 0, overallLoadedBytes: 0, overallTotalBytes: 0 });
|
|
905
|
+
return { model: id, info };
|
|
906
|
+
}
|
|
907
|
+
/** Generates an image, after the model's earlier generations. */
|
|
908
|
+
async #generateImage(request, signal) {
|
|
909
|
+
const model = this.#imageModels.get(request.model);
|
|
910
|
+
if (model === undefined)
|
|
911
|
+
throw new WebslmError("DISPOSED", "this image model was unloaded");
|
|
912
|
+
const run = async () => {
|
|
913
|
+
if (signal.aborted)
|
|
914
|
+
throw abortError(signal);
|
|
915
|
+
const started = now();
|
|
916
|
+
const options = JSON.stringify(request.options);
|
|
917
|
+
// The native engine's progress events and its result come through
|
|
918
|
+
// different queues: a successful result waits for all of them
|
|
919
|
+
// (encoding, one per step, decoding).
|
|
920
|
+
let received = 0;
|
|
921
|
+
const expected = (request.options.steps ?? 1) + 2;
|
|
922
|
+
let allReceived = () => { };
|
|
923
|
+
const done = new Promise((resolve) => {
|
|
924
|
+
allReceived = resolve;
|
|
925
|
+
});
|
|
926
|
+
const onProgress = (phase, step, steps) => {
|
|
927
|
+
received += 1;
|
|
928
|
+
if (received >= expected)
|
|
929
|
+
allReceived();
|
|
930
|
+
this.#host.post({
|
|
931
|
+
type: "imageProgress",
|
|
932
|
+
id: request.id,
|
|
933
|
+
phase: phase,
|
|
934
|
+
step,
|
|
935
|
+
steps,
|
|
936
|
+
});
|
|
937
|
+
return !signal.aborted;
|
|
938
|
+
};
|
|
939
|
+
const { handle } = model;
|
|
940
|
+
let image;
|
|
941
|
+
if (handle.runtime === "native") {
|
|
942
|
+
const cancel = new handle.addon.CancelToken();
|
|
943
|
+
const onAbort = () => cancel.cancel();
|
|
944
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
945
|
+
try {
|
|
946
|
+
image = await handle.model.generate(request.prompt, options, onProgress, cancel);
|
|
947
|
+
if (received < expected)
|
|
948
|
+
await done;
|
|
949
|
+
}
|
|
950
|
+
finally {
|
|
951
|
+
signal.removeEventListener("abort", onAbort);
|
|
952
|
+
}
|
|
953
|
+
// Node-API memory cannot be transferred to another thread.
|
|
954
|
+
image = { ...image, rgba: image.rgba.slice() };
|
|
955
|
+
}
|
|
956
|
+
else {
|
|
957
|
+
image = (await handle.model.generate(request.prompt, options, onProgress));
|
|
958
|
+
}
|
|
959
|
+
return { ...image, timeMs: now() - started };
|
|
960
|
+
};
|
|
961
|
+
const next = model.queue.then(run);
|
|
962
|
+
model.queue = next.catch(() => { });
|
|
963
|
+
return next;
|
|
964
|
+
}
|
|
760
965
|
#remoteRead(requestId, path, start, end, target) {
|
|
761
966
|
const readId = this.#nextRead++;
|
|
762
967
|
return new Promise((resolve, reject) => {
|
|
@@ -773,6 +978,34 @@ export class Engine {
|
|
|
773
978
|
});
|
|
774
979
|
}
|
|
775
980
|
}
|
|
981
|
+
/** What `loadImage` reports, from what the engine describes. */
|
|
982
|
+
function imageModelInfo(raw, runtime, opened, runtimeNote, loadTimeMs) {
|
|
983
|
+
const str = (key) => (typeof raw[key] === "string" ? raw[key] : undefined);
|
|
984
|
+
const device = str("device") === "cpu" ? "cpu" : runtime === "native" ? "gpu" : "webgpu";
|
|
985
|
+
const adapter = str("adapter");
|
|
986
|
+
const deviceNote = str("deviceNote");
|
|
987
|
+
const backend = runtime === "native"
|
|
988
|
+
? (adapter ?? device)
|
|
989
|
+
: device === "cpu"
|
|
990
|
+
? "WebAssembly CPU"
|
|
991
|
+
: `WebGPU${adapter === undefined ? "" : ` (${adapter})`}`;
|
|
992
|
+
return {
|
|
993
|
+
pipeline: str("pipeline") ?? "",
|
|
994
|
+
decoder: str("decoder") === "kl" ? "kl" : "tiny",
|
|
995
|
+
scheduler: str("scheduler") ?? "",
|
|
996
|
+
sizeMultiple: typeof raw["sizeMultiple"] === "number" ? raw["sizeMultiple"] : 8,
|
|
997
|
+
device,
|
|
998
|
+
backend,
|
|
999
|
+
runtime,
|
|
1000
|
+
quant: str("weightFormat") ?? "f16",
|
|
1001
|
+
...(opened.repo === undefined ? {} : { repo: opened.repo }),
|
|
1002
|
+
...(opened.revision === undefined ? {} : { revision: opened.revision }),
|
|
1003
|
+
...(deviceNote === undefined ? {} : { deviceNote }),
|
|
1004
|
+
...(runtimeNote === undefined ? {} : { runtimeNote }),
|
|
1005
|
+
fromCache: opened.fromCache,
|
|
1006
|
+
loadTimeMs,
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
776
1009
|
/** `lora` with the hub repository and revision it came from, when known. */
|
|
777
1010
|
function withOrigin(lora, source) {
|
|
778
1011
|
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,13 @@ 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[];
|
|
20
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
21
|
+
export declare const SPEECH_MODEL_TYPES: readonly string[];
|
|
15
22
|
/** Files read besides the weights, when the repository has them. */
|
|
16
23
|
export declare const CHECKPOINT_SIDE_FILES: readonly string[];
|
|
17
24
|
export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
@@ -38,6 +45,22 @@ export declare const ADAPTER_WEIGHTS = "adapter_model.safetensors";
|
|
|
38
45
|
* `adapter_config.json` and `adapter_model.safetensors`, no `config.json`.
|
|
39
46
|
*/
|
|
40
47
|
export declare function isAdapterListing(names: readonly string[]): boolean;
|
|
48
|
+
/** The pipeline description at the root of a `diffusers` repository. */
|
|
49
|
+
export declare const MODEL_INDEX = "model_index.json";
|
|
50
|
+
/** Whether a repository file list is a `diffusers` text-to-image pipeline. */
|
|
51
|
+
export declare function isImagePipelineListing(names: readonly string[]): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* The files of a `diffusers` pipeline or standalone component to download
|
|
54
|
+
* (`diffusion::needed_files` in Rust): a pipeline needs its metadata and
|
|
55
|
+
* one weight file per component, preferring half precision; a standalone
|
|
56
|
+
* autoencoder (`madebyollin/taesd`: a `config.json`, no tokenizer, and
|
|
57
|
+
* `diffusion_pytorch_model.safetensors`) its config and weights. `undefined`
|
|
58
|
+
* for other repositories; `weights` is empty when a component has none.
|
|
59
|
+
*/
|
|
60
|
+
export declare function selectDiffusionFiles(names: readonly string[]): {
|
|
61
|
+
side: string[];
|
|
62
|
+
weights: string[];
|
|
63
|
+
} | undefined;
|
|
41
64
|
/** Options shared by the Hub helpers. */
|
|
42
65
|
export interface HubOptions {
|
|
43
66
|
/** Hub endpoint (mirrors, self-hosting). Defaults to `https://huggingface.co`. */
|
|
@@ -90,7 +113,8 @@ export declare function fetchRevision(repo: string, revision: string, options?:
|
|
|
90
113
|
* weights (the shards named by the index, `model.safetensors`, or every
|
|
91
114
|
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
92
115
|
* With `gguf`, or for a repository without safetensors weights, the weights
|
|
93
|
-
* are one GGUF file ({@link pickGgufFile}).
|
|
116
|
+
* are one GGUF file ({@link pickGgufFile}). A text-to-image pipeline gets
|
|
117
|
+
* the files {@link selectDiffusionFiles} picks.
|
|
94
118
|
*/
|
|
95
119
|
export declare function selectCheckpointFiles(names: readonly string[], index?: {
|
|
96
120
|
weight_map?: Record<string, string>;
|
|
@@ -124,6 +148,16 @@ export interface HubModel {
|
|
|
124
148
|
readonly supported: boolean;
|
|
125
149
|
/** Whether it runs from its GGUF files (their architecture is supported). */
|
|
126
150
|
readonly gguf?: boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Whether it is an embedding model: supported when it is one of
|
|
153
|
+
* {@link ENCODER_MODEL_TYPES} (load it and call `embed`), refused otherwise.
|
|
154
|
+
*/
|
|
155
|
+
readonly embedding?: boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Whether it is a speech recognition model (one of
|
|
158
|
+
* {@link SPEECH_MODEL_TYPES}: load it and call `transcribe`).
|
|
159
|
+
*/
|
|
160
|
+
readonly speech?: boolean;
|
|
127
161
|
/** Why it is not supported. */
|
|
128
162
|
readonly reason?: string;
|
|
129
163
|
readonly downloads?: number;
|
|
@@ -137,8 +171,11 @@ export interface SearchModelsOptions extends HubOptions {
|
|
|
137
171
|
/** Drop unsupported repositories from the result (default `false`). */
|
|
138
172
|
readonly supportedOnly?: boolean;
|
|
139
173
|
}
|
|
140
|
-
/**
|
|
141
|
-
|
|
174
|
+
/**
|
|
175
|
+
* Why an embedding, reranker or classifier checkpoint of an architecture
|
|
176
|
+
* other than the supported encoders is refused.
|
|
177
|
+
*/
|
|
178
|
+
export declare const EMBEDDING_REASON = "embedding model of an unsupported architecture (webslm embeds with BERT, ModernBERT and model2vec)";
|
|
142
179
|
/**
|
|
143
180
|
* Whether a repository holds an embedding, reranker or classification model
|
|
144
181
|
* rather than one for text generation, even when its architecture is a
|
|
@@ -186,6 +223,13 @@ export interface ModelCheck {
|
|
|
186
223
|
readonly supported: boolean;
|
|
187
224
|
/** Everything that prevents loading (empty when supported). */
|
|
188
225
|
readonly reasons: readonly string[];
|
|
226
|
+
/**
|
|
227
|
+
* Whether it is an embedding model: supported when its `model_type` is
|
|
228
|
+
* one of {@link ENCODER_MODEL_TYPES} (load it and call `embed`).
|
|
229
|
+
*/
|
|
230
|
+
readonly embedding?: boolean;
|
|
231
|
+
/** Whether it is a speech recognition model (load it and call `transcribe`). */
|
|
232
|
+
readonly speech?: boolean;
|
|
189
233
|
readonly modelType?: string;
|
|
190
234
|
readonly gated: false | "auto" | "manual";
|
|
191
235
|
readonly hasTokenizer: boolean;
|
package/dist/hub.js
CHANGED
|
@@ -24,6 +24,13 @@ export const SUPPORTED_MODEL_TYPES = [
|
|
|
24
24
|
"smolvlm",
|
|
25
25
|
"lfm2_vl",
|
|
26
26
|
];
|
|
27
|
+
/**
|
|
28
|
+
* `model_type` values of the encoders the engine embeds with (BERT and
|
|
29
|
+
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
30
|
+
*/
|
|
31
|
+
export const ENCODER_MODEL_TYPES = ["bert", "modernbert", "model2vec"];
|
|
32
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
33
|
+
export const SPEECH_MODEL_TYPES = ["whisper"];
|
|
27
34
|
/** Files read besides the weights, when the repository has them. */
|
|
28
35
|
export const CHECKPOINT_SIDE_FILES = [
|
|
29
36
|
"config.json",
|
|
@@ -37,6 +44,12 @@ export const CHECKPOINT_SIDE_FILES = [
|
|
|
37
44
|
"preprocessor_config.json",
|
|
38
45
|
"processor_config.json",
|
|
39
46
|
"video_preprocessor_config.json",
|
|
47
|
+
// Encoders: the sentence-transformers pipeline (pooling, normalization,
|
|
48
|
+
// sequence length).
|
|
49
|
+
"modules.json",
|
|
50
|
+
"sentence_bert_config.json",
|
|
51
|
+
"config_sentence_transformers.json",
|
|
52
|
+
"1_Pooling/config.json",
|
|
40
53
|
];
|
|
41
54
|
export const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
42
55
|
export const SAFETENSORS_SINGLE = "model.safetensors";
|
|
@@ -85,6 +98,58 @@ export function isAdapterListing(names) {
|
|
|
85
98
|
const present = new Set(names);
|
|
86
99
|
return present.has(ADAPTER_CONFIG) && present.has(ADAPTER_WEIGHTS) && !present.has("config.json");
|
|
87
100
|
}
|
|
101
|
+
/** The pipeline description at the root of a `diffusers` repository. */
|
|
102
|
+
export const MODEL_INDEX = "model_index.json";
|
|
103
|
+
/** Components a text-to-image pipeline reads (one weight file each). */
|
|
104
|
+
const PIPELINE_COMPONENTS = ["text_encoder", "unet", "vae"];
|
|
105
|
+
/** Small files of a text-to-image pipeline (`diffusion::PIPELINE_METADATA_FILES` in Rust). */
|
|
106
|
+
const PIPELINE_METADATA_FILES = [
|
|
107
|
+
MODEL_INDEX,
|
|
108
|
+
"scheduler/scheduler_config.json",
|
|
109
|
+
"tokenizer/vocab.json",
|
|
110
|
+
"tokenizer/merges.txt",
|
|
111
|
+
"tokenizer/tokenizer_config.json",
|
|
112
|
+
"tokenizer/special_tokens_map.json",
|
|
113
|
+
"text_encoder/config.json",
|
|
114
|
+
"unet/config.json",
|
|
115
|
+
"vae/config.json",
|
|
116
|
+
];
|
|
117
|
+
/**
|
|
118
|
+
* Weight files of a pipeline component (`""` for a standalone component at
|
|
119
|
+
* the root, such as an autoencoder), the half-precision variant first.
|
|
120
|
+
*/
|
|
121
|
+
function componentWeightCandidates(component) {
|
|
122
|
+
const stem = component === "text_encoder" ? "model" : "diffusion_pytorch_model";
|
|
123
|
+
const prefix = component === "" ? "" : `${component}/`;
|
|
124
|
+
return [`${prefix}${stem}.fp16.safetensors`, `${prefix}${stem}.safetensors`];
|
|
125
|
+
}
|
|
126
|
+
/** Whether a repository file list is a `diffusers` text-to-image pipeline. */
|
|
127
|
+
export function isImagePipelineListing(names) {
|
|
128
|
+
return names.includes(MODEL_INDEX);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The files of a `diffusers` pipeline or standalone component to download
|
|
132
|
+
* (`diffusion::needed_files` in Rust): a pipeline needs its metadata and
|
|
133
|
+
* one weight file per component, preferring half precision; a standalone
|
|
134
|
+
* autoencoder (`madebyollin/taesd`: a `config.json`, no tokenizer, and
|
|
135
|
+
* `diffusion_pytorch_model.safetensors`) its config and weights. `undefined`
|
|
136
|
+
* for other repositories; `weights` is empty when a component has none.
|
|
137
|
+
*/
|
|
138
|
+
export function selectDiffusionFiles(names) {
|
|
139
|
+
const present = new Set(names);
|
|
140
|
+
const pick = (component) => componentWeightCandidates(component).find((f) => present.has(f));
|
|
141
|
+
if (present.has(MODEL_INDEX)) {
|
|
142
|
+
const side = PIPELINE_METADATA_FILES.filter((f) => present.has(f));
|
|
143
|
+
const weights = PIPELINE_COMPONENTS.map(pick);
|
|
144
|
+
return { side, weights: weights.every((w) => w !== undefined) ? weights : [] };
|
|
145
|
+
}
|
|
146
|
+
if (present.has("config.json") && !present.has("tokenizer.json")) {
|
|
147
|
+
const weights = pick("");
|
|
148
|
+
if (weights !== undefined)
|
|
149
|
+
return { side: ["config.json"], weights: [weights] };
|
|
150
|
+
}
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
88
153
|
/**
|
|
89
154
|
* The Hub endpoint: `hubUrl`, else `HF_ENDPOINT` from the environment (Node,
|
|
90
155
|
* Bun, Deno; a mirror or a local stand-in, as for the `webslm` command-line
|
|
@@ -197,13 +262,19 @@ function parseGated(value) {
|
|
|
197
262
|
* weights (the shards named by the index, `model.safetensors`, or every
|
|
198
263
|
* top-level `*.safetensors`). `index` is the parsed index when there is one.
|
|
199
264
|
* With `gguf`, or for a repository without safetensors weights, the weights
|
|
200
|
-
* are one GGUF file ({@link pickGgufFile}).
|
|
265
|
+
* are one GGUF file ({@link pickGgufFile}). A text-to-image pipeline gets
|
|
266
|
+
* the files {@link selectDiffusionFiles} picks.
|
|
201
267
|
*/
|
|
202
268
|
export function selectCheckpointFiles(names, index, gguf) {
|
|
203
269
|
// A LoRA adapter needs only its two files.
|
|
204
270
|
if (isAdapterListing(names))
|
|
205
271
|
return { side: [ADAPTER_CONFIG], weights: [ADAPTER_WEIGHTS] };
|
|
206
272
|
const present = new Set(names);
|
|
273
|
+
if (gguf === undefined) {
|
|
274
|
+
const diffusion = selectDiffusionFiles(names);
|
|
275
|
+
if (diffusion !== undefined)
|
|
276
|
+
return diffusion;
|
|
277
|
+
}
|
|
207
278
|
const side = CHECKPOINT_SIDE_FILES.filter((f) => present.has(f));
|
|
208
279
|
const hasSafetensors = present.has(SAFETENSORS_INDEX) || names.some((n) => !n.includes("/") && n.endsWith(".safetensors"));
|
|
209
280
|
const ggufFile = gguf ?? (hasSafetensors ? undefined : pickGgufFile(names));
|
|
@@ -218,8 +289,11 @@ export function selectCheckpointFiles(names, index, gguf) {
|
|
|
218
289
|
const weights = names.filter((n) => !n.includes("/") && n.endsWith(".safetensors")).sort();
|
|
219
290
|
return { side, weights };
|
|
220
291
|
}
|
|
221
|
-
/**
|
|
222
|
-
|
|
292
|
+
/**
|
|
293
|
+
* Why an embedding, reranker or classifier checkpoint of an architecture
|
|
294
|
+
* other than the supported encoders is refused.
|
|
295
|
+
*/
|
|
296
|
+
export const EMBEDDING_REASON = "embedding model of an unsupported architecture (webslm embeds with BERT, ModernBERT and model2vec)";
|
|
223
297
|
const ENCODER_PIPELINES = ["feature-extraction", "sentence-similarity", "text-ranking", "text-classification"];
|
|
224
298
|
/**
|
|
225
299
|
* Whether a repository holds an embedding, reranker or classification model
|
|
@@ -277,8 +351,11 @@ export function estimateMemory(params) {
|
|
|
277
351
|
export function unsupportedReason(modelType) {
|
|
278
352
|
if (modelType === undefined)
|
|
279
353
|
return "no config.json model_type published";
|
|
280
|
-
if (SUPPORTED_MODEL_TYPES.includes(modelType)
|
|
354
|
+
if (SUPPORTED_MODEL_TYPES.includes(modelType) ||
|
|
355
|
+
ENCODER_MODEL_TYPES.includes(modelType) ||
|
|
356
|
+
SPEECH_MODEL_TYPES.includes(modelType)) {
|
|
281
357
|
return undefined;
|
|
358
|
+
}
|
|
282
359
|
return `architecture "${modelType}" is not supported yet`;
|
|
283
360
|
}
|
|
284
361
|
/**
|
|
@@ -335,7 +412,8 @@ function toHubModel(entry, maxParams) {
|
|
|
335
412
|
const ggufType = ggufArchitecture === undefined ? undefined : GGUF_ARCHITECTURES[ggufArchitecture];
|
|
336
413
|
const ggufTotal = entry.gguf?.total;
|
|
337
414
|
const params = typeof total === "number" ? total : typeof ggufTotal === "number" && ggufType !== undefined ? ggufTotal : undefined;
|
|
338
|
-
const
|
|
415
|
+
const encoder = modelType !== undefined && ENCODER_MODEL_TYPES.includes(modelType);
|
|
416
|
+
const embedding = encoder || isEmbeddingModel({
|
|
339
417
|
repo: entry.id,
|
|
340
418
|
pipelineTag: typeof entry.pipeline_tag === "string" ? entry.pipeline_tag : undefined,
|
|
341
419
|
libraryName: typeof entry.library_name === "string" ? entry.library_name : undefined,
|
|
@@ -343,7 +421,7 @@ function toHubModel(entry, maxParams) {
|
|
|
343
421
|
});
|
|
344
422
|
// GGUF files of a supported architecture run whatever else the repository holds.
|
|
345
423
|
const gguf = ggufType !== undefined && SUPPORTED_MODEL_TYPES.includes(ggufType);
|
|
346
|
-
let reason = embedding ? EMBEDDING_REASON : gguf ? undefined : unsupportedReason(modelType);
|
|
424
|
+
let reason = embedding && !encoder ? EMBEDDING_REASON : gguf ? undefined : unsupportedReason(modelType);
|
|
347
425
|
if (reason === undefined && params === undefined)
|
|
348
426
|
reason = "no safetensors weights";
|
|
349
427
|
if (reason === undefined && !gguf)
|
|
@@ -362,6 +440,10 @@ function toHubModel(entry, maxParams) {
|
|
|
362
440
|
model.modelType = ggufType;
|
|
363
441
|
if (gguf)
|
|
364
442
|
model.gguf = true;
|
|
443
|
+
if (embedding)
|
|
444
|
+
model.embedding = true;
|
|
445
|
+
if (modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType))
|
|
446
|
+
model.speech = true;
|
|
365
447
|
if (architectures !== undefined)
|
|
366
448
|
model.architectures = architectures;
|
|
367
449
|
if (params !== undefined) {
|
|
@@ -437,7 +519,9 @@ export async function checkModel(repo, options = {}) {
|
|
|
437
519
|
else {
|
|
438
520
|
reasons.push("no config.json");
|
|
439
521
|
}
|
|
440
|
-
|
|
522
|
+
const encoder = modelType !== undefined && ENCODER_MODEL_TYPES.includes(modelType);
|
|
523
|
+
const embedding = encoder || isEmbeddingModel({ repo, files: names });
|
|
524
|
+
if (embedding && !encoder)
|
|
441
525
|
reasons.unshift(EMBEDDING_REASON);
|
|
442
526
|
const hasTokenizer = names.includes("tokenizer.json");
|
|
443
527
|
if (!hasTokenizer)
|
|
@@ -469,7 +553,8 @@ export async function checkModel(repo, options = {}) {
|
|
|
469
553
|
hasEmbeddings = true;
|
|
470
554
|
}
|
|
471
555
|
}
|
|
472
|
-
|
|
556
|
+
const speech = modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType);
|
|
557
|
+
if (selected.weights.length > 0 && !hasEmbeddings && !encoder && !speech) {
|
|
473
558
|
reasons.push("unexpected weight layout (no model.embed_tokens.weight)");
|
|
474
559
|
}
|
|
475
560
|
const packed = packedWeightsReason(dtypes);
|
|
@@ -495,6 +580,10 @@ export async function checkModel(repo, options = {}) {
|
|
|
495
580
|
};
|
|
496
581
|
if (modelType !== undefined)
|
|
497
582
|
check.modelType = modelType;
|
|
583
|
+
if (embedding)
|
|
584
|
+
check.embedding = true;
|
|
585
|
+
if (speech)
|
|
586
|
+
check.speech = true;
|
|
498
587
|
if (config !== undefined) {
|
|
499
588
|
check.config = config;
|
|
500
589
|
if (shapes.length > 0) {
|