webslm 0.3.1 → 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/dist/engine.js CHANGED
@@ -9,16 +9,27 @@
9
9
  * A model keeps reading its source after the load: applying or removing a
10
10
  * LoRA adapter reads the affected base matrices again. Reads of a `fetch`
11
11
  * source are forwarded to the page under the request being served.
12
+ *
13
+ * In Node, a model runs on the native engine (the Node-API addon, downloaded on first use
14
+ * and verified, see `native.ts`) when it is available, the source is a hub model and `backend` allows it; otherwise
15
+ * on the WebAssembly engine. Both take the same options and report the same
16
+ * descriptions: the requests below are served the same way for both.
12
17
  */
13
18
  import { openStore } from "./cache/index.js";
19
+ import { weightCachePath } from "./cache/models.js";
14
20
  import { prepareHubCheckpoint } from "./download.js";
15
21
  import { WebslmError, abortError, deserializeError, serializeError } from "./errors.js";
16
22
  import { SAFETENSORS_INDEX } from "./hub.js";
17
23
  import { scoreTransferables } from "./protocol.js";
18
24
  import { installNodeWebWorker, nodePoolAvailable } from "./node-web-worker.js";
19
25
  import { installPoolWorkerFactory } from "./pool.js";
20
- import { isNode, now, yieldToEventLoop } from "./runtime.js";
26
+ import { importNode, isNode, now, yieldToEventLoop } from "./runtime.js";
21
27
  import { defaultThreadCount, readFlavourModule, resolveFlavour, selectWasmFlavour, } from "./wasm-flavour.js";
28
+ /** Whether `WEBSLM_QUANT_CACHE=0` turns the converted-weight cache off (Node). */
29
+ function weightCacheDisabledByEnv() {
30
+ const env = globalThis.process?.env;
31
+ return env?.["WEBSLM_QUANT_CACHE"]?.trim() === "0";
32
+ }
22
33
  let wasmReady;
23
34
  /**
24
35
  * Instantiates the WebAssembly module once per realm (later calls share it,
@@ -65,14 +76,16 @@ const FLAVOUR_NAMES = {
65
76
  threads: "relaxed SIMD",
66
77
  };
67
78
  /**
68
- * Human-readable CPU backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"` or
69
- * `"CPU (wasm, SIMD128, 1 thread, deterministic, f32 activations)"`.
79
+ * Human-readable CPU backend, e.g. `"CPU (wasm, relaxed SIMD, 8 threads)"`,
80
+ * `"CPU (wasm, SIMD128, 1 thread, deterministic, f32 activations)"` or
81
+ * `"CPU (native, neon-i8mm, 10 threads)"`.
70
82
  */
71
83
  export function describeCpu(cpu, activations = "quantized") {
72
84
  const threads = cpu.threads === 1 ? "1 thread" : `${cpu.threads} threads`;
73
85
  const mode = cpu.deterministic ? ", deterministic" : "";
74
86
  const precision = activations === "f32" ? ", f32 activations" : "";
75
- return `CPU (wasm, ${FLAVOUR_NAMES[cpu.flavour]}, ${threads}${mode}${precision})`;
87
+ const build = cpu.flavour === "native" ? `native, ${cpu.kernels}` : `wasm, ${FLAVOUR_NAMES[cpu.flavour]}`;
88
+ return `CPU (${build}, ${threads}${mode}${precision})`;
76
89
  }
