mlx-bun 0.0.11 → 0.0.13
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 +63 -27
- package/THIRD_PARTY_LICENSES.md +9 -0
- package/docs/design/colibri-glm52-port.md +1486 -0
- package/docs/design/pre-colibri-stabilization.md +329 -0
- package/docs/investigations/colibri-oracle-pin.md +1284 -0
- package/docs/investigations/indexshare-performance-spike.md +357 -0
- package/docs/planning/release-notes-v0.0.12.md +80 -0
- package/docs/planning/release-notes-v0.0.13.md +77 -0
- package/docs/reference/cli.md +28 -2
- package/docs/reference/distribution.md +25 -1
- package/docs/reference/embedding.md +5 -2
- package/docs/reference/features-matrix.md +5 -2
- package/docs/reference/library-api.md +41 -13
- package/docs/reference/models.md +49 -2
- package/docs/reference/server-api.md +113 -20
- package/docs/reference/server-config.md +21 -14
- package/docs/reference/training.md +10 -1
- package/package.json +1 -1
- package/src/anthropic.ts +54 -44
- package/src/chat-template.ts +189 -11
- package/src/cli.ts +127 -8
- package/src/config.ts +81 -26
- package/src/diffusion/diffusion-generate.ts +14 -8
- package/src/download.ts +103 -12
- package/src/eval/ifeval.ts +63 -120
- package/src/eval/runner.ts +14 -5
- package/src/eval/tasks/ifeval.ts +167 -31
- package/src/expert-io.ts +391 -0
- package/src/expert-residency.ts +1134 -0
- package/src/expert-usage.ts +415 -0
- package/src/generate.ts +114 -17
- package/src/hf-push.ts +1 -1
- package/src/index.ts +14 -2
- package/src/jobs/runner.ts +37 -18
- package/src/kv-store.ts +147 -8
- package/src/lora.ts +77 -14
- package/src/media-fetch.ts +198 -56
- package/src/mlx/array.ts +43 -0
- package/src/mlx/autograd.ts +51 -14
- package/src/mlx/checkpoint.ts +46 -13
- package/src/mlx/custom-vjp.ts +83 -35
- package/src/model/factory.ts +96 -5
- package/src/model/gemma4-base.ts +32 -0
- package/src/model/glm52-atlas.ts +511 -0
- package/src/model/glm52-cache.ts +706 -0
- package/src/model/glm52-config.ts +262 -0
- package/src/model/glm52-container.ts +305 -0
- package/src/model/glm52-coupling.ts +388 -0
- package/src/model/glm52-dsa.ts +602 -0
- package/src/model/glm52-expert-layout.ts +253 -0
- package/src/model/glm52-layout.ts +152 -0
- package/src/model/glm52-memory.ts +473 -0
- package/src/model/glm52-mla.ts +786 -0
- package/src/model/glm52-moe.ts +223 -0
- package/src/model/glm52-pilot.ts +537 -0
- package/src/model/glm52-reference.ts +445 -0
- package/src/model/glm52-residency.ts +557 -0
- package/src/model/glm52-resident-weights.ts +135 -0
- package/src/model/glm52-streamed-experts.ts +453 -0
- package/src/model/glm52-streamed-metal.ts +610 -0
- package/src/model/glm52-weights.ts +503 -0
- package/src/model/glm52.ts +1153 -0
- package/src/model/support.ts +8 -1
- package/src/native/expert_io.c +523 -0
- package/src/native-pack.ts +6 -4
- package/src/responses.ts +62 -49
- package/src/serve/batch-scheduler.ts +95 -16
- package/src/serve/generation-gateway.ts +41 -16
- package/src/server.ts +471 -93
- package/src/spec/glm52-mtp-source.ts +392 -0
- package/src/spec/serve-loop.ts +99 -18
- package/src/spec/source.ts +31 -6
- package/src/ssd-cache.ts +6 -2
- package/src/tool-call.ts +30 -2
- package/src/train/job.ts +0 -10
- package/src/train/lora-params.ts +17 -6
- package/src/train/trainer.ts +59 -26
- package/src/web/app.html +13 -2
- package/src/web/app.js +30 -3
- package/src/web/src/status.ts +51 -3
- package/src/web-tools.ts +54 -2
- package/src/weights.ts +82 -19
package/src/eval/tasks/ifeval.ts
CHANGED
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
// 'banana'", "respond in JSON"). Each example carries one or more constraint
|
|
6
6
|
// instructions; we generate a response and run the corresponding verifier.
|
|
7
7
|
//
|
|
8
|
-
// We report
|
|
9
|
-
// *
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
8
|
+
// We report strict and loose metrics at both official granularities:
|
|
9
|
+
// * prompt — fraction of examples where ALL instructions pass;
|
|
10
|
+
// * instruction — fraction of supported individual checks that pass.
|
|
11
|
+
// Loose mode first strips leading "Sure, here is…" boilerplate and outer code
|
|
12
|
+
// fences. The primary metric (`accuracy`) remains prompt-level strict, as
|
|
13
|
+
// headlined by ifeval.py's IFEvalResult.__str__. Unknown instruction IDs retain
|
|
14
|
+
// optiq's prompt-pass behavior but are excluded from instruction accuracy and
|
|
15
|
+
// reported through the coverage object.
|
|
15
16
|
//
|
|
16
17
|
// Faithful port note: several verifiers below read kwarg keys that the dataset
|
|
17
18
|
// rows never populate (e.g. _check_capital_words_count / _check_letter_frequency
|
|
@@ -21,18 +22,56 @@
|
|
|
21
22
|
|
|
22
23
|
import { generateText, loadJsonl, sampleIndices, type TaskModel } from "../runner";
|
|
23
24
|
|
|
24
|
-
interface
|
|
25
|
-
key: number;
|
|
25
|
+
export interface IfevalInstance {
|
|
26
26
|
prompt: string;
|
|
27
27
|
instruction_id_list: string[];
|
|
28
28
|
kwargs: Record<string, unknown>[];
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
interface IfevalRow extends IfevalInstance {
|
|
32
|
+
key: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface IfevalCoverage {
|
|
36
|
+
/** Prompts for which every instruction ID has a registered verifier. */
|
|
37
|
+
fullySupportedPrompts: number;
|
|
38
|
+
promptCoverage: number;
|
|
39
|
+
/** Registered instruction checks; unknown IDs are excluded from accuracy. */
|
|
40
|
+
supportedInstructions: number;
|
|
41
|
+
totalInstructions: number;
|
|
42
|
+
instructionCoverage: number;
|
|
43
|
+
unhandledInstructionCounts: Record<string, number>;
|
|
44
|
+
}
|
|
45
|
+
|
|
31
46
|
export interface IfevalResult {
|
|
32
47
|
nTotal: number;
|
|
33
48
|
strictAcc: number; // 0..1 — prompt-level strict pass rate
|
|
34
49
|
looseAcc: number; // 0..1 — prompt-level loose pass rate
|
|
35
50
|
accuracy: number; // 0..1 — primary metric == strictAcc (ifeval.py headline)
|
|
51
|
+
strictInstructionAcc: number;
|
|
52
|
+
looseInstructionAcc: number;
|
|
53
|
+
coverage: IfevalCoverage;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface IfevalVerification {
|
|
57
|
+
/**
|
|
58
|
+
* One result per requested instruction. null means the instruction ID is
|
|
59
|
+
* unhandled and therefore excluded from instruction-level accuracy.
|
|
60
|
+
*/
|
|
61
|
+
instructionPasses: Array<boolean | null>;
|
|
62
|
+
/** OptiQ parity: unhandled IDs do not make the prompt fail. */
|
|
63
|
+
pass: boolean;
|
|
64
|
+
unhandled: string[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface IfevalInstanceScore {
|
|
68
|
+
strict: IfevalVerification;
|
|
69
|
+
loose: IfevalVerification;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface IfevalPair {
|
|
73
|
+
instance: IfevalInstance;
|
|
74
|
+
response: string;
|
|
36
75
|
}
|
|
37
76
|
|
|
38
77
|
// ---------------------------------------------------------------------------
|
|
@@ -278,20 +317,24 @@ const VERIFIERS = new Map<string, Verifier>([
|
|
|
278
317
|
["detectable_content:postscript", alwaysPass],
|
|
279
318
|
]);
|
|
280
319
|
|
|
320
|
+
export const SUPPORTED_INSTRUCTIONS = new Set(VERIFIERS.keys());
|
|
321
|
+
|
|
281
322
|
/**
|
|
282
323
|
* Verify one response against its instruction list.
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
324
|
+
* `instructionPasses` is aligned with the requested IDs and uses null for
|
|
325
|
+
* unhandled IDs. An ID with no registered verifier does not affect prompt
|
|
326
|
+
* `pass` and is recorded in `unhandled` — matching ifeval.py's `continue`
|
|
327
|
+
* policy exactly, so strict prompt accuracy reproduces OptiQ's. The canonical
|
|
328
|
+
* aggregate excludes those nulls from instruction accuracy and reports them
|
|
329
|
+
* through coverage.
|
|
288
330
|
*/
|
|
289
331
|
export function verifyResponse(
|
|
290
332
|
response: string,
|
|
291
333
|
instructionIds: string[],
|
|
292
334
|
kwargsList: Kw[],
|
|
293
|
-
):
|
|
335
|
+
): IfevalVerification {
|
|
294
336
|
const unhandled: string[] = [];
|
|
337
|
+
const instructionPasses: Array<boolean | null> = [];
|
|
295
338
|
let pass = true;
|
|
296
339
|
for (let i = 0; i < instructionIds.length; i++) {
|
|
297
340
|
const iid = instructionIds[i]!;
|
|
@@ -299,15 +342,19 @@ export function verifyResponse(
|
|
|
299
342
|
const verifier = VERIFIERS.get(iid);
|
|
300
343
|
if (verifier === undefined) {
|
|
301
344
|
unhandled.push(iid);
|
|
345
|
+
instructionPasses.push(null);
|
|
302
346
|
continue; // ifeval.py: treat an unhandled instruction as PASS (don't touch `pass`)
|
|
303
347
|
}
|
|
304
348
|
try {
|
|
305
|
-
|
|
349
|
+
const followed = verifier(response, kw);
|
|
350
|
+
instructionPasses.push(followed);
|
|
351
|
+
if (!followed) pass = false;
|
|
306
352
|
} catch {
|
|
353
|
+
instructionPasses.push(false);
|
|
307
354
|
pass = false;
|
|
308
355
|
}
|
|
309
356
|
}
|
|
310
|
-
return { pass, unhandled };
|
|
357
|
+
return { instructionPasses, pass, unhandled };
|
|
311
358
|
}
|
|
312
359
|
|
|
313
360
|
/** Loose-mode preprocessing — mirrors ifeval.py `_loose_clean`. */
|
|
@@ -328,6 +375,92 @@ export function stripThinking(response: string): string {
|
|
|
328
375
|
return idx === -1 ? response : response.slice(idx + "</think>".length);
|
|
329
376
|
}
|
|
330
377
|
|
|
378
|
+
/** Score one generated response with the canonical strict + loose contract. */
|
|
379
|
+
export function scoreIfevalInstance(
|
|
380
|
+
instance: IfevalInstance,
|
|
381
|
+
rawResponse: string,
|
|
382
|
+
): IfevalInstanceScore {
|
|
383
|
+
const response = stripThinking(rawResponse);
|
|
384
|
+
return {
|
|
385
|
+
strict: verifyResponse(
|
|
386
|
+
response,
|
|
387
|
+
instance.instruction_id_list,
|
|
388
|
+
instance.kwargs,
|
|
389
|
+
),
|
|
390
|
+
loose: verifyResponse(
|
|
391
|
+
looseClean(response),
|
|
392
|
+
instance.instruction_id_list,
|
|
393
|
+
instance.kwargs,
|
|
394
|
+
),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Canonical IFEval aggregation.
|
|
400
|
+
*
|
|
401
|
+
* Prompt accuracy follows the OptiQ reference behavior: an unknown instruction
|
|
402
|
+
* is recorded but does not fail its prompt. Instruction accuracy has a stricter
|
|
403
|
+
* denominator contract: unknown instructions are excluded and their coverage
|
|
404
|
+
* is reported explicitly, so an incomplete verifier registry cannot silently
|
|
405
|
+
* inflate that metric.
|
|
406
|
+
*/
|
|
407
|
+
export function scoreIfevalPairs(pairs: IfevalPair[]): IfevalResult {
|
|
408
|
+
let strictPrompts = 0;
|
|
409
|
+
let loosePrompts = 0;
|
|
410
|
+
let fullySupportedPrompts = 0;
|
|
411
|
+
let strictInstructions = 0;
|
|
412
|
+
let looseInstructions = 0;
|
|
413
|
+
let supportedInstructions = 0;
|
|
414
|
+
let totalInstructions = 0;
|
|
415
|
+
const unhandledCounts = new Map<string, number>();
|
|
416
|
+
|
|
417
|
+
for (const { instance, response } of pairs) {
|
|
418
|
+
const score = scoreIfevalInstance(instance, response);
|
|
419
|
+
if (score.strict.pass) strictPrompts++;
|
|
420
|
+
if (score.loose.pass) loosePrompts++;
|
|
421
|
+
if (score.strict.unhandled.length === 0) fullySupportedPrompts++;
|
|
422
|
+
totalInstructions += instance.instruction_id_list.length;
|
|
423
|
+
|
|
424
|
+
for (let i = 0; i < score.strict.instructionPasses.length; i++) {
|
|
425
|
+
const strict = score.strict.instructionPasses[i];
|
|
426
|
+
if (strict === null) continue;
|
|
427
|
+
supportedInstructions++;
|
|
428
|
+
if (strict) strictInstructions++;
|
|
429
|
+
if (score.loose.instructionPasses[i]) looseInstructions++;
|
|
430
|
+
}
|
|
431
|
+
for (const id of score.strict.unhandled)
|
|
432
|
+
unhandledCounts.set(id, (unhandledCounts.get(id) ?? 0) + 1);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const nTotal = pairs.length;
|
|
436
|
+
const strictAcc = nTotal ? strictPrompts / nTotal : 0;
|
|
437
|
+
const looseAcc = nTotal ? loosePrompts / nTotal : 0;
|
|
438
|
+
return {
|
|
439
|
+
nTotal,
|
|
440
|
+
strictAcc,
|
|
441
|
+
looseAcc,
|
|
442
|
+
accuracy: strictAcc,
|
|
443
|
+
strictInstructionAcc: supportedInstructions
|
|
444
|
+
? strictInstructions / supportedInstructions
|
|
445
|
+
: 0,
|
|
446
|
+
looseInstructionAcc: supportedInstructions
|
|
447
|
+
? looseInstructions / supportedInstructions
|
|
448
|
+
: 0,
|
|
449
|
+
coverage: {
|
|
450
|
+
fullySupportedPrompts,
|
|
451
|
+
promptCoverage: nTotal ? fullySupportedPrompts / nTotal : 0,
|
|
452
|
+
supportedInstructions,
|
|
453
|
+
totalInstructions,
|
|
454
|
+
instructionCoverage: totalInstructions
|
|
455
|
+
? supportedInstructions / totalInstructions
|
|
456
|
+
: 0,
|
|
457
|
+
unhandledInstructionCounts: Object.fromEntries(
|
|
458
|
+
[...unhandledCounts.entries()].sort(([a], [b]) => a.localeCompare(b)),
|
|
459
|
+
),
|
|
460
|
+
},
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
|
|
331
464
|
export async function evaluateIfeval(
|
|
332
465
|
tm: TaskModel,
|
|
333
466
|
opts: { nSamples?: number; maxTokens?: number; seed?: number; frozen?: boolean } = {},
|
|
@@ -348,7 +481,7 @@ export async function evaluateIfeval(
|
|
|
348
481
|
|
|
349
482
|
let nStrict = 0;
|
|
350
483
|
let nLoose = 0;
|
|
351
|
-
const
|
|
484
|
+
const pairs: IfevalPair[] = [];
|
|
352
485
|
|
|
353
486
|
for (let k = 0; k < idx.length; k++) {
|
|
354
487
|
const item = rows[idx[k]!]!;
|
|
@@ -356,14 +489,16 @@ export async function evaluateIfeval(
|
|
|
356
489
|
const kwList = item.kwargs ?? iids.map(() => ({}));
|
|
357
490
|
|
|
358
491
|
const raw = await generateText(tm, item.prompt, { maxTokens, useChat: true });
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
492
|
+
const instance: IfevalInstance = {
|
|
493
|
+
prompt: item.prompt,
|
|
494
|
+
instruction_id_list: iids,
|
|
495
|
+
kwargs: kwList,
|
|
496
|
+
};
|
|
497
|
+
const score = scoreIfevalInstance(instance, raw);
|
|
498
|
+
pairs.push({ instance, response: raw });
|
|
364
499
|
|
|
365
|
-
if (strict.pass) nStrict++;
|
|
366
|
-
if (loose.pass) nLoose++;
|
|
500
|
+
if (score.strict.pass) nStrict++;
|
|
501
|
+
if (score.loose.pass) nLoose++;
|
|
367
502
|
|
|
368
503
|
if ((k + 1) % 10 === 0 || k + 1 === idx.length)
|
|
369
504
|
process.stderr.write(
|
|
@@ -372,8 +507,12 @@ export async function evaluateIfeval(
|
|
|
372
507
|
}
|
|
373
508
|
process.stderr.write("\n");
|
|
374
509
|
|
|
375
|
-
|
|
376
|
-
|
|
510
|
+
const result = scoreIfevalPairs(pairs);
|
|
511
|
+
const unhandledCounts = Object.entries(
|
|
512
|
+
result.coverage.unhandledInstructionCounts,
|
|
513
|
+
);
|
|
514
|
+
if (unhandledCounts.length) {
|
|
515
|
+
const top = unhandledCounts.sort((a, b) => b[1] - a[1]);
|
|
377
516
|
process.stderr.write(
|
|
378
517
|
" ifeval unported instruction ids (treated as PASS, per optiq): " +
|
|
379
518
|
top.map(([k, v]) => `${k}(${v})`).join(", ") +
|
|
@@ -381,8 +520,5 @@ export async function evaluateIfeval(
|
|
|
381
520
|
);
|
|
382
521
|
}
|
|
383
522
|
|
|
384
|
-
|
|
385
|
-
const strictAcc = nTotal ? nStrict / nTotal : 0;
|
|
386
|
-
const looseAcc = nTotal ? nLoose / nTotal : 0;
|
|
387
|
-
return { nTotal, strictAcc, looseAcc, accuracy: strictAcc };
|
|
523
|
+
return result;
|
|
388
524
|
}
|
package/src/expert-io.ts
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import { dlopen, FFIType, ptr as ffiPtr, toArrayBuffer } from "bun:ffi";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { nativePackDir } from "./native-pack";
|
|
5
|
+
import type { MlxArray } from "./mlx/array";
|
|
6
|
+
import type { MlxHandle } from "./mlx/ffi";
|
|
7
|
+
|
|
8
|
+
const { cstring, i32, ptr: pointer, u32, u64 } = FFIType;
|
|
9
|
+
const EBUSY = 16;
|
|
10
|
+
const EAGAIN = 35;
|
|
11
|
+
const MAX_SEGMENTS = 8;
|
|
12
|
+
const HINT_STATS = 8;
|
|
13
|
+
|
|
14
|
+
type ExpertIOState = "open" | "closing" | "closed";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Poll an asynchronous expert read without letting an await cross the
|
|
18
|
+
* store's lifetime boundary. Exported only so the race can be tested with a
|
|
19
|
+
* deterministic fake poller rather than relying on native I/O timing.
|
|
20
|
+
*/
|
|
21
|
+
export async function _pollExpertReadUntilReady(
|
|
22
|
+
assertOpen: () => void,
|
|
23
|
+
poll: () => number,
|
|
24
|
+
sleep: () => Promise<void> = () => Bun.sleep(1),
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
for (;;) {
|
|
27
|
+
assertOpen();
|
|
28
|
+
const status = poll();
|
|
29
|
+
if (status === 0) return;
|
|
30
|
+
if (status !== EAGAIN) throw new Error(`expert read failed: errno ${status}`);
|
|
31
|
+
await sleep();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ExpertIOOptions {
|
|
36
|
+
slots: number;
|
|
37
|
+
slotBytes: number;
|
|
38
|
+
workers?: number;
|
|
39
|
+
alignment?: number;
|
|
40
|
+
noCache?: boolean;
|
|
41
|
+
/** Keep loaded anonymous slot pages out of the macOS compressor. */
|
|
42
|
+
wireSlots?: boolean;
|
|
43
|
+
libraryPath?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ExpertIOSegment {
|
|
47
|
+
readonly file: number;
|
|
48
|
+
readonly offset: number;
|
|
49
|
+
readonly destination: number;
|
|
50
|
+
readonly length: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ExpertIOHintSegment {
|
|
54
|
+
readonly file: number;
|
|
55
|
+
readonly offset: number;
|
|
56
|
+
readonly length: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ExpertIOHintSnapshot {
|
|
60
|
+
readonly submitted: number;
|
|
61
|
+
readonly completed: number;
|
|
62
|
+
readonly dropped: number;
|
|
63
|
+
readonly operations: number;
|
|
64
|
+
readonly bytes: number;
|
|
65
|
+
readonly errors: number;
|
|
66
|
+
readonly queueDepth: number;
|
|
67
|
+
readonly inFlight: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function resolveLibrary(explicit?: string): string {
|
|
71
|
+
if (explicit) return explicit;
|
|
72
|
+
if (process.env.MLX_BUN_EXPERT_IO_DYLIB) return process.env.MLX_BUN_EXPERT_IO_DYLIB;
|
|
73
|
+
const candidates = [
|
|
74
|
+
join(dirname(process.execPath), "libmlx_bun_expert_io.dylib"),
|
|
75
|
+
join(nativePackDir(), "libmlx_bun_expert_io.dylib"),
|
|
76
|
+
join(import.meta.dir, "..", "dist-native", "libmlx_bun_expert_io.dylib"),
|
|
77
|
+
];
|
|
78
|
+
return candidates.find(existsSync) ?? candidates[0]!;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export class ExpertIOSlabStore {
|
|
82
|
+
readonly files: readonly string[];
|
|
83
|
+
readonly slots: number;
|
|
84
|
+
readonly slotBytes: number;
|
|
85
|
+
#lib: any;
|
|
86
|
+
#handle: bigint;
|
|
87
|
+
#state: ExpertIOState = "open";
|
|
88
|
+
readonly #wireSlots: boolean;
|
|
89
|
+
|
|
90
|
+
constructor(path: string | readonly string[], options: ExpertIOOptions) {
|
|
91
|
+
if (!Number.isSafeInteger(options.slots) || options.slots <= 0) throw new Error("slots must be positive");
|
|
92
|
+
if (!Number.isSafeInteger(options.slotBytes) || options.slotBytes <= 0) throw new Error("slotBytes must be positive");
|
|
93
|
+
const paths = typeof path === "string" ? [path] : [...path];
|
|
94
|
+
if (paths.length === 0 || paths.some((entry) => entry.length === 0))
|
|
95
|
+
throw new Error("expert slab store requires at least one file");
|
|
96
|
+
this.files = Object.freeze(paths);
|
|
97
|
+
this.slots = options.slots; this.slotBytes = options.slotBytes;
|
|
98
|
+
this.#wireSlots = options.wireSlots === true;
|
|
99
|
+
this.#lib = dlopen(resolveLibrary(options.libraryPath), {
|
|
100
|
+
mlx_bun_expert_io_open: { args: [cstring, u32, u64, u64, u32, i32], returns: u64 },
|
|
101
|
+
mlx_bun_expert_io_open_many: {
|
|
102
|
+
args: [pointer, u64, u32, u32, u64, u64, u32, i32],
|
|
103
|
+
returns: u64,
|
|
104
|
+
},
|
|
105
|
+
mlx_bun_expert_io_submit: { args: [u64, u32, u64, u64, u64], returns: i32 },
|
|
106
|
+
mlx_bun_expert_io_submitv: {
|
|
107
|
+
args: [u64, u32, u64, pointer, pointer, pointer, pointer, u32],
|
|
108
|
+
returns: i32,
|
|
109
|
+
},
|
|
110
|
+
mlx_bun_expert_io_hintv: {
|
|
111
|
+
args: [u64, pointer, pointer, pointer, u32],
|
|
112
|
+
returns: i32,
|
|
113
|
+
},
|
|
114
|
+
mlx_bun_expert_io_hint_stats: {
|
|
115
|
+
args: [u64, pointer, u32],
|
|
116
|
+
returns: i32,
|
|
117
|
+
},
|
|
118
|
+
mlx_bun_expert_io_wait: { args: [u64, u32, u64], returns: i32 },
|
|
119
|
+
mlx_bun_expert_io_poll: { args: [u64, u32, u64], returns: i32 },
|
|
120
|
+
mlx_bun_expert_io_cancel: { args: [u64, u32, u64], returns: i32 },
|
|
121
|
+
mlx_bun_expert_io_lease: { args: [u64, u32, u64, i32], returns: i32 },
|
|
122
|
+
mlx_bun_expert_io_release: { args: [u64, u32, u64, i32], returns: i32 },
|
|
123
|
+
mlx_bun_expert_io_discard: { args: [u64, u32, u64], returns: i32 },
|
|
124
|
+
mlx_bun_expert_io_set_wiring: { args: [u64, i32], returns: i32 },
|
|
125
|
+
mlx_bun_process_phys_footprint: { args: [], returns: u64 },
|
|
126
|
+
mlx_bun_process_compressed: { args: [], returns: u64 },
|
|
127
|
+
mlx_bun_expert_io_ptr: { args: [u64, u32, u64], returns: u64 },
|
|
128
|
+
mlx_bun_expert_io_length: { args: [u64, u32, u64], returns: u64 },
|
|
129
|
+
mlx_bun_expert_io_close: { args: [u64], returns: i32 },
|
|
130
|
+
});
|
|
131
|
+
const encoded = Buffer.from(`${paths.join("\0")}\0`);
|
|
132
|
+
this.#handle = this.#lib.symbols.mlx_bun_expert_io_open_many(
|
|
133
|
+
ffiPtr(encoded), BigInt(encoded.byteLength), paths.length,
|
|
134
|
+
options.slots, BigInt(options.slotBytes),
|
|
135
|
+
BigInt(options.alignment ?? 16 * 1024),
|
|
136
|
+
options.workers ?? 2, options.noCache === false ? 0 : 1,
|
|
137
|
+
) as bigint;
|
|
138
|
+
if (this.#handle === 0n) {
|
|
139
|
+
this.#lib.close();
|
|
140
|
+
throw new Error(`failed to open expert slab store: ${paths.join(", ")}`);
|
|
141
|
+
}
|
|
142
|
+
if (this.#wireSlots) {
|
|
143
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_set_wiring(
|
|
144
|
+
this.#handle,
|
|
145
|
+
1,
|
|
146
|
+
);
|
|
147
|
+
if (status !== 0) {
|
|
148
|
+
this.#lib.symbols.mlx_bun_expert_io_close(this.#handle);
|
|
149
|
+
this.#lib.close();
|
|
150
|
+
throw new Error(`failed to enable expert slot wiring: errno ${status}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
submit(slot: number, generation: bigint, offset: number, length: number): void {
|
|
156
|
+
this.submitSegments(slot, generation, [{
|
|
157
|
+
file: 0,
|
|
158
|
+
offset,
|
|
159
|
+
destination: 0,
|
|
160
|
+
length,
|
|
161
|
+
}]);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
submitSegments(
|
|
165
|
+
slot: number,
|
|
166
|
+
generation: bigint,
|
|
167
|
+
segments: readonly ExpertIOSegment[],
|
|
168
|
+
): void {
|
|
169
|
+
this.#checkSlot(slot);
|
|
170
|
+
if (generation <= 0n) throw new RangeError("expert generation must be positive");
|
|
171
|
+
if (segments.length === 0 || segments.length > MAX_SEGMENTS)
|
|
172
|
+
throw new RangeError(`expert read requires 1..${MAX_SEGMENTS} segments`);
|
|
173
|
+
const files = new Uint32Array(segments.length);
|
|
174
|
+
const offsets = new BigUint64Array(segments.length);
|
|
175
|
+
const destinations = new BigUint64Array(segments.length);
|
|
176
|
+
const lengths = new BigUint64Array(segments.length);
|
|
177
|
+
let extent = 0;
|
|
178
|
+
for (let index = 0; index < segments.length; index++) {
|
|
179
|
+
const segment = segments[index]!;
|
|
180
|
+
if (!Number.isSafeInteger(segment.file) || segment.file < 0 ||
|
|
181
|
+
segment.file >= this.files.length)
|
|
182
|
+
throw new RangeError(`expert segment ${index} file is out of range`);
|
|
183
|
+
if (!Number.isSafeInteger(segment.offset) || segment.offset < 0)
|
|
184
|
+
throw new RangeError(`expert segment ${index} offset must be non-negative`);
|
|
185
|
+
if (!Number.isSafeInteger(segment.destination) || segment.destination < 0)
|
|
186
|
+
throw new RangeError(`expert segment ${index} destination must be non-negative`);
|
|
187
|
+
if (!Number.isSafeInteger(segment.length) || segment.length <= 0)
|
|
188
|
+
throw new RangeError(`expert segment ${index} length must be positive`);
|
|
189
|
+
const end = segment.destination + segment.length;
|
|
190
|
+
if (!Number.isSafeInteger(end) || end > this.slotBytes)
|
|
191
|
+
throw new RangeError(`expert segment ${index} exceeds slot capacity`);
|
|
192
|
+
for (let prior = 0; prior < index; prior++) {
|
|
193
|
+
const other = segments[prior]!;
|
|
194
|
+
const otherEnd = other.destination + other.length;
|
|
195
|
+
if (segment.destination < otherEnd && other.destination < end)
|
|
196
|
+
throw new RangeError(`expert segment ${index} overlaps segment ${prior}`);
|
|
197
|
+
}
|
|
198
|
+
files[index] = segment.file;
|
|
199
|
+
offsets[index] = BigInt(segment.offset);
|
|
200
|
+
destinations[index] = BigInt(segment.destination);
|
|
201
|
+
lengths[index] = BigInt(segment.length);
|
|
202
|
+
extent = Math.max(extent, end);
|
|
203
|
+
}
|
|
204
|
+
if (extent > this.slotBytes)
|
|
205
|
+
throw new RangeError("expert segmented read exceeds slot capacity");
|
|
206
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_submitv(
|
|
207
|
+
this.#handle,
|
|
208
|
+
slot,
|
|
209
|
+
generation,
|
|
210
|
+
ffiPtr(files),
|
|
211
|
+
ffiPtr(offsets),
|
|
212
|
+
ffiPtr(destinations),
|
|
213
|
+
ffiPtr(lengths),
|
|
214
|
+
segments.length,
|
|
215
|
+
);
|
|
216
|
+
if (status !== 0)
|
|
217
|
+
throw new Error(`expert segmented read submit failed: errno ${status}`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async wait(slot: number, generation: bigint): Promise<void> {
|
|
221
|
+
await _pollExpertReadUntilReady(
|
|
222
|
+
() => this.#checkSlot(slot),
|
|
223
|
+
() => this.#lib.symbols.mlx_bun_expert_io_poll(this.#handle, slot, generation),
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Queue advisory readahead on the dedicated hint worker. No slab is used. */
|
|
228
|
+
hintSegments(segments: readonly ExpertIOHintSegment[]): boolean {
|
|
229
|
+
this.#checkOpen();
|
|
230
|
+
if (segments.length === 0 || segments.length > MAX_SEGMENTS)
|
|
231
|
+
throw new RangeError(`expert hint requires 1..${MAX_SEGMENTS} segments`);
|
|
232
|
+
const files = new Uint32Array(segments.length);
|
|
233
|
+
const offsets = new BigUint64Array(segments.length);
|
|
234
|
+
const lengths = new BigUint64Array(segments.length);
|
|
235
|
+
for (let index = 0; index < segments.length; index++) {
|
|
236
|
+
const segment = segments[index]!;
|
|
237
|
+
if (!Number.isSafeInteger(segment.file) || segment.file < 0 ||
|
|
238
|
+
segment.file >= this.files.length)
|
|
239
|
+
throw new RangeError(`expert hint ${index} file is out of range`);
|
|
240
|
+
if (!Number.isSafeInteger(segment.offset) || segment.offset < 0)
|
|
241
|
+
throw new RangeError(`expert hint ${index} offset must be non-negative`);
|
|
242
|
+
if (!Number.isSafeInteger(segment.length) || segment.length <= 0)
|
|
243
|
+
throw new RangeError(`expert hint ${index} length must be positive`);
|
|
244
|
+
files[index] = segment.file;
|
|
245
|
+
offsets[index] = BigInt(segment.offset);
|
|
246
|
+
lengths[index] = BigInt(segment.length);
|
|
247
|
+
}
|
|
248
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_hintv(
|
|
249
|
+
this.#handle,
|
|
250
|
+
ffiPtr(files),
|
|
251
|
+
ffiPtr(offsets),
|
|
252
|
+
ffiPtr(lengths),
|
|
253
|
+
segments.length,
|
|
254
|
+
);
|
|
255
|
+
if (status === 0) return true;
|
|
256
|
+
if (status === EAGAIN) return false;
|
|
257
|
+
throw new Error(`expert hint submit failed: errno ${status}`);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
hintTelemetry(): ExpertIOHintSnapshot {
|
|
261
|
+
this.#checkOpen();
|
|
262
|
+
const out = new BigUint64Array(HINT_STATS);
|
|
263
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_hint_stats(
|
|
264
|
+
this.#handle,
|
|
265
|
+
ffiPtr(out),
|
|
266
|
+
out.length,
|
|
267
|
+
);
|
|
268
|
+
if (status !== 0)
|
|
269
|
+
throw new Error(`expert hint telemetry failed: errno ${status}`);
|
|
270
|
+
return {
|
|
271
|
+
submitted: Number(out[0]),
|
|
272
|
+
completed: Number(out[1]),
|
|
273
|
+
dropped: Number(out[2]),
|
|
274
|
+
operations: Number(out[3]),
|
|
275
|
+
bytes: Number(out[4]),
|
|
276
|
+
errors: Number(out[5]),
|
|
277
|
+
queueDepth: Number(out[6]),
|
|
278
|
+
inFlight: Number(out[7]),
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
cancel(slot: number, generation: bigint): void {
|
|
283
|
+
this.#checkSlot(slot);
|
|
284
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_cancel(this.#handle, slot, generation);
|
|
285
|
+
if (status !== 0) throw new Error(`expert read cancel failed: errno ${status}`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
lease(slot: number, generation: bigint, consumer: "cpu" | "gpu" = "cpu"): void {
|
|
289
|
+
this.#checkSlot(slot);
|
|
290
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_lease(this.#handle, slot, generation, consumer === "gpu" ? 1 : 0);
|
|
291
|
+
if (status !== 0) throw new Error(`expert slot lease failed: errno ${status}`);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
releaseCpu(slot: number, generation: bigint): void {
|
|
295
|
+
this.#checkSlot(slot);
|
|
296
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_release(this.#handle, slot, generation, 0);
|
|
297
|
+
if (status !== 0) throw new Error(`expert slot release failed: errno ${status}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
releaseGpuFenced(slot: number, generation: bigint): void {
|
|
301
|
+
this.#checkSlot(slot);
|
|
302
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_release(this.#handle, slot, generation, 1);
|
|
303
|
+
if (status !== 0) throw new Error(`expert GPU slot release failed: errno ${status}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async releaseAfterGpuSync(
|
|
307
|
+
slot: number, generation: bigint, dependentOutputs: readonly MlxArray[], stream?: MlxHandle,
|
|
308
|
+
): Promise<void> {
|
|
309
|
+
this.#checkSlot(slot);
|
|
310
|
+
if (dependentOutputs.length === 0) throw new Error("GPU slot release requires dependent outputs to evaluate");
|
|
311
|
+
const [{ gpuStream }, { synchronize }, ops] = await Promise.all([
|
|
312
|
+
import("./mlx/array"), import("./mlx/ffi"), import("./mlx/ops"),
|
|
313
|
+
]);
|
|
314
|
+
ops.evalAll([...dependentOutputs]);
|
|
315
|
+
synchronize(stream ?? gpuStream);
|
|
316
|
+
this.releaseGpuFenced(slot, generation);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
discard(slot: number, generation: bigint): void {
|
|
320
|
+
this.#checkSlot(slot);
|
|
321
|
+
const status = this.#lib.symbols.mlx_bun_expert_io_discard(this.#handle, slot, generation);
|
|
322
|
+
if (status !== 0) throw new Error(`expert slot discard failed: errno ${status}`);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
physicalFootprint(): number {
|
|
326
|
+
this.#checkOpen();
|
|
327
|
+
return Number(this.#lib.symbols.mlx_bun_process_phys_footprint());
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
compressedMemory(): number {
|
|
331
|
+
this.#checkOpen();
|
|
332
|
+
return Number(this.#lib.symbols.mlx_bun_process_compressed());
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
pointer(slot: number, generation: bigint): number {
|
|
336
|
+
this.#checkSlot(slot);
|
|
337
|
+
const result = Number(this.#lib.symbols.mlx_bun_expert_io_ptr(this.#handle, slot, generation));
|
|
338
|
+
if (!result) throw new Error("expert slot pointer requires the matching active lease");
|
|
339
|
+
return result;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
view(slot: number, generation: bigint, length?: number): Uint8Array {
|
|
343
|
+
this.#checkSlot(slot);
|
|
344
|
+
const resolvedLength = length ?? Number(this.#lib.symbols.mlx_bun_expert_io_length(this.#handle, slot, generation));
|
|
345
|
+
if (resolvedLength < 0 || resolvedLength > this.slotBytes) throw new RangeError("expert slot view exceeds capacity");
|
|
346
|
+
return new Uint8Array(toArrayBuffer(this.pointer(slot, generation) as never, 0, resolvedLength));
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
close(): void {
|
|
350
|
+
if (this.#state === "closed") return;
|
|
351
|
+
if (this.#state === "closing") return;
|
|
352
|
+
this.#state = "closing";
|
|
353
|
+
let status: number;
|
|
354
|
+
try {
|
|
355
|
+
status = this.#lib.symbols.mlx_bun_expert_io_close(this.#handle);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
this.#state = "open";
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
if (status !== 0) {
|
|
361
|
+
this.#state = "open";
|
|
362
|
+
throw new Error(`expert slab close failed: errno ${status}`);
|
|
363
|
+
}
|
|
364
|
+
this.#state = "closed";
|
|
365
|
+
this.#lib.close();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
#checkSlot(slot: number): void {
|
|
369
|
+
this.#checkOpen();
|
|
370
|
+
if (!Number.isInteger(slot) || slot < 0 || slot >= this.slots) throw new RangeError("expert slot out of range");
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
#checkOpen(): void {
|
|
374
|
+
if (this.#state !== "open") throw new Error("expert slab store is closed");
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export { EBUSY as EXPERT_IO_BUSY_ERRNO };
|
|
379
|
+
|
|
380
|
+
export interface LruCandidate { slot: number; lastUse: bigint; pinned?: boolean; leased?: boolean }
|
|
381
|
+
|
|
382
|
+
/** Deterministic eviction primitive: oldest use wins, then lowest slot ID. */
|
|
383
|
+
export function selectExpertLruVictim(candidates: readonly LruCandidate[]): number | null {
|
|
384
|
+
let best: LruCandidate | null = null;
|
|
385
|
+
for (const candidate of candidates) {
|
|
386
|
+
if (candidate.pinned || candidate.leased) continue;
|
|
387
|
+
if (!best || candidate.lastUse < best.lastUse ||
|
|
388
|
+
(candidate.lastUse === best.lastUse && candidate.slot < best.slot)) best = candidate;
|
|
389
|
+
}
|
|
390
|
+
return best?.slot ?? null;
|
|
391
|
+
}
|