webslm 0.3.0 → 0.4.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 +71 -15
- package/dist/ai-sdk/index.d.ts +1 -1
- package/dist/ai-sdk/index.js +1 -1
- package/dist/cache/models.d.ts +6 -0
- package/dist/cache/models.js +11 -0
- package/dist/curated.d.ts +31 -1
- package/dist/curated.js +49 -5
- package/dist/engine.d.ts +33 -4
- package/dist/engine.js +451 -43
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/models.d.ts +30 -9
- package/dist/models.js +72 -10
- package/dist/native.d.ts +165 -0
- package/dist/native.js +243 -0
- package/dist/protocol.d.ts +14 -3
- package/dist/recommended-sampling.d.ts +54 -0
- package/dist/recommended-sampling.js +73 -0
- package/dist/simple.d.ts +20 -6
- package/dist/simple.js +33 -7
- package/dist/types.d.ts +106 -20
- package/native-manifest.json +47 -0
- package/package.json +2 -1
- package/wasm/relaxed/webslm_wasm.d.ts +34 -9
- package/wasm/relaxed/webslm_wasm.js +78 -22
- 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 +34 -9
- package/wasm/simd/webslm_wasm.js +78 -22
- 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 +34 -9
- package/wasm/threads/webslm_wasm.js +83 -27
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +5 -3
package/dist/native.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The native engine in Node: a Node-API addon built from the same Rust
|
|
3
|
+
* engine (`crates/webslm-node`). Each release attaches it to its GitHub
|
|
4
|
+
* Release for every platform (`webslm-node-<version>-<platform>.node.gz`),
|
|
5
|
+
* and the published package carries their SHA-256 (`native-manifest.json`).
|
|
6
|
+
* On first use the addon of this platform is downloaded into the cache
|
|
7
|
+
* directory, checked against the manifest and loaded; later runs load it
|
|
8
|
+
* from the cache, without network. When it cannot be (no build for this
|
|
9
|
+
* platform, offline, a failed download, a checksum that does not match) the
|
|
10
|
+
* WebAssembly engine runs instead. No install script runs.
|
|
11
|
+
*
|
|
12
|
+
* The addon runs the native CPU kernels (NEON, AVX2, AVX-512 VNNI) on every
|
|
13
|
+
* core and the GPU through `wgpu` (Metal on macOS, Vulkan or DX12 on Linux
|
|
14
|
+
* and Windows), with the device rules of the command-line tool.
|
|
15
|
+
*
|
|
16
|
+
* Node-only: the engine imports this module only in Node; browser bundles
|
|
17
|
+
* never download or load the addon.
|
|
18
|
+
*/
|
|
19
|
+
import { importNode } from "./runtime.js";
|
|
20
|
+
/** The platforms the native engine is released for. */
|
|
21
|
+
export const NATIVE_PLATFORMS = [
|
|
22
|
+
"darwin-arm64",
|
|
23
|
+
"darwin-x64",
|
|
24
|
+
"linux-x64-gnu",
|
|
25
|
+
"linux-arm64-gnu",
|
|
26
|
+
"linux-x64-musl",
|
|
27
|
+
"linux-arm64-musl",
|
|
28
|
+
"win32-x64-msvc",
|
|
29
|
+
];
|
|
30
|
+
/** Where the release assets are downloaded from (`WEBSLM_NATIVE_URL` replaces it: a mirror, or tests). */
|
|
31
|
+
export const NATIVE_RELEASES = "https://github.com/maxgfr/webslm/releases/download";
|
|
32
|
+
/** Most milliseconds the download of the addon may take before WebAssembly runs instead. */
|
|
33
|
+
export const NATIVE_DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
34
|
+
/** The native platform of `info`, when the engine is released for it. */
|
|
35
|
+
export function nativePlatform(info) {
|
|
36
|
+
let platform;
|
|
37
|
+
switch (info.platform) {
|
|
38
|
+
case "darwin":
|
|
39
|
+
platform = `darwin-${info.arch}`;
|
|
40
|
+
break;
|
|
41
|
+
case "linux":
|
|
42
|
+
platform = `linux-${info.arch}-${info.musl === true ? "musl" : "gnu"}`;
|
|
43
|
+
break;
|
|
44
|
+
case "win32":
|
|
45
|
+
platform = `win32-${info.arch}-msvc`;
|
|
46
|
+
break;
|
|
47
|
+
default:
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
return NATIVE_PLATFORMS.includes(platform) ? platform : undefined;
|
|
51
|
+
}
|
|
52
|
+
/** Why the native engine cannot run; `auto` falls back to WebAssembly with this reason. */
|
|
53
|
+
export class NativeUnavailable extends Error {
|
|
54
|
+
name = "NativeUnavailable";
|
|
55
|
+
}
|
|
56
|
+
async function sha256Hex(bytes) {
|
|
57
|
+
const crypto = await importNode("crypto");
|
|
58
|
+
return crypto.createHash("sha256").update(bytes).digest("hex");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The path of a verified copy of the addon for `options.platform`: the one
|
|
62
|
+
* in the cache when its SHA-256 matches the manifest, else the release asset,
|
|
63
|
+
* downloaded, checked (compressed and uncompressed), and stored in the cache.
|
|
64
|
+
* Throws {@link NativeUnavailable} with the reason otherwise.
|
|
65
|
+
*/
|
|
66
|
+
export async function fetchNativeAddon(options) {
|
|
67
|
+
const { manifest, version, platform } = options;
|
|
68
|
+
if (manifest === undefined) {
|
|
69
|
+
throw new NativeUnavailable("this build of webslm has no native-manifest.json (built from source: set WEBSLM_NATIVE_PATH)");
|
|
70
|
+
}
|
|
71
|
+
if (manifest.version !== version) {
|
|
72
|
+
throw new NativeUnavailable(`native-manifest.json describes ${manifest.version}, webslm is ${version}`);
|
|
73
|
+
}
|
|
74
|
+
const entry = manifest.assets[platform];
|
|
75
|
+
if (entry === undefined)
|
|
76
|
+
throw new NativeUnavailable(`no native build of ${version} for ${platform}`);
|
|
77
|
+
const fs = await importNode("fs/promises");
|
|
78
|
+
const path = await importNode("path");
|
|
79
|
+
const dir = path.join(options.cacheDir, "native", version);
|
|
80
|
+
const file = path.join(dir, entry.file.replace(/\.gz$/, ""));
|
|
81
|
+
const cached = await fs.readFile(file).catch(() => undefined);
|
|
82
|
+
if (cached !== undefined && (await sha256Hex(cached)) === entry.nodeSha256)
|
|
83
|
+
return file;
|
|
84
|
+
if (options.offline === true) {
|
|
85
|
+
throw new NativeUnavailable(`offline mode is on and the native engine ${version} is not in the cache`);
|
|
86
|
+
}
|
|
87
|
+
const url = `${options.baseUrl ?? NATIVE_RELEASES}/v${version}/${entry.file}`;
|
|
88
|
+
let gzipped;
|
|
89
|
+
try {
|
|
90
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
91
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? NATIVE_DOWNLOAD_TIMEOUT_MS),
|
|
92
|
+
});
|
|
93
|
+
if (!response.ok)
|
|
94
|
+
throw new Error(`HTTP ${response.status}`);
|
|
95
|
+
gzipped = new Uint8Array(await response.arrayBuffer());
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
99
|
+
throw new NativeUnavailable(`cannot download the native engine from ${url} (${message})`);
|
|
100
|
+
}
|
|
101
|
+
if ((await sha256Hex(gzipped)) !== entry.sha256) {
|
|
102
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
|
|
103
|
+
}
|
|
104
|
+
const zlib = await importNode("zlib");
|
|
105
|
+
let addon;
|
|
106
|
+
try {
|
|
107
|
+
addon = zlib.gunzipSync(gzipped);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} is not a gzip file`);
|
|
111
|
+
}
|
|
112
|
+
if ((await sha256Hex(addon)) !== entry.nodeSha256) {
|
|
113
|
+
throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
|
|
114
|
+
}
|
|
115
|
+
// Written under a temporary name and renamed: concurrent processes never
|
|
116
|
+
// load a partial file.
|
|
117
|
+
await fs.mkdir(dir, { recursive: true });
|
|
118
|
+
const partial = `${file}.${Date.now()}-${Math.random().toString(36).slice(2)}.partial`;
|
|
119
|
+
try {
|
|
120
|
+
await fs.writeFile(partial, addon);
|
|
121
|
+
await fs.rename(partial, file);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
await fs.rm(partial, { force: true }).catch(() => { });
|
|
125
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
126
|
+
throw new NativeUnavailable(`cannot store the native engine in ${dir} (${message})`);
|
|
127
|
+
}
|
|
128
|
+
return file;
|
|
129
|
+
}
|
|
130
|
+
function nodeProcess() {
|
|
131
|
+
return globalThis.process;
|
|
132
|
+
}
|
|
133
|
+
/** Whether Linux runs on musl: glibc reports its version in the process report. */
|
|
134
|
+
async function isMusl(process) {
|
|
135
|
+
try {
|
|
136
|
+
const report = process.report?.getReport();
|
|
137
|
+
if (report?.header !== undefined)
|
|
138
|
+
return report.header.glibcVersionRuntime === undefined;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// Reports can be turned off.
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const fs = await importNode("fs/promises");
|
|
145
|
+
return (await fs.readFile("/usr/bin/ldd", "utf8")).includes("musl");
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Whether `auto` may pick the native engine in this runtime. */
|
|
152
|
+
export function nativeAutoAllowed(process) {
|
|
153
|
+
// Deno runs Node-API addons only with `--allow-ffi`, and would prompt for
|
|
154
|
+
// it: there `backend: "native"` asks for it explicitly.
|
|
155
|
+
return process.versions["deno"] === undefined;
|
|
156
|
+
}
|
|
157
|
+
let availability;
|
|
158
|
+
/**
|
|
159
|
+
* Loads the addon once per thread: `WEBSLM_NATIVE_PATH` (a `.node` file, for
|
|
160
|
+
* local builds) when set, else the release asset of this platform and
|
|
161
|
+
* version, from `<cacheDir>/native/<version>/` or downloaded there first and
|
|
162
|
+
* checked against `native-manifest.json` (see {@link fetchNativeAddon}).
|
|
163
|
+
* Resolves with the reason when it cannot be used.
|
|
164
|
+
*/
|
|
165
|
+
export function loadNativeAddon(cacheDir) {
|
|
166
|
+
availability ??= (async () => {
|
|
167
|
+
const process = nodeProcess();
|
|
168
|
+
if (process === undefined)
|
|
169
|
+
return { reason: "the native engine runs in Node only" };
|
|
170
|
+
const { createRequire } = await importNode("module");
|
|
171
|
+
const base = import.meta.url;
|
|
172
|
+
const loadModule = createRequire(base);
|
|
173
|
+
const version = packageVersion(loadModule);
|
|
174
|
+
const explicit = process.env["WEBSLM_NATIVE_PATH"]?.trim();
|
|
175
|
+
let source;
|
|
176
|
+
if (explicit !== undefined && explicit !== "") {
|
|
177
|
+
source = explicit;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const platform = nativePlatform({
|
|
181
|
+
platform: process.platform,
|
|
182
|
+
arch: process.arch,
|
|
183
|
+
...(process.platform === "linux" ? { musl: await isMusl(process) } : {}),
|
|
184
|
+
});
|
|
185
|
+
if (platform === undefined)
|
|
186
|
+
return { reason: `no native build for ${process.platform}-${process.arch}` };
|
|
187
|
+
if (version === undefined)
|
|
188
|
+
return { reason: "the version of webslm is unknown" };
|
|
189
|
+
const { defaultCacheDir } = await import("./cache/node-fs.js");
|
|
190
|
+
const { offlineMode } = await import("./hub.js");
|
|
191
|
+
const baseUrl = process.env["WEBSLM_NATIVE_URL"]?.trim();
|
|
192
|
+
try {
|
|
193
|
+
source = await fetchNativeAddon({
|
|
194
|
+
platform,
|
|
195
|
+
version,
|
|
196
|
+
manifest: readManifest(loadModule),
|
|
197
|
+
cacheDir: cacheDir ?? (await defaultCacheDir()),
|
|
198
|
+
offline: offlineMode(),
|
|
199
|
+
...(baseUrl === undefined || baseUrl === "" ? {} : { baseUrl }),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
return { reason: error instanceof Error ? error.message : String(error) };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
let addon;
|
|
207
|
+
try {
|
|
208
|
+
addon = loadModule(source);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
|
|
212
|
+
return { reason: `${source} does not load (${message})` };
|
|
213
|
+
}
|
|
214
|
+
const actual = addon.version();
|
|
215
|
+
if (version !== undefined && actual !== version) {
|
|
216
|
+
return { reason: `${source} is version ${actual}, webslm is ${version}` };
|
|
217
|
+
}
|
|
218
|
+
return { addon, source };
|
|
219
|
+
})();
|
|
220
|
+
return availability;
|
|
221
|
+
}
|
|
222
|
+
/** The version of this package, from its `package.json`. */
|
|
223
|
+
function packageVersion(loadModule) {
|
|
224
|
+
try {
|
|
225
|
+
return loadModule("../package.json").version;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** The package's `native-manifest.json`, when it has one (the published package does). */
|
|
232
|
+
function readManifest(loadModule) {
|
|
233
|
+
try {
|
|
234
|
+
return loadModule("../native-manifest.json");
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** @internal Forgets the loaded addon (tests). */
|
|
241
|
+
export function resetNativeAddon() {
|
|
242
|
+
availability = undefined;
|
|
243
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* `read` messages. `abort` and `readResult` get no answer.
|
|
7
7
|
*/
|
|
8
8
|
import type { SerializedError } from "./errors.js";
|
|
9
|
-
import type { Activations, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
|
|
9
|
+
import type { Activations, AdapterMode, Backend, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
|
|
10
10
|
import type { WasmFlavour } from "./wasm-flavour.js";
|
|
11
11
|
/** A model source in a form that can be posted to a worker. */
|
|
12
12
|
export type WireSource = {
|
|
@@ -25,12 +25,23 @@ export type WireSource = {
|
|
|
25
25
|
};
|
|
26
26
|
export interface WireLoadOptions {
|
|
27
27
|
readonly quant: string;
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* The caller asked for `quant: "auto"` (and resolved it to `quant` for the
|
|
30
|
+
* WebAssembly engine): the native engine decides again, against the
|
|
31
|
+
* machine's memory and GPU.
|
|
32
|
+
*/
|
|
33
|
+
readonly autoQuant?: boolean;
|
|
34
|
+
/** `"auto"`, `"cpu"`, `"gpu"` or `"webgpu"`; the engine reports what it used. */
|
|
29
35
|
readonly device?: string;
|
|
36
|
+
/** `"auto"` (default), `"native"` or `"wasm"`. */
|
|
37
|
+
readonly backend?: Backend;
|
|
30
38
|
readonly contextLength?: number;
|
|
31
39
|
/** Scale of the adapter of a `load` request. */
|
|
32
40
|
readonly adapterScale?: number;
|
|
41
|
+
readonly adapterMode?: AdapterMode;
|
|
33
42
|
readonly cacheDir?: string;
|
|
43
|
+
/** `false` turns the converted-weight cache off. */
|
|
44
|
+
readonly weightCache?: boolean;
|
|
34
45
|
readonly deterministic?: boolean;
|
|
35
46
|
readonly activations?: Activations;
|
|
36
47
|
readonly wasmFlavour?: WasmFlavour;
|
|
@@ -72,7 +83,7 @@ type WithId<T> = T & {
|
|
|
72
83
|
export type Request = WithId<{
|
|
73
84
|
readonly type: "load";
|
|
74
85
|
readonly source: WireSource;
|
|
75
|
-
/** A LoRA adapter
|
|
86
|
+
/** A LoRA adapter applied at load. */
|
|
76
87
|
readonly adapter?: WireSource;
|
|
77
88
|
readonly options: WireLoadOptions;
|
|
78
89
|
} | {
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sampling settings that model cards recommend: the table of the Rust
|
|
3
|
+
* engine (`crates/webslm-core/src/recommended_sampling.json`, used by the
|
|
4
|
+
* `webslm` command-line tool and server), copied here so that the package
|
|
5
|
+
* needs no file of the repository; `test/sampling.test.ts` checks that both
|
|
6
|
+
* stay identical. See `recommendedSampling` for how a checkpoint gets a set.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Sampling settings a model card recommends. Fields left out keep the
|
|
10
|
+
* engine's defaults (no top-k, top-p 1, min-p 0, no penalty).
|
|
11
|
+
*/
|
|
12
|
+
export interface SamplingDefaults {
|
|
13
|
+
readonly temperature: number;
|
|
14
|
+
readonly topK?: number;
|
|
15
|
+
readonly topP?: number;
|
|
16
|
+
readonly minP?: number;
|
|
17
|
+
readonly repetitionPenalty?: number;
|
|
18
|
+
readonly presencePenalty?: number;
|
|
19
|
+
}
|
|
20
|
+
/** The settings of one model family. */
|
|
21
|
+
export interface SamplingSet {
|
|
22
|
+
/** Whether the family reasons when `enable_thinking` is not set (Qwen3, LFM3). */
|
|
23
|
+
readonly thinksByDefault?: boolean;
|
|
24
|
+
/** When the model answers directly. */
|
|
25
|
+
readonly answer: SamplingDefaults;
|
|
26
|
+
/** When it reasons first (`answer` when absent). */
|
|
27
|
+
readonly thinking?: SamplingDefaults;
|
|
28
|
+
}
|
|
29
|
+
/** The table: sets by name, and which repositories and `model_type`s use them. */
|
|
30
|
+
export interface SamplingTable {
|
|
31
|
+
readonly sets: Readonly<Record<string, SamplingSet>>;
|
|
32
|
+
readonly repos: Readonly<Record<string, string>>;
|
|
33
|
+
readonly modelTypes: Readonly<Record<string, string>>;
|
|
34
|
+
}
|
|
35
|
+
export declare const RECOMMENDED_SAMPLING: SamplingTable;
|
|
36
|
+
/** What identifies a checkpoint for {@link samplingSet}. */
|
|
37
|
+
export interface CheckpointTraits {
|
|
38
|
+
/** Hub repository id (a `@revision` suffix is ignored). */
|
|
39
|
+
readonly repo?: string | undefined;
|
|
40
|
+
/** `model_type` of its `config.json`. */
|
|
41
|
+
readonly modelType?: string | undefined;
|
|
42
|
+
/** Whether its `generation_config.json` asks for sampling (`do_sample`). */
|
|
43
|
+
readonly doSample?: boolean | undefined;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The set of a checkpoint, the way the Rust engine picks it: a listed
|
|
47
|
+
* repository (case-insensitive) uses its set whatever its
|
|
48
|
+
* `generation_config.json` says; otherwise a checkpoint whose
|
|
49
|
+
* `generation_config.json` does not ask for sampling uses the set of its
|
|
50
|
+
* `model_type`, when listed; otherwise none.
|
|
51
|
+
*/
|
|
52
|
+
export declare function samplingSet(checkpoint: CheckpointTraits): SamplingSet | undefined;
|
|
53
|
+
/** The settings of `set` with or without reasoning (`think` unset: the family's default). */
|
|
54
|
+
export declare function settingsFor(set: SamplingSet, think?: boolean): SamplingDefaults;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sampling settings that model cards recommend: the table of the Rust
|
|
3
|
+
* engine (`crates/webslm-core/src/recommended_sampling.json`, used by the
|
|
4
|
+
* `webslm` command-line tool and server), copied here so that the package
|
|
5
|
+
* needs no file of the repository; `test/sampling.test.ts` checks that both
|
|
6
|
+
* stay identical. See `recommendedSampling` for how a checkpoint gets a set.
|
|
7
|
+
*/
|
|
8
|
+
// Each model card: SmolLM2 (its usage example), LFM2.5 and LFM3
|
|
9
|
+
// ("generation parameters", LFM3's "general" set), Qwen3 (best practices,
|
|
10
|
+
// thinking and non-thinking), Qwen3.5 (the settings its benchmarks used in
|
|
11
|
+
// each mode).
|
|
12
|
+
export const RECOMMENDED_SAMPLING = {
|
|
13
|
+
sets: {
|
|
14
|
+
smollm2: {
|
|
15
|
+
answer: { temperature: 0.2, topP: 0.9 },
|
|
16
|
+
},
|
|
17
|
+
lfm2: {
|
|
18
|
+
answer: { temperature: 0.1, topK: 50, repetitionPenalty: 1.05 },
|
|
19
|
+
},
|
|
20
|
+
lfm3: {
|
|
21
|
+
thinksByDefault: true,
|
|
22
|
+
answer: { temperature: 0.1, topK: 50, repetitionPenalty: 1.1 },
|
|
23
|
+
},
|
|
24
|
+
qwen3: {
|
|
25
|
+
thinksByDefault: true,
|
|
26
|
+
answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0 },
|
|
27
|
+
thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0 },
|
|
28
|
+
},
|
|
29
|
+
qwen3_5: {
|
|
30
|
+
answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0, presencePenalty: 1.5 },
|
|
31
|
+
thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0, presencePenalty: 1.5 },
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
repos: {
|
|
35
|
+
"HuggingFaceTB/SmolLM2-135M-Instruct": "smollm2",
|
|
36
|
+
"HuggingFaceTB/SmolLM2-360M-Instruct": "smollm2",
|
|
37
|
+
"LiquidAI/LFM2.5-350M": "lfm2",
|
|
38
|
+
"Qwen/Qwen3-0.6B": "qwen3",
|
|
39
|
+
"Qwen/Qwen3.5-0.8B": "qwen3_5",
|
|
40
|
+
"LiquidAI/LFM3-1.7B": "lfm3",
|
|
41
|
+
},
|
|
42
|
+
modelTypes: {
|
|
43
|
+
lfm2: "lfm2",
|
|
44
|
+
lfm3: "lfm3",
|
|
45
|
+
qwen3: "qwen3",
|
|
46
|
+
qwen3_5: "qwen3_5",
|
|
47
|
+
qwen3_5_text: "qwen3_5",
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* The set of a checkpoint, the way the Rust engine picks it: a listed
|
|
52
|
+
* repository (case-insensitive) uses its set whatever its
|
|
53
|
+
* `generation_config.json` says; otherwise a checkpoint whose
|
|
54
|
+
* `generation_config.json` does not ask for sampling uses the set of its
|
|
55
|
+
* `model_type`, when listed; otherwise none.
|
|
56
|
+
*/
|
|
57
|
+
export function samplingSet(checkpoint) {
|
|
58
|
+
const table = RECOMMENDED_SAMPLING;
|
|
59
|
+
const repo = checkpoint.repo?.split("@")[0]?.toLowerCase();
|
|
60
|
+
const byRepo = repo === undefined
|
|
61
|
+
? undefined
|
|
62
|
+
: Object.entries(table.repos).find(([id]) => id.toLowerCase() === repo)?.[1];
|
|
63
|
+
const name = byRepo ??
|
|
64
|
+
(checkpoint.doSample !== true && checkpoint.modelType !== undefined
|
|
65
|
+
? table.modelTypes[checkpoint.modelType]
|
|
66
|
+
: undefined);
|
|
67
|
+
return name === undefined ? undefined : table.sets[name];
|
|
68
|
+
}
|
|
69
|
+
/** The settings of `set` with or without reasoning (`think` unset: the family's default). */
|
|
70
|
+
export function settingsFor(set, think) {
|
|
71
|
+
const thinking = think ?? set.thinksByDefault === true;
|
|
72
|
+
return (thinking ? set.thinking : undefined) ?? set.answer;
|
|
73
|
+
}
|
package/dist/simple.d.ts
CHANGED
|
@@ -7,11 +7,16 @@ import { type Model } from "./models.js";
|
|
|
7
7
|
import type { ChatMessage, LoadModelOptions, ModelInfo, ModelSource } from "./types.js";
|
|
8
8
|
/**
|
|
9
9
|
* The model {@link load}, {@link ask} and {@link stream} use when none is
|
|
10
|
-
* given:
|
|
11
|
-
*
|
|
10
|
+
* given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
|
|
11
|
+
* on the CPU, and able to follow a conversation (the SmolLM2 checkpoints of
|
|
12
|
+
* the same size lose track of it after a turn or two).
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEFAULT_MODEL = "LiquidAI/LFM2.5-350M";
|
|
15
|
+
/**
|
|
16
|
+
* Sampling temperature used when neither the call, the model card of a
|
|
17
|
+
* curated model (`recommendedSampling`) nor the checkpoint's
|
|
18
|
+
* `generation_config.json` sets one.
|
|
12
19
|
*/
|
|
13
|
-
export declare const DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct";
|
|
14
|
-
/** Sampling temperature used when neither the call nor the checkpoint's `generation_config.json` sets one. */
|
|
15
20
|
export declare const DEFAULT_TEMPERATURE = 0.7;
|
|
16
21
|
/** Largest number of new tokens of an answer, unless `maxTokens` says otherwise. */
|
|
17
22
|
export declare const DEFAULT_MAX_TOKENS = 512;
|
|
@@ -21,7 +26,9 @@ export interface PromptOptions {
|
|
|
21
26
|
readonly maxTokens?: number;
|
|
22
27
|
/**
|
|
23
28
|
* Sampling temperature; `0` is greedy (deterministic) decoding. Defaults to
|
|
24
|
-
* the
|
|
29
|
+
* the model card's recommended sampling for the curated models
|
|
30
|
+
* (`recommendedSampling`), else the checkpoint's `generation_config.json`
|
|
31
|
+
* value, else 0.7.
|
|
25
32
|
*/
|
|
26
33
|
readonly temperature?: number;
|
|
27
34
|
/** System prompt sent before the user message. */
|
|
@@ -222,12 +229,19 @@ export declare class ReasoningSplitter {
|
|
|
222
229
|
* Text without such a block is all answer. `open` is `true` while the block
|
|
223
230
|
* is not closed yet (a stream still thinking, or an answer cut by `maxTokens`).
|
|
224
231
|
*
|
|
232
|
+
* `opened` says that the prompt already opened the block (templates such as
|
|
233
|
+
* Qwen3.5's and LFM3's end with `<think>` when thinking is on), so the output
|
|
234
|
+
* starts inside it. Left out, it is inferred: an output that closes a block
|
|
235
|
+
* it never opened started inside one.
|
|
236
|
+
*
|
|
225
237
|
* ```ts
|
|
226
238
|
* splitReasoning("<think>\nThe user greets me.\n</think>\n\nHello!");
|
|
227
239
|
* // { text: "Hello!", reasoning: "The user greets me.", open: false }
|
|
240
|
+
* splitReasoning("The user greets me.\n</think>\n\nHello!");
|
|
241
|
+
* // the same
|
|
228
242
|
* ```
|
|
229
243
|
*/
|
|
230
|
-
export declare function splitReasoning(output: string): Answer & {
|
|
244
|
+
export declare function splitReasoning(output: string, opened?: boolean): Answer & {
|
|
231
245
|
readonly open: boolean;
|
|
232
246
|
};
|
|
233
247
|
/** @internal Runs async functions one at a time, in call order. */
|
package/dist/simple.js
CHANGED
|
@@ -4,15 +4,21 @@
|
|
|
4
4
|
* {@link Session}.
|
|
5
5
|
*/
|
|
6
6
|
import { AsyncQueue } from "./async-queue.js";
|
|
7
|
+
import { recommendedSampling } from "./curated.js";
|
|
7
8
|
import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
|
|
8
9
|
import { loadModel } from "./models.js";
|
|
9
10
|
/**
|
|
10
11
|
* The model {@link load}, {@link ask} and {@link stream} use when none is
|
|
11
|
-
* given:
|
|
12
|
-
*
|
|
12
|
+
* given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
|
|
13
|
+
* on the CPU, and able to follow a conversation (the SmolLM2 checkpoints of
|
|
14
|
+
* the same size lose track of it after a turn or two).
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_MODEL = "LiquidAI/LFM2.5-350M";
|
|
17
|
+
/**
|
|
18
|
+
* Sampling temperature used when neither the call, the model card of a
|
|
19
|
+
* curated model (`recommendedSampling`) nor the checkpoint's
|
|
20
|
+
* `generation_config.json` sets one.
|
|
13
21
|
*/
|
|
14
|
-
export const DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct";
|
|
15
|
-
/** Sampling temperature used when neither the call nor the checkpoint's `generation_config.json` sets one. */
|
|
16
22
|
export const DEFAULT_TEMPERATURE = 0.7;
|
|
17
23
|
/** Largest number of new tokens of an answer, unless `maxTokens` says otherwise. */
|
|
18
24
|
export const DEFAULT_MAX_TOKENS = 512;
|
|
@@ -128,18 +134,27 @@ export class ReasoningSplitter {
|
|
|
128
134
|
* Text without such a block is all answer. `open` is `true` while the block
|
|
129
135
|
* is not closed yet (a stream still thinking, or an answer cut by `maxTokens`).
|
|
130
136
|
*
|
|
137
|
+
* `opened` says that the prompt already opened the block (templates such as
|
|
138
|
+
* Qwen3.5's and LFM3's end with `<think>` when thinking is on), so the output
|
|
139
|
+
* starts inside it. Left out, it is inferred: an output that closes a block
|
|
140
|
+
* it never opened started inside one.
|
|
141
|
+
*
|
|
131
142
|
* ```ts
|
|
132
143
|
* splitReasoning("<think>\nThe user greets me.\n</think>\n\nHello!");
|
|
133
144
|
* // { text: "Hello!", reasoning: "The user greets me.", open: false }
|
|
145
|
+
* splitReasoning("The user greets me.\n</think>\n\nHello!");
|
|
146
|
+
* // the same
|
|
134
147
|
* ```
|
|
135
148
|
*/
|
|
136
|
-
export function splitReasoning(output) {
|
|
149
|
+
export function splitReasoning(output, opened) {
|
|
137
150
|
let text = "";
|
|
138
151
|
let reasoning = "";
|
|
152
|
+
const close = output.indexOf(CLOSE);
|
|
153
|
+
const startsInside = opened ?? (close !== -1 && !output.slice(0, close).includes(OPEN));
|
|
139
154
|
const splitter = new ReasoningSplitter({
|
|
140
155
|
text: (t) => (text += t),
|
|
141
156
|
reasoning: (t) => (reasoning += t),
|
|
142
|
-
},
|
|
157
|
+
}, startsInside);
|
|
143
158
|
splitter.push(output);
|
|
144
159
|
const open = splitter.inReasoning;
|
|
145
160
|
splitter.end();
|
|
@@ -300,7 +315,13 @@ class LLMImpl {
|
|
|
300
315
|
}, traits.opensReasoning(options.think));
|
|
301
316
|
const generation = {
|
|
302
317
|
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
303
|
-
|
|
318
|
+
// Curated models get their model card's sampling from the model
|
|
319
|
+
// itself (`recommendedSampling`).
|
|
320
|
+
...(options.temperature === undefined && hasRecommendedSampling(this.model.info())
|
|
321
|
+
? {}
|
|
322
|
+
: {
|
|
323
|
+
temperature: options.temperature ?? this.model.info().generationConfig.temperature ?? DEFAULT_TEMPERATURE,
|
|
324
|
+
}),
|
|
304
325
|
...(options.seed === undefined ? {} : { seed: options.seed }),
|
|
305
326
|
...(options.stop === undefined ? {} : { stop: options.stop }),
|
|
306
327
|
...passThrough(options),
|
|
@@ -326,6 +347,11 @@ class LLMImpl {
|
|
|
326
347
|
return this.#traits;
|
|
327
348
|
}
|
|
328
349
|
}
|
|
350
|
+
/** Whether the model card's sampling applies to `info` (`recommendedSampling`). */
|
|
351
|
+
function hasRecommendedSampling(info) {
|
|
352
|
+
const traits = { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
|
|
353
|
+
return recommendedSampling(traits) !== undefined;
|
|
354
|
+
}
|
|
329
355
|
/** Generation options the simple API passes through unchanged. */
|
|
330
356
|
function passThrough(options) {
|
|
331
357
|
const keys = [
|