77
90
  export class Engine {
78
91
  #host;
@@ -125,19 +138,20 @@ export class Engine {
125
138
  case "createSession": {
126
139
  const model = this.#model(request.model);
127
140
  const id = this.#nextSession++;
128
- model.sessions.set(id, model.wasm.createSession());
141
+ model.sessions.set(id, await model.handle.model.createSession());
129
142
  return [id];
130
143
  }
131
144
  case "forkSession": {
132
145
  const model = this.#model(request.model);
133
- const fork = this.#session(request.model, request.session).fork();
146
+ const fork = await this.#session(request.model, request.session).fork();
134
147
  const id = this.#nextSession++;
135
148
  model.sessions.set(id, fork);
136
149
  return [id];
137
150
  }
138
151
  case "scoreContinuations": {
139
152
  const session = this.#session(request.model, request.session);
140
- const scores = (await session.scoreContinuations(request.prefix, JSON.stringify(request.continuations)));
153
+ const runtime = this.#model(request.model).handle.runtime;
154
+ const scores = (await session.scoreContinuations(request.prefix, JSON.stringify(request.continuations))).map((a) => transferable(a, runtime));
141
155
  return [scores, scores.map((a) => a.buffer)];
142
156
  }
143
157
  case "shiftContext": {
@@ -154,40 +168,49 @@ export class Engine {
154
168
  case "step": {
155
169
  const session = this.#session(request.model, request.session);
156
170
  const options = JSON.stringify(request.options);
157
- const raw = (await (request.type === "score"
171
+ const result = (await (request.type === "score"
158
172
  ? session.score(request.ids, options)
159
173
  : session.step(request.token, options)));
174
+ const runtime = this.#model(request.model).handle.runtime;
175
+ const raw = {
176
+ ...result,
177
+ ...(result.logits === undefined ? {} : { logits: transferable(result.logits, runtime) }),
178
+ hidden: Object.fromEntries(Object.entries(result.hidden).map(([i, a]) => [i, transferable(a, runtime)])),
179
+ };
160
180
  return [raw, scoreTransferables(raw)];
161
181
  }
162
182
  case "truncate": {
163
183
  const session = this.#session(request.model, request.session);
164
- session.truncate(request.length);
184
+ await session.truncate(request.length);
165
185
  return [session.length];
166
186
  }
167
187
  case "reset": {
168
188
  const model = this.#model(request.model);
169
189
  if (request.session === undefined)
170
- model.wasm.reset();
190
+ await model.handle.model.reset();
171
191
  else
172
- this.#session(request.model, request.session).reset();
192
+ await this.#session(request.model, request.session).reset();
173
193
  return [0];
174
194
  }
175
195
  case "tokenize": {
176
- const ids = this.#model(request.model).wasm.tokenize(request.text, request.addSpecialTokens);
196
+ const { handle } = this.#model(request.model);
197
+ const ids = transferable(await handle.model.tokenize(request.text, request.addSpecialTokens), handle.runtime);
177
198
  return [ids, [ids.buffer]];
178
199
  }
179
200
  case "detokenize":
180
- return [this.#model(request.model).wasm.detokenize(request.ids, request.skipSpecialTokens)];
201
+ return [
202
+ await this.#model(request.model).handle.model.detokenize(request.ids, request.skipSpecialTokens),
203
+ ];
181
204
  case "renderChat":
182
205
  return [
183
- this.#model(request.model).wasm.renderChat(JSON.stringify(request.messages), JSON.stringify(request.templateKwargs)),
206
+ await this.#model(request.model).handle.model.renderChat(JSON.stringify(request.messages), JSON.stringify(request.templateKwargs)),
184
207
  ];
185
208
  case "unload": {
186
209
  const model = this.#models.get(request.model);
187
210
  if (model !== undefined) {
188
211
  for (const session of model.sessions.values())
189
212
  session.free();
190
- model.wasm.free();
213
+ model.handle.model.free();
191
214
  this.#models.delete(request.model);
192
215
  }
193
216
  return [true];
@@ -210,7 +233,9 @@ export class Engine {
210
233
  }
211
234
  async #generate(request, signal) {
212
235
  const model = this.#model(request.model);
213
- const target = request.session === undefined ? model.wasm : this.#session(request.model, request.session);
236
+ if (model.handle.runtime === "native")
237
+ return this.#generateNative(request, model.handle, signal);
238
+ const target = request.session === undefined ? model.handle.model : this.#session(request.model, request.session);
214
239
  const started = now();
215
240
  let first;
216
241
  let last = started;
@@ -240,21 +265,70 @@ export class Engine {
240
265
  const summary = (await (request.type === "chat"
241
266
  ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
242
267
  : target.generate(request.prompt, options, onDelta, onPrefill)));
243
- const decoded = summary.generatedTokens - 1;
244
- const decodeSeconds = first === undefined ? 0 : (last - first) / 1000;
245
- return {
246
- ...summary,
247
- timeToFirstTokenMs: first === undefined ? 0 : first - started,
248
- tokensPerSecond: decoded > 0 && decodeSeconds > 0 ? decoded / decodeSeconds : 0,
268
+ return withTimings(summary, started, first, last);
269
+ }
270
+ /**
271
+ * A generation on the native engine: tokens arrive from the model's thread
272
+ * through a threadsafe function, and the signal cancels the call (before
273
+ * its next token, or the next piece of its prompt).
274
+ */
275
+ async #generateNative(request, handle, signal) {
276
+ const target = request.session === undefined ? handle.model : this.#session(request.model, request.session);
277
+ const cancel = new handle.addon.CancelToken();
278
+ const onAbort = () => cancel.cancel();
279
+ signal.addEventListener("abort", onAbort, { once: true });
280
+ if (signal.aborted)
281
+ cancel.cancel();
282
+ const started = now();
283
+ let first;
284
+ let last = started;
285
+ // The result and the tokens come through different queues: the result
286
+ // waits for every token it counts, so that the stream gets them all.
287
+ let received = 0;
288
+ let expected = Number.POSITIVE_INFINITY;
289
+ let allReceived = () => { };
290
+ const done = new Promise((resolve) => {
291
+ allReceived = resolve;
292
+ });
293
+ const onDelta = (text, token, info) => {
294
+ last = now();
295
+ first ??= last;
296
+ this.#host.post({
297
+ type: "delta",
298
+ id: request.id,
299
+ text,
300
+ token,
301
+ ...(info?.logprob === undefined ? {} : { logprob: info.logprob }),
302
+ ...(info?.topLogprobs === undefined ? {} : { topLogprobs: info.topLogprobs }),
303
+ ...(info?.forced === true ? { forced: true } : {}),
304
+ });
305
+ received += 1;
306
+ if (received >= expected)
307
+ allReceived();
308
+ };
309
+ const onPrefill = (doneTokens, total) => {
310
+ this.#host.post({ type: "prefill", id: request.id, done: doneTokens, total });
249
311
  };
312
+ const options = JSON.stringify(request.options);
313
+ try {
314
+ const summary = (await (request.type === "chat"
315
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill, cancel)
316
+ : target.generate(request.prompt, options, onDelta, onPrefill, cancel)));
317
+ expected = summary.tokens.length;
318
+ if (received < expected)
319
+ await done;
320
+ return withTimings(summary, started, first, last);
321
+ }
322
+ finally {
323
+ signal.removeEventListener("abort", onAbort);
324
+ }
250
325
  }
251
326
  /**
252
327
  * Opens a source: downloads a hub checkpoint (or adapter) into the cache,
253
328
  * hashes files held by the page, or forwards reads to the page. `active`
254
329
  * names the request reads are served for (it changes after the load).
255
330
  */
256
- async #openSource(active, source, cacheDir, progress, bindings, target) {
257
- const { Sha256Hasher } = bindings;
331
+ async #openSource(active, source, cacheDir, progress, createHasher, target) {
258
332
  const sizes = new Map();
259
333
  const hashes = new Map();
260
334
  switch (source.kind) {
@@ -264,7 +338,7 @@ export class Engine {
264
338
  store,
265
339
  signal: active.signal,
266
340
  onProgress: progress,
267
- createHasher: () => new Sha256Hasher(),
341
+ createHasher,
268
342
  ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
269
343
  ...(source.token === undefined ? {} : { token: source.token }),
270
344
  };
@@ -282,6 +356,7 @@ export class Engine {
282
356
  repo: checkpoint.repo,
283
357
  revision: checkpoint.sha,
284
358
  fromCache: checkpoint.fromCache,
359
+ store,
285
360
  };
286
361
  }
287
362
  case "files": {
@@ -290,7 +365,7 @@ export class Engine {
290
365
  sizes.set(name, fileSize(data));
291
366
  if (active.signal.aborted)
292
367
  throw abortError(active.signal);
293
- hashes.set(name, await hashFile(data, () => new Sha256Hasher()));
368
+ hashes.set(name, await hashFile(data, createHasher));
294
369
  }
295
370
  return {
296
371
  read: async (path, start, end) => {
@@ -345,29 +420,122 @@ export class Engine {
345
420
  const list = opened.list;
346
421
  return { source: new bindings.JsSource(read, list === undefined ? undefined : () => list), weightTotal };
347
422
  }
423
+ /**
424
+ * The converted-weight cache of a hub checkpoint in `quant`, in the store
425
+ * it was downloaded to: `<repo>/<sha>/quantized/<format>/weights.webslmq`,
426
+ * the command-line tool's layout. Only OPFS and the Node cache directory
427
+ * hold it (the Cache API keeps a file in memory until it is complete).
428
+ */
429
+ async #openWeightCache(opened, options, progress, bindings) {
430
+ const { store, repo, revision } = opened;
431
+ if (options.weightCache === false ||
432
+ weightCacheDisabledByEnv() ||
433
+ store === undefined ||
434
+ repo === undefined ||
435
+ revision === undefined ||
436
+ (store.kind !== "opfs" && store.kind !== "fs")) {
437
+ return undefined;
438
+ }
439
+ const path = weightCachePath(repo, revision, options.quant);
440
+ const size = (await store.size(path).catch(() => undefined)) ?? 0;
441
+ let writer;
442
+ let read = 0;
443
+ let lastReport = 0;
444
+ const handle = new bindings.JsWeightCache(`${repo}@${revision}`, size, async (start, end) => {
445
+ const bytes = await store.read(path, start, end);
446
+ read += bytes.length;
447
+ const t = now();
448
+ if (t - lastReport > 50) {
449
+ lastReport = t;
450
+ progress({
451
+ phase: "load",
452
+ file: path.split("/").pop() ?? path,
453
+ loadedBytes: read,
454
+ totalBytes: size,
455
+ overallLoadedBytes: read,
456
+ overallTotalBytes: size,
457
+ });
458
+ }
459
+ return bytes;
460
+ }, async (chunk) => {
461
+ writer ??= await store.openWriter(path, 0);
462
+ await writer.write(chunk);
463
+ });
464
+ const discard = async () => {
465
+ await writer?.abort().catch(() => { });
466
+ await store.remove(path).catch(() => { });
467
+ };
468
+ return {
469
+ handle,
470
+ settle: async (outcome) => {
471
+ if (outcome.status === "written" && writer !== undefined) {
472
+ try {
473
+ await writer.close();
474
+ return { status: "written", bytes: outcome.bytes };
475
+ }
476
+ catch {
477
+ await discard();
478
+ return { status: "failed", bytes: 0 };
479
+ }
480
+ }
481
+ // A stale file (weights it lacks were converted again) or a
482
+ // partial one is removed, to be written again by the next load.
483
+ if (writer !== undefined || (outcome.status === "hit" && outcome.misses > 0))
484
+ await discard();
485
+ if (outcome.status === "hit")
486
+ return { status: "hit", bytes: outcome.bytes };
487
+ return { status: outcome.status === "failed" ? "failed" : "off", bytes: 0 };
488
+ },
489
+ abort: async () => {
490
+ if (writer !== undefined)
491
+ await discard();
492
+ },
493
+ };
494
+ }
348
495
  async #load(requestId, source, adapterSource, options, signal) {
349
496
  const started = now();
350
497
  const active = { id: requestId, signal };
351
498
  const progress = (p) => this.#host.post({ type: "progress", id: active.id, progress: p });
499
+ const native = await chooseNative(options.backend ?? "auto", source, options.wasmFlavour, options.cacheDir);
500
+ if (native.addon !== undefined) {
501
+ // The native engine needs no WebAssembly: hash downloads with Node's own SHA-256.
502
+ const createHasher = await nodeSha256();
503
+ const opened = await this.#openSource(active, source, options.cacheDir, progress, createHasher);
504
+ const adapter = adapterSource === undefined
505
+ ? undefined
506
+ : await this.#openSource(active, adapterSource, options.cacheDir, progress, createHasher, "adapter");
507
+ return this.#loadNative(native.addon, opened, adapter, options, active, started, progress);
508
+ }
352
509
  const engine = await initEngineWasm({
353
510
  ...(options.wasmFlavour === undefined ? {} : { flavour: options.wasmFlavour }),
354
511
  ...(options.threads === undefined ? {} : { threads: options.threads }),
355
512
  });
356
513
  const { WasmModel } = engine.bindings;
357
- const opened = await this.#openSource(active, source, options.cacheDir, progress, engine.bindings);
514
+ const wasmHasher = () => new engine.bindings.Sha256Hasher();
515
+ const opened = await this.#openSource(active, source, options.cacheDir, progress, wasmHasher);
358
516
  const adapter = adapterSource === undefined
359
517
  ? undefined
360
- : await this.#openSource(active, adapterSource, options.cacheDir, progress, engine.bindings, "adapter");
518
+ : await this.#openSource(active, adapterSource, options.cacheDir, progress, wasmHasher, "adapter");
361
519
  const { source: jsSource, weightTotal } = this.#jsSource(opened, active, progress, engine.bindings);
362
- const wasm = await WasmModel.load(jsSource, JSON.stringify({
363
- format: options.quant,
364
- device: options.device ?? "auto",
365
- ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
366
- ...(options.deterministic === true ? { deterministic: true } : {}),
367
- ...(options.activations === undefined ? {} : { activations: options.activations }),
368
- ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
369
- ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
370
- }), adapter === undefined ? undefined : this.#jsSource(adapter, active, () => { }, engine.bindings).source);
520
+ const weightCache = await this.#openWeightCache(opened, options, progress, engine.bindings);
521
+ let wasm;
522
+ try {
523
+ wasm = await WasmModel.load(jsSource, JSON.stringify({
524
+ format: options.quant,
525
+ device: options.device ?? "auto",
526
+ ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
527
+ ...(options.deterministic === true ? { deterministic: true } : {}),
528
+ ...(options.activations === undefined ? {} : { activations: options.activations }),
529
+ ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
530
+ ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
531
+ }), adapter === undefined ? undefined : this.#jsSource(adapter, active, () => { }, engine.bindings).source, weightCache?.handle);
532
+ }
533
+ catch (error) {
534
+ await weightCache?.abort();
535
+ throw error;
536
+ }
537
+ const cacheOutcome = wasm.info().weightCache;
538
+ const weightCacheInfo = weightCache === undefined ? { status: "off", bytes: 0 } : await weightCache.settle(cacheOutcome);
371
539
  if (signal.aborted) {
372
540
  wasm.free();
373
541
  throw abortError(signal);
@@ -383,8 +551,9 @@ export class Engine {
383
551
  ...(size === undefined ? {} : { sizeBytes: size }),
384
552
  };
385
553
  });
386
- const { weightFormat, kernels, deterministic, threads, backend, deviceNote, adapter: gpuAdapter, lora, files: _files, ...rest } = raw;
554
+ const { weightFormat, kernels, deterministic, threads, backend, deviceNote, adapter: gpuAdapter, lora, files: _files, weightCache: _weightCache, ...rest } = raw;
387
555
  void _files;
556
+ void _weightCache;
388
557
  const cpu = {
389
558
  flavour: engine.flavour,
390
559
  kernels,
@@ -399,6 +568,8 @@ export class Engine {
399
568
  ...(repo === undefined ? {} : { repo }),
400
569
  ...(revision === undefined ? {} : { revision }),
401
570
  device: gpu ? "webgpu" : "cpu",
571
+ runtime: "wasm",
572
+ ...(native.note === undefined ? {} : { runtimeNote: native.note }),
402
573
  backend: gpu
403
574
  ? `WebGPU${gpuAdapter === undefined ? "" : ` (${gpuAdapter})`}`
404
575
  : describeCpu(cpu, rest.activations),
@@ -408,10 +579,81 @@ export class Engine {
408
579
  quant: weightFormat,
409
580
  files,
410
581
  fromCache: opened.fromCache,
582
+ weightCache: weightCacheInfo,
411
583
  loadTimeMs: now() - started,
412
584
  };
413
585
  const id = this.#nextModel++;
414
- this.#models.set(id, { wasm, sessions: new Map(), info, active, adapterQueue: Promise.resolve() });
586
+ this.#models.set(id, {
587
+ handle: { runtime: "wasm", model: wasm },
588
+ sessions: new Map(),
589
+ info,
590
+ active,
591
+ adapterQueue: Promise.resolve(),
592
+ });
593
+ progress({
594
+ phase: "ready",
595
+ loadedBytes: weightTotal,
596
+ totalBytes: weightTotal,
597
+ overallLoadedBytes: weightTotal,
598
+ overallTotalBytes: weightTotal,
599
+ });
600
+ return { model: id, info };
601
+ }
602
+ /**
603
+ * Loads a hub checkpoint on the native engine, from the snapshot directory
604
+ * the download wrote (the command-line tool's layout), with its
605
+ * converted-weight cache next to it.
606
+ */
607
+ async #loadNative(addon, opened, adapter, options, active, started, progress) {
608
+ const dir = await snapshotDirectory(opened);
609
+ if (dir === undefined)
610
+ throw new WebslmError("ENGINE", "the native engine needs the model in the cache directory");
611
+ // Block-quantized weights only, as the WebAssembly engine keeps them
612
+ // (float formats convert quickly).
613
+ const cache = options.weightCache !== false &&
614
+ !weightCacheDisabledByEnv() &&
615
+ (options.autoQuant === true || options.quant !== "f32") &&
616
+ opened.repo !== undefined &&
617
+ opened.revision !== undefined
618
+ ? { weightCacheDir: await joinFsPath(dir, "quantized"), weightCacheKey: `${opened.repo}@${opened.revision}` }
619
+ : {};
620
+ const adapterDir = adapter === undefined ? undefined : await adapterDirectory(adapter);
621
+ const weightTotal = [...opened.sizes]
622
+ .filter(([file]) => file.endsWith(".safetensors"))
623
+ .reduce((n, [, size]) => n + size, 0);
624
+ progress({ phase: "load", loadedBytes: 0, totalBytes: weightTotal, overallLoadedBytes: 0, overallTotalBytes: weightTotal });
625
+ let model;
626
+ try {
627
+ model = await addon.NativeModel.load(dir, JSON.stringify({
628
+ format: options.autoQuant === true ? "auto" : options.quant,
629
+ device: options.device ?? "auto",
630
+ ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
631
+ ...(options.deterministic === true ? { deterministic: true } : {}),
632
+ ...(options.activations === undefined ? {} : { activations: options.activations }),
633
+ ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
634
+ ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
635
+ }), {
636
+ ...cache,
637
+ ...(adapterDir === undefined ? {} : { adapterDir: adapterDir.path }),
638
+ ...(options.threads === undefined ? {} : { threads: options.threads }),
639
+ });
640
+ }
641
+ finally {
642
+ await adapterDir?.dispose();
643
+ }
644
+ if (active.signal.aborted) {
645
+ model.free();
646
+ throw abortError(active.signal);
647
+ }
648
+ const info = nativeModelInfo(model.info(), opened, adapter, now() - started);
649
+ const id = this.#nextModel++;
650
+ this.#models.set(id, {
651
+ handle: { runtime: "native", model, addon },
652
+ sessions: new Map(),
653
+ info,
654
+ active,
655
+ adapterQueue: Promise.resolve(),
656
+ });
415
657
  progress({
416
658
  phase: "ready",
417
659
  loadedBytes: weightTotal,
@@ -437,13 +679,29 @@ export class Engine {
437
679
  async #applyAdapter(request, signal) {
438
680
  const model = this.#model(request.model);
439
681
  return this.#exclusive(model, request.id, signal, async () => {
440
- const engine = await initEngineWasm();
441
682
  const progress = (p) => this.#host.post({ type: "progress", id: request.id, progress: p });
442
683
  const active = { id: request.id, signal };
443
- const opened = await this.#openSource(active, request.source, request.options.cacheDir, progress, engine.bindings, "adapter");
444
- const adapter = this.#jsSource(opened, active, () => { }, engine.bindings).source;
445
684
  const options = JSON.stringify(request.options.scale === undefined ? {} : { scale: request.options.scale });
446
- const lora = withOrigin((await model.wasm.applyAdapter(adapter, options)), opened);
685
+ let opened;
686
+ let applied;
687
+ if (model.handle.runtime === "native") {
688
+ opened = await this.#openSource(active, request.source, request.options.cacheDir, progress, await nodeSha256(), "adapter");
689
+ const dir = await adapterDirectory(opened);
690
+ try {
691
+ applied = (await model.handle.model.applyAdapter(dir.path, options));
692
+ }
693
+ finally {
694
+ await dir.dispose();
695
+ }
696
+ }
697
+ else {
698
+ const engine = await initEngineWasm();
699
+ const createHasher = () => new engine.bindings.Sha256Hasher();
700
+ opened = await this.#openSource(active, request.source, request.options.cacheDir, progress, createHasher, "adapter");
701
+ const adapter = this.#jsSource(opened, active, () => { }, engine.bindings).source;
702
+ applied = (await model.handle.model.applyAdapter(adapter, options));
703
+ }
704
+ const lora = withOrigin(applied, opened);
447
705
  model.info = { ...model.info, lora };
448
706
  return lora;
449
707
  });
@@ -451,7 +709,7 @@ export class Engine {
451
709
  async #removeAdapter(id, modelId, signal) {
452
710
  const model = this.#model(modelId);
453
711
  return this.#exclusive(model, id, signal, async () => {
454
- const removed = (await model.wasm.removeAdapter());
712
+ const removed = (await model.handle.model.removeAdapter());
455
713
  const { lora, ...info } = model.info;
456
714
  model.info = info;
457
715
  return removed === null ? null : (lora ?? removed);
@@ -509,3 +767,152 @@ async function hashFile(data, createHasher) {
509
767
  hasher.free();
510
768
  }
511
769
  }
770
+ /** `summary` with the timings measured on this side. */
771
+ function withTimings(summary, started, first, last) {
772
+ const decoded = summary.generatedTokens - 1;
773
+ const decodeSeconds = first === undefined ? 0 : (last - first) / 1000;
774
+ return {
775
+ ...summary,
776
+ timeToFirstTokenMs: first === undefined ? 0 : first - started,
777
+ tokensPerSecond: decoded > 0 && decodeSeconds > 0 ? decoded / decodeSeconds : 0,
778
+ };
779
+ }
780
+ /** The engine `backend` picks for `source`: the native addon, or why not. */
781
+ export async function chooseNative(backend, source, wasmFlavour, cacheDir) {
782
+ if (backend === "wasm")
783
+ return {};
784
+ // Asking for a WebAssembly build asks for WebAssembly.
785
+ if (backend === "auto" && wasmFlavour !== undefined)
786
+ return {};
787
+ const unsupported = (reason) => {
788
+ if (backend === "native")
789
+ throw new WebslmError("UNSUPPORTED_DEVICE", `backend "native": ${reason}`);
790
+ return { note: `auto: WebAssembly (${reason})` };
791
+ };
792
+ if (!isNode()) {
793
+ // Browsers have only the WebAssembly engine: nothing to explain under auto.
794
+ if (backend === "native")
795
+ throw new WebslmError("UNSUPPORTED_DEVICE", 'backend "native": the native engine runs in Node only');
796
+ return {};
797
+ }
798
+ const { loadNativeAddon, nativeAutoAllowed } = await import("./native.js");
799
+ const process = globalThis.process;
800
+ if (backend === "auto" && !nativeAutoAllowed(process)) {
801
+ return { note: 'auto: WebAssembly (in Deno, backend: "native" loads the native engine, with --allow-ffi)' };
802
+ }
803
+ if (source.kind !== "hub") {
804
+ return unsupported("the native engine loads hub models, from the cache directory");
805
+ }
806
+ const available = await loadNativeAddon(cacheDir);
807
+ if (available.addon === undefined)
808
+ return unsupported(available.reason);
809
+ return { addon: available.addon };
810
+ }
811
+ async function joinFsPath(...parts) {
812
+ return (await importNode("path")).join(...parts);
813
+ }
814
+ /** The directory of a hub snapshot in the Node cache directory, if that is where it is. */
815
+ async function snapshotDirectory(opened) {
816
+ const root = opened.store?.root;
817
+ if (opened.store?.kind !== "fs" || typeof root !== "string" || opened.repo === undefined)
818
+ return undefined;
819
+ if (opened.revision === undefined)
820
+ return undefined;
821
+ return joinFsPath(root, ...opened.repo.split("/"), opened.revision);
822
+ }
823
+ /**
824
+ * A directory holding a LoRA adapter's files for the native engine: the
825
+ * snapshot of a hub adapter, else a temporary copy of its two files
826
+ * (`dispose` removes it).
827
+ */
828
+ async function adapterDirectory(opened) {
829
+ const snapshot = await snapshotDirectory(opened);
830
+ if (snapshot !== undefined)
831
+ return { path: snapshot, dispose: async () => { } };
832
+ const fs = await importNode("fs/promises");
833
+ const os = await importNode("os");
834
+ const dir = await fs.mkdtemp(await joinFsPath(os.tmpdir(), "webslm-adapter-"));
835
+ const dispose = () => fs.rm(dir, { recursive: true, force: true });
836
+ try {
837
+ for (const file of ["adapter_config.json", "adapter_model.safetensors"]) {
838
+ const bytes = await opened.read(file);
839
+ if (bytes === null)
840
+ throw new WebslmError("INVALID_ADAPTER", `the adapter has no ${file}`);
841
+ await fs.writeFile(await joinFsPath(dir, file), bytes);
842
+ }
843
+ }
844
+ catch (error) {
845
+ await dispose();
846
+ throw error;
847
+ }
848
+ return { path: dir, dispose };
849
+ }
850
+ const NATIVE_CACHE_STATUS = {
851
+ hit: "hit",
852
+ written: "written",
853
+ failed: "failed",
854
+ };
855
+ /** The {@link ModelInfo} of a model on the native engine. */
856
+ export function nativeModelInfo(raw, opened, adapter, loadTimeMs) {
857
+ const { device, weightFormat, kernels, deterministic, threads, backend: _backend, deviceNote, adapter: gpuAdapter, lora, files: rawFiles, weightCache, ...rest } = raw;
858
+ void _backend;
859
+ const files = rawFiles.map((f) => {
860
+ const sha256 = f.sha256 ?? opened.hashes.get(f.file);
861
+ const size = opened.sizes.get(f.file);
862
+ return {
863
+ file: f.file,
864
+ bytesRead: f.bytesRead,
865
+ ...(sha256 === undefined || sha256 === null ? {} : { sha256 }),
866
+ ...(size === undefined ? {} : { sizeBytes: size }),
867
+ };
868
+ });
869
+ const gpu = device === "gpu";
870
+ const cpu = { flavour: "native", kernels, threads, deterministic };
871
+ const status = NATIVE_CACHE_STATUS[weightCache.status] ?? "off";
872
+ const { repo, revision } = opened;
873
+ return {
874
+ ...rest,
875
+ ...(repo === undefined ? {} : { repo }),
876
+ ...(revision === undefined ? {} : { revision }),
877
+ device: gpu ? "gpu" : "cpu",
878
+ runtime: "native",
879
+ backend: gpu
880
+ ? `GPU (native${gpuAdapter === undefined ? "" : `, ${gpuAdapter}`})`
881
+ : describeCpu(cpu, rest.activations),
882
+ ...(gpu ? {} : { cpu }),
883
+ ...(deviceNote === undefined ? {} : { deviceNote }),
884
+ ...(lora === undefined || adapter === undefined ? {} : { lora: withOrigin(lora, adapter) }),
885
+ quant: weightFormat,
886
+ files,
887
+ fromCache: opened.fromCache,
888
+ weightCache: { status, bytes: status === "hit" || status === "written" ? weightCache.bytes : 0 },
889
+ loadTimeMs,
890
+ };
891
+ }
892
+ /** SHA-256 hashers on `node:crypto`, for loads that never start the WebAssembly engine. */
893
+ async function nodeSha256() {
894
+ const crypto = await importNode("crypto");
895
+ return () => {
896
+ let hash = crypto.createHash("sha256");
897
+ return {
898
+ update: (bytes) => {
899
+ hash.update(bytes);
900
+ },
901
+ finish: () => {
902
+ const digest = hash.digest("hex");
903
+ hash = crypto.createHash("sha256");
904
+ return digest;
905
+ },
906
+ free: () => { },
907
+ };
908
+ };
909
+ }
910
+ /**
911
+ * `array` in a buffer `postMessage` can transfer: the native engine's typed
912
+ * arrays wrap memory Node-API allocated outside the JavaScript heap, which
913
+ * cannot be transferred to another thread, so they are copied; the
914
+ * WebAssembly engine's are plain JavaScript arrays already.
915
+ */
916
+ function transferable(array, runtime) {
917
+ return runtime === "native" ? array.slice() : array;
918
+ }