mlx-bun 0.0.4
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/LICENSE +21 -0
- package/README.md +362 -0
- package/THIRD_PARTY_LICENSES.md +41 -0
- package/bin/mlx-bun.mjs +32 -0
- package/docs/curve-designer.html +303 -0
- package/docs/design/adapters-end-to-end.md +201 -0
- package/docs/design/compat-cli-surface-design.md +227 -0
- package/docs/design/docs-reorg-plan.md +152 -0
- package/docs/design/hlg-sampling.md +340 -0
- package/docs/design/memory-system.md +339 -0
- package/docs/design/optimization_plan.md +344 -0
- package/docs/design/parallel-slots.md +515 -0
- package/docs/design/runtime-isolation.md +247 -0
- package/docs/design/segmented-backward-training.md +508 -0
- package/docs/investigations/chunk-finetune-experiment.md +84 -0
- package/docs/investigations/curve-bisector-routing.md +123 -0
- package/docs/investigations/curve-runs/bisector-route.json +98 -0
- package/docs/investigations/curve-runs/bisector-trace.json +1393 -0
- package/docs/investigations/curve-runs/curve-terrain.json +1179 -0
- package/docs/investigations/curve-runs/curve-terrain.svg +42 -0
- package/docs/investigations/curve-terrain.html +105 -0
- package/docs/investigations/expert-offload-single-user-moe.md +292 -0
- package/docs/investigations/hlg-ab.html +34 -0
- package/docs/investigations/hlg-explorer.html +238 -0
- package/docs/investigations/hlg-figs/cliff.svg +1 -0
- package/docs/investigations/hlg-figs/cross.svg +1 -0
- package/docs/investigations/hlg-figs/edges.svg +1 -0
- package/docs/investigations/hlg-figs/k20-grids.svg +1 -0
- package/docs/investigations/hlg-figs/k20-peaks.svg +1 -0
- package/docs/investigations/hlg-figs/lw-curve.svg +1 -0
- package/docs/investigations/hlg-figs/terrain.svg +1 -0
- package/docs/investigations/hlg-report.html +262 -0
- package/docs/investigations/hlg-runs/hlg-ab.json +149 -0
- package/docs/investigations/hlg-runs/hlg-blind-prompts.md +87 -0
- package/docs/investigations/hlg-runs/hlg-blind.json +107 -0
- package/docs/investigations/hlg-runs/hlg-cliff.json +197 -0
- package/docs/investigations/hlg-runs/hlg-cross.json +505 -0
- package/docs/investigations/hlg-runs/hlg-edge.json +388 -0
- package/docs/investigations/hlg-runs/hlg-eval1.json +25 -0
- package/docs/investigations/hlg-runs/hlg-frontier.json +86 -0
- package/docs/investigations/hlg-runs/hlg-grid.json +242 -0
- package/docs/investigations/hlg-runs/hlg-grid2.json +343 -0
- package/docs/investigations/hlg-runs/hlg-lw-coarse.json +110 -0
- package/docs/investigations/hlg-runs/hlg-map.json +383 -0
- package/docs/investigations/hlg-runs/run0-original.log +159 -0
- package/docs/investigations/hlg-runs/runA-recommended.log +131 -0
- package/docs/investigations/hlg-runs/runAA-cliff-cpm5.log +26 -0
- package/docs/investigations/hlg-runs/runAB-grid2-e4b.log +18 -0
- package/docs/investigations/hlg-runs/runAC-peak-e4b-partial.log +25 -0
- package/docs/investigations/hlg-runs/runAD-ab-samples.log +8 -0
- package/docs/investigations/hlg-runs/runAE-edge-e4b.log +51 -0
- package/docs/investigations/hlg-runs/runAF-logit-calibration.log +10 -0
- package/docs/investigations/hlg-runs/runAG-eval-config2.log +16 -0
- package/docs/investigations/hlg-runs/runB-gain-variants.log +192 -0
- package/docs/investigations/hlg-runs/runC-pivots.log +162 -0
- package/docs/investigations/hlg-runs/runD-oetf.log +132 -0
- package/docs/investigations/hlg-runs/runE-eotf.log +162 -0
- package/docs/investigations/hlg-runs/runF-shaper-working.log +86 -0
- package/docs/investigations/hlg-runs/runG-shaper-sweep.log +101 -0
- package/docs/investigations/hlg-runs/runH-wsweep.log +176 -0
- package/docs/investigations/hlg-runs/runI-asweep.log +176 -0
- package/docs/investigations/hlg-runs/runJ-knobmap.log +49 -0
- package/docs/investigations/hlg-runs/runK-frontier.log +19 -0
- package/docs/investigations/hlg-runs/runL-widemap.log +65 -0
- package/docs/investigations/hlg-runs/runM-frontier-emb.log +15 -0
- package/docs/investigations/hlg-runs/runN-verify.log +116 -0
- package/docs/investigations/hlg-runs/runO-frontier-seed5000.log +15 -0
- package/docs/investigations/hlg-runs/runP-grid-AxSm.log +15 -0
- package/docs/investigations/hlg-runs/runQ-grid-tgW.log +15 -0
- package/docs/investigations/hlg-runs/runR-blind-transcript.log +79 -0
- package/docs/investigations/hlg-runs/runS-cross-coherence.log +33 -0
- package/docs/investigations/hlg-runs/runT-cross-cpm5.log +33 -0
- package/docs/investigations/hlg-runs/runU-cross-12b.log +33 -0
- package/docs/investigations/hlg-runs/runV-lw-e4b.log +22 -0
- package/docs/investigations/hlg-runs/runW-lw-12b.log +22 -0
- package/docs/investigations/hlg-runs/runX-lw-cpm5.log +22 -0
- package/docs/investigations/hlg-runs/runY-cliff-e4b.log +26 -0
- package/docs/investigations/hlg-runs/runZ-cliff-12b.log +26 -0
- package/docs/investigations/hlg-sampling-investigation.md +970 -0
- package/docs/investigations/lab-build-journal.md +157 -0
- package/docs/investigations/pi-builtin-investigation.md +308 -0
- package/docs/investigations/starter-model-port-handoff.md +323 -0
- package/docs/planning/IDEAS.md +26 -0
- package/docs/planning/PRODUCT_ROADMAP.md +426 -0
- package/docs/planning/ResearchTopics.md +119 -0
- package/docs/planning/chunk-task-roadmap.md +77 -0
- package/docs/planning/journal.md +155 -0
- package/docs/reference/distribution.md +121 -0
- package/docs/reference/embedding.md +168 -0
- package/docs/reference/library-api.md +153 -0
- package/docs/reference/server-api.md +224 -0
- package/docs/reference/server-config.md +243 -0
- package/docs/segmented-backward-handoff.md +148 -0
- package/package.json +68 -0
- package/src/anthropic.ts +491 -0
- package/src/chat-template.ts +186 -0
- package/src/cli.ts +1075 -0
- package/src/config.ts +229 -0
- package/src/curve-sampler.ts +122 -0
- package/src/dataset/generators.ts +1087 -0
- package/src/dataset/index.ts +12 -0
- package/src/dataset/job.ts +81 -0
- package/src/dataset/llm.ts +71 -0
- package/src/dataset/registry.ts +528 -0
- package/src/download.ts +283 -0
- package/src/eval/README.md +86 -0
- package/src/eval/kl-prompts.ts +29 -0
- package/src/eval/kl.ts +294 -0
- package/src/eval/quality-db.ts +92 -0
- package/src/eval/runner.ts +102 -0
- package/src/eval/score.ts +49 -0
- package/src/eval/tasks/bfcl.ts +500 -0
- package/src/eval/tasks/gsm8k.ts +85 -0
- package/src/eval/tasks/hashhop.ts +109 -0
- package/src/eval/tasks/humaneval.ts +252 -0
- package/src/eval/tasks/ifeval.ts +354 -0
- package/src/eval/tasks/mmlu.ts +145 -0
- package/src/evaldb.ts +199 -0
- package/src/expert-offload-build.ts +77 -0
- package/src/expert-offload.ts +61 -0
- package/src/expert-trace.ts +67 -0
- package/src/fit.ts +254 -0
- package/src/generate.ts +451 -0
- package/src/harness-pi.ts +177 -0
- package/src/hf-push.ts +628 -0
- package/src/index.ts +22 -0
- package/src/jobs/db.ts +139 -0
- package/src/jobs/index.ts +29 -0
- package/src/jobs/job-entry.ts +106 -0
- package/src/jobs/runner.ts +304 -0
- package/src/jobs/sse.ts +114 -0
- package/src/jobs/types.ts +58 -0
- package/src/kv-store.ts +185 -0
- package/src/lora.ts +314 -0
- package/src/md-modules.d.ts +7 -0
- package/src/mlx/array.ts +237 -0
- package/src/mlx/autograd.ts +267 -0
- package/src/mlx/checkpoint.ts +116 -0
- package/src/mlx/compile.ts +158 -0
- package/src/mlx/custom-vjp.ts +140 -0
- package/src/mlx/ffi.ts +433 -0
- package/src/mlx/metal-kernel.ts +130 -0
- package/src/mlx/ops.ts +707 -0
- package/src/mmap.ts +90 -0
- package/src/model/batched-mask.ts +204 -0
- package/src/model/batched-rotating.ts +300 -0
- package/src/model/compiled-decode.ts +681 -0
- package/src/model/factory.ts +27 -0
- package/src/model/fingerprint.ts +33 -0
- package/src/model/flash-attention.ts +674 -0
- package/src/model/fused-decode-kernel.ts +305 -0
- package/src/model/fused-geglu-kernel.ts +87 -0
- package/src/model/gemma4-base.ts +1616 -0
- package/src/model/gemma4.ts +1012 -0
- package/src/model/generated/gemma4-12b.ts +526 -0
- package/src/model/generated/gemma4-26b.ts +500 -0
- package/src/model/generated/gemma4-e4b.ts +757 -0
- package/src/model/generated/index.ts +18 -0
- package/src/model/minicpm5.ts +278 -0
- package/src/model/qwen3-delta.ts +224 -0
- package/src/model/qwen3_5.ts +429 -0
- package/src/model/support.ts +46 -0
- package/src/native-pack.ts +152 -0
- package/src/pi-provider.ts +95 -0
- package/src/pi-terminal.ts +264 -0
- package/src/pi-web.ts +924 -0
- package/src/preflight.ts +123 -0
- package/src/prompt-cache.ts +113 -0
- package/src/quantize/allocator.ts +627 -0
- package/src/quantize/calibration.ts +180 -0
- package/src/quantize/config-writer.ts +132 -0
- package/src/quantize/index.ts +57 -0
- package/src/quantize/job.ts +136 -0
- package/src/quantize/quantizer.ts +462 -0
- package/src/quantize/safetensors-writer.ts +171 -0
- package/src/quantize/sensitivity.ts +234 -0
- package/src/registry.ts +336 -0
- package/src/responses.ts +774 -0
- package/src/safetensors.ts +158 -0
- package/src/sampler.ts +517 -0
- package/src/serve/batch-scheduler.ts +362 -0
- package/src/serve/generation-gateway.ts +160 -0
- package/src/server.ts +1891 -0
- package/src/spec/drafter.ts +261 -0
- package/src/spec/generate.ts +221 -0
- package/src/status-page.html +497 -0
- package/src/tokenizer.ts +38 -0
- package/src/tool-call.ts +242 -0
- package/src/train/dataset.ts +461 -0
- package/src/train/export.ts +32 -0
- package/src/train/forward.ts +229 -0
- package/src/train/index.ts +43 -0
- package/src/train/job.ts +148 -0
- package/src/train/lora-params.ts +194 -0
- package/src/train/loss.ts +342 -0
- package/src/train/merge.ts +195 -0
- package/src/train/optimizer.ts +176 -0
- package/src/train/rank.ts +101 -0
- package/src/train/segmented.ts +520 -0
- package/src/train/trainer.ts +600 -0
- package/src/tui.ts +161 -0
- package/src/vision/embedder.ts +168 -0
- package/src/vision/preprocess.ts +247 -0
- package/src/vision/prompt.ts +158 -0
- package/src/vision/siglip.ts +599 -0
- package/src/web/app.html +2471 -0
- package/src/web/skills/web-research/SKILL.md +44 -0
- package/src/web/skills.ts +59 -0
- package/src/web-tools.ts +426 -0
- package/src/weights.ts +91 -0
package/src/mlx/array.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// MlxArray: ownership wrapper around an mlx_array handle.
|
|
2
|
+
// Explicit .dispose() is the contract; a FinalizationRegistry backstop
|
|
3
|
+
// frees leaked handles on GC (verified in spikes/phase0-memory.ts).
|
|
4
|
+
|
|
5
|
+
import { JSCallback, ptr, toArrayBuffer } from "bun:ffi";
|
|
6
|
+
import { C, Dtype, DTYPE_NAMES, type MlxHandle, optInt, outArray, takeMlxError } from "./ffi";
|
|
7
|
+
import type { SafetensorsDtype } from "../safetensors";
|
|
8
|
+
|
|
9
|
+
export const gpuStream: MlxHandle = C.mlx_default_gpu_stream_new();
|
|
10
|
+
export const cpuStream: MlxHandle = C.mlx_default_cpu_stream_new();
|
|
11
|
+
|
|
12
|
+
/** Shape buffer for FFI; ptr() rejects empty views, so 0-d arrays pass a
|
|
13
|
+
* dummy buffer with dim=0 (the pointee is never read). */
|
|
14
|
+
function shapeBuf(shape: number[]): Int32Array {
|
|
15
|
+
return shape.length === 0 ? new Int32Array(1) : new Int32Array(shape);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const SAFETENSORS_TO_MLX: Record<SafetensorsDtype, Dtype> = {
|
|
19
|
+
BOOL: Dtype.bool, U8: Dtype.uint8, I8: Dtype.int8,
|
|
20
|
+
U16: Dtype.uint16, I16: Dtype.int16, U32: Dtype.uint32, I32: Dtype.int32,
|
|
21
|
+
U64: Dtype.uint64, I64: Dtype.int64,
|
|
22
|
+
F16: Dtype.float16, BF16: Dtype.bfloat16, F32: Dtype.float32, F64: Dtype.float64,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// --- zero-copy pinning ---------------------------------------------------
|
|
26
|
+
// Buffers handed to mlx via new_data_managed_payload must outlive the mlx
|
|
27
|
+
// array. We pin the JS view in a map keyed by a payload id; the shared dtor
|
|
28
|
+
// callback unpins when mlx drops its last reference. threadsafe: mlx may
|
|
29
|
+
// release buffers from its eval thread.
|
|
30
|
+
|
|
31
|
+
const pinned = new Map<number, Uint8Array>();
|
|
32
|
+
let nextPinId = 1;
|
|
33
|
+
|
|
34
|
+
const unpinCallback = new JSCallback(
|
|
35
|
+
(payloadId: number) => { pinned.delete(payloadId); },
|
|
36
|
+
{ args: ["u64"], returns: "void", threadsafe: true },
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
export function pinnedBufferCount(): number {
|
|
40
|
+
return pinned.size;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// --- finalization backstop ----------------------------------------------
|
|
44
|
+
|
|
45
|
+
const registry = new FinalizationRegistry((handle: MlxHandle) => {
|
|
46
|
+
C.mlx_array_free(handle);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export class MlxArray {
|
|
50
|
+
#handle: MlxHandle;
|
|
51
|
+
#disposed = false;
|
|
52
|
+
#token = {};
|
|
53
|
+
|
|
54
|
+
constructor(handle: MlxHandle) {
|
|
55
|
+
this.#handle = handle;
|
|
56
|
+
registry.register(this, handle, this.#token);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Zero-copy: wrap an existing buffer (e.g. an mmap view). The view is
|
|
60
|
+
* pinned until mlx releases it. */
|
|
61
|
+
static fromView(view: Uint8Array, shape: number[], dtype: Dtype): MlxArray {
|
|
62
|
+
const sb = shapeBuf(shape);
|
|
63
|
+
const id = nextPinId++;
|
|
64
|
+
pinned.set(id, view);
|
|
65
|
+
const handle = C.mlx_array_new_data_managed_payload(
|
|
66
|
+
ptr(view), ptr(sb), shape.length, dtype, id, unpinCallback.ptr,
|
|
67
|
+
);
|
|
68
|
+
return new MlxArray(handle);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Zero-copy: wrap a raw pointer (e.g. into an mmap'd weight shard).
|
|
72
|
+
* The caller guarantees the memory outlives the array — weight mmaps
|
|
73
|
+
* live for the process, so the dtor is a no-op unpin of id 0. */
|
|
74
|
+
static fromPointer(dataPtr: number, shape: number[], dtype: Dtype): MlxArray {
|
|
75
|
+
const sb = shapeBuf(shape);
|
|
76
|
+
const handle = C.mlx_array_new_data_managed_payload(
|
|
77
|
+
dataPtr, ptr(sb), shape.length, dtype, 0, unpinCallback.ptr,
|
|
78
|
+
);
|
|
79
|
+
return new MlxArray(handle);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Copying constructor for small host data. */
|
|
83
|
+
static fromFloat32(data: Float32Array, shape: number[]): MlxArray {
|
|
84
|
+
const sb = shapeBuf(shape);
|
|
85
|
+
return new MlxArray(
|
|
86
|
+
C.mlx_array_new_data(ptr(data), ptr(sb), shape.length, Dtype.float32),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Copy raw bytes into a fresh mlx-managed (page-aligned) LEAF array of the
|
|
91
|
+
* given dtype/shape. Unlike fromView (which no-copy-wraps the host buffer and
|
|
92
|
+
* is unsafe to feed to GPU ops when unaligned), mlx_array_new_data COPIES, so
|
|
93
|
+
* the source bytes need not outlive the array and GPU ops are safe. Used to
|
|
94
|
+
* detach a value from its computation graph: `MlxArray.fromBytesCopy(
|
|
95
|
+
* x.rawBytes(), x.shape, x.dtype)` yields a graph-free leaf with x's exact
|
|
96
|
+
* bytes (segmented-backward boundaries — src/train/segmented.ts). */
|
|
97
|
+
static fromBytesCopy(bytes: Uint8Array, shape: number[], dtype: Dtype): MlxArray {
|
|
98
|
+
const sb = shapeBuf(shape);
|
|
99
|
+
return new MlxArray(
|
|
100
|
+
C.mlx_array_new_data(ptr(bytes), ptr(sb), shape.length, dtype),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
static fromInt32(data: Int32Array, shape: number[]): MlxArray {
|
|
105
|
+
const sb = shapeBuf(shape);
|
|
106
|
+
return new MlxArray(
|
|
107
|
+
C.mlx_array_new_data(ptr(data), ptr(sb), shape.length, Dtype.int32),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
get handle(): MlxHandle {
|
|
112
|
+
if (this.#disposed) throw new Error("MlxArray used after dispose");
|
|
113
|
+
return this.#handle;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
get ndim(): number {
|
|
117
|
+
return Number(C.mlx_array_ndim(this.handle));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// NOTE on the DFG stale-read bug (repro/bun-ffi-f64/ISSUE.md): the
|
|
121
|
+
// toArrayBuffer readbacks below (shape/rawBytes/toFloat32) are safe.
|
|
122
|
+
// The hazard is reading a *pre-existing* typed array after an FFI call
|
|
123
|
+
// wrote through its pointer — the JIT forwards a stale value from before
|
|
124
|
+
// the call. Here the view is constructed *after* the call, from the
|
|
125
|
+
// pointer the call returned: the loads are data-dependent on the call
|
|
126
|
+
// result and there is no prior JS load/store to forward from.
|
|
127
|
+
|
|
128
|
+
get shape(): number[] {
|
|
129
|
+
const n = this.ndim;
|
|
130
|
+
if (n === 0) return [];
|
|
131
|
+
const shapePtr = C.mlx_array_shape(this.handle);
|
|
132
|
+
return [...new Int32Array(toArrayBuffer(shapePtr!, 0, n * 4))];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
get dtype(): Dtype {
|
|
136
|
+
return C.mlx_array_dtype(this.handle) as Dtype;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
get dtypeName(): string {
|
|
140
|
+
return DTYPE_NAMES[this.dtype] ?? `unknown(${this.dtype})`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
get size(): number {
|
|
144
|
+
return Number(C.mlx_array_size(this.handle));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
get nbytes(): number {
|
|
148
|
+
return Number(C.mlx_array_nbytes(this.handle));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
eval(): this {
|
|
152
|
+
if (C.mlx_array_eval(this.handle) !== 0) throw new Error(`mlx_array_eval failed: ${takeMlxError() ?? ""}`);
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Cast to another dtype (lazy). */
|
|
157
|
+
astype(dtype: Dtype, stream: MlxHandle = gpuStream): MlxArray {
|
|
158
|
+
return new MlxArray(
|
|
159
|
+
outArray("astype", (slot) => C.mlx_astype(slot, this.handle, dtype, stream)),
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Raw bytes of the evaluated array (copy). bf16/f16/f32 only. */
|
|
164
|
+
rawBytes(): Uint8Array {
|
|
165
|
+
this.eval();
|
|
166
|
+
const dt = this.dtype;
|
|
167
|
+
const p =
|
|
168
|
+
dt === Dtype.float32 ? C.mlx_array_data_float32(this.handle)
|
|
169
|
+
: dt === Dtype.float16 ? C.mlx_array_data_float16(this.handle)
|
|
170
|
+
: dt === Dtype.bfloat16 ? C.mlx_array_data_bfloat16(this.handle)
|
|
171
|
+
: dt === Dtype.uint32 ? C.mlx_array_data_uint32(this.handle)
|
|
172
|
+
: null;
|
|
173
|
+
if (p === null) throw new Error(`rawBytes: unsupported dtype ${this.dtypeName}`);
|
|
174
|
+
return new Uint8Array(toArrayBuffer(p!, 0, this.nbytes)).slice();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Read back as float32 (casts on GPU if needed, then copies out). */
|
|
178
|
+
toFloat32(): Float32Array {
|
|
179
|
+
const src = this.dtype === Dtype.float32 ? this : this.astype(Dtype.float32);
|
|
180
|
+
src.eval();
|
|
181
|
+
const dataPtr = C.mlx_array_data_float32(src.handle);
|
|
182
|
+
const out = new Float32Array(toArrayBuffer(dataPtr!, 0, src.size * 4)).slice();
|
|
183
|
+
if (src !== this) src.dispose();
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Basic slice: start/stop per dimension (stride 1). */
|
|
188
|
+
slice(start: number[], stop: number[], stream: MlxHandle = gpuStream): MlxArray {
|
|
189
|
+
const s = new Int32Array(start);
|
|
190
|
+
const e = new Int32Array(stop);
|
|
191
|
+
const strides = new Int32Array(start.map(() => 1));
|
|
192
|
+
return new MlxArray(
|
|
193
|
+
outArray("slice", (slot) =>
|
|
194
|
+
C.mlx_slice(
|
|
195
|
+
slot, this.handle,
|
|
196
|
+
ptr(s), BigInt(s.length), ptr(e), BigInt(e.length),
|
|
197
|
+
ptr(strides), BigInt(strides.length), stream,
|
|
198
|
+
),
|
|
199
|
+
),
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
add(other: MlxArray, stream: MlxHandle = gpuStream): MlxArray {
|
|
204
|
+
return new MlxArray(
|
|
205
|
+
outArray("add", (slot) => C.mlx_add(slot, this.handle, other.handle, stream)),
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Dequantize (w, scales, biases) → full precision. */
|
|
210
|
+
static dequantize(
|
|
211
|
+
w: MlxArray, scales: MlxArray, biases: MlxArray | null,
|
|
212
|
+
groupSize: number, bits: number, mode = "affine",
|
|
213
|
+
stream: MlxHandle = gpuStream,
|
|
214
|
+
): MlxArray {
|
|
215
|
+
const modeBuf = Buffer.from(mode + "\0", "utf8");
|
|
216
|
+
return new MlxArray(
|
|
217
|
+
outArray("dequantize", (slot) =>
|
|
218
|
+
C.mlx_dequantize(
|
|
219
|
+
slot, w.handle, scales.handle, biases?.handle ?? 0n,
|
|
220
|
+
optInt(groupSize), optInt(bits), ptr(modeBuf),
|
|
221
|
+
0n /* global_scale */, optInt(null) /* out dtype */, stream,
|
|
222
|
+
),
|
|
223
|
+
),
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
dispose(): void {
|
|
228
|
+
if (this.#disposed) return;
|
|
229
|
+
this.#disposed = true;
|
|
230
|
+
registry.unregister(this.#token);
|
|
231
|
+
C.mlx_array_free(this.#handle);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
[Symbol.dispose](): void {
|
|
235
|
+
this.dispose();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Native autograd via mlx-c value_and_grad over a JS loss closure.
|
|
2
|
+
//
|
|
3
|
+
// Encapsulates the exact FFI lifecycle proven in spikes/phase-train-vag.ts:
|
|
4
|
+
// JS loss closure (JSCallback) → mlx_closure_new_func_payload →
|
|
5
|
+
// mlx_value_and_grad → mlx_closure_value_and_grad_apply → read grads.
|
|
6
|
+
//
|
|
7
|
+
// House rules honored:
|
|
8
|
+
// - Out-params read via bun:ffi `read.u64` (never slot[0] — DFG stale-read).
|
|
9
|
+
// - The JS closure NEVER throws across the FFI boundary (try/catch → return 1);
|
|
10
|
+
// the captured error is re-thrown on the JS side after apply() fails.
|
|
11
|
+
// - All native handles (closure, value_and_grad closure, JSCallback) are held
|
|
12
|
+
// alive on the instance and freed in dispose().
|
|
13
|
+
|
|
14
|
+
import { JSCallback, ptr, read } from "bun:ffi";
|
|
15
|
+
import { C, takeMlxError } from "./ffi";
|
|
16
|
+
import { MlxArray } from "./array";
|
|
17
|
+
|
|
18
|
+
/** A reusable value-and-grad over a JS-built loss graph.
|
|
19
|
+
*
|
|
20
|
+
* `loss(primals)` receives the input arrays in argument order and must
|
|
21
|
+
* return a single SCALAR MlxArray (the loss). The graph it builds is
|
|
22
|
+
* differentiated w.r.t. the inputs named in `argIdx`. `apply(primals)`
|
|
23
|
+
* returns the loss value and exactly `argIdx.length` gradients (one per
|
|
24
|
+
* differentiated input, in `argIdx` order).
|
|
25
|
+
*
|
|
26
|
+
* The closure must not throw; if the user `loss` throws, the error is
|
|
27
|
+
* captured and surfaced from `apply()`. The MlxArrays handed to `loss`
|
|
28
|
+
* are owned by mlx — do NOT dispose them; the returned loss IS disposed
|
|
29
|
+
* of by mlx's graph. */
|
|
30
|
+
export class ValueAndGrad {
|
|
31
|
+
readonly #cb: JSCallback;
|
|
32
|
+
readonly #closure: bigint;
|
|
33
|
+
readonly #vag: bigint;
|
|
34
|
+
readonly #argIdx: Int32Array;
|
|
35
|
+
#closureError: string | null = null;
|
|
36
|
+
#disposed = false;
|
|
37
|
+
|
|
38
|
+
constructor(loss: (primals: MlxArray[]) => MlxArray, argIdx: number[]) {
|
|
39
|
+
if (argIdx.length === 0) throw new Error("ValueAndGrad: argIdx must be non-empty");
|
|
40
|
+
this.#argIdx = new Int32Array(argIdx);
|
|
41
|
+
|
|
42
|
+
this.#cb = new JSCallback(
|
|
43
|
+
(outPtr: number, inVec: bigint, _payload: number): number => {
|
|
44
|
+
try {
|
|
45
|
+
// Read the primals out of the input vector_array. mlx_vector_array_get
|
|
46
|
+
// returns a fresh (ref-counted) handle, so disposing the wrapper
|
|
47
|
+
// afterward is correct — it drops our reference, not mlx's graph
|
|
48
|
+
// reference (proven in spikes/phase-train-vag.ts).
|
|
49
|
+
const n = Number(C.mlx_vector_array_size(inVec));
|
|
50
|
+
const primals: MlxArray[] = [];
|
|
51
|
+
for (let i = 0; i < n; i++) {
|
|
52
|
+
const slot = new BigUint64Array([C.mlx_array_new()]);
|
|
53
|
+
const sp = ptr(slot);
|
|
54
|
+
if (C.mlx_vector_array_get(sp, inVec, BigInt(i)) !== 0)
|
|
55
|
+
throw new Error(`vector_array_get(${i}) failed`);
|
|
56
|
+
primals.push(new MlxArray(read.u64(sp, 0)));
|
|
57
|
+
}
|
|
58
|
+
const out = loss(primals);
|
|
59
|
+
// Populate *out with the single scalar loss. set_data copies the
|
|
60
|
+
// handle into the output vector (mlx retains its own reference), so
|
|
61
|
+
// disposing the loss wrapper afterward drops only our reference.
|
|
62
|
+
const handles = new BigUint64Array([out.handle]);
|
|
63
|
+
if (C.mlx_vector_array_set_data(outPtr as never, ptr(handles), 1n) !== 0)
|
|
64
|
+
throw new Error("vector_array_set_data failed");
|
|
65
|
+
for (const p of primals) p.dispose();
|
|
66
|
+
out.dispose();
|
|
67
|
+
return 0;
|
|
68
|
+
} catch (e) {
|
|
69
|
+
this.#closureError = e instanceof Error ? e.message : String(e);
|
|
70
|
+
return 1;
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
{ args: ["ptr", "u64", "ptr"], returns: "i32" },
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
this.#closure = C.mlx_closure_new_func_payload(this.#cb.ptr as never, null, null);
|
|
77
|
+
|
|
78
|
+
const vagSlot = new BigUint64Array([C.mlx_closure_value_and_grad_new()]);
|
|
79
|
+
if (C.mlx_value_and_grad(ptr(vagSlot), this.#closure, ptr(this.#argIdx), BigInt(this.#argIdx.length)) !== 0) {
|
|
80
|
+
// best-effort cleanup before throwing
|
|
81
|
+
C.mlx_closure_free(this.#closure);
|
|
82
|
+
this.#cb.close();
|
|
83
|
+
throw new Error("mlx_value_and_grad failed");
|
|
84
|
+
}
|
|
85
|
+
this.#vag = read.u64(ptr(vagSlot), 0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Run the loss + backward on `primals` (in argument order). Returns the
|
|
89
|
+
* scalar loss and one gradient per differentiated input. Caller owns all
|
|
90
|
+
* returned arrays (dispose them). */
|
|
91
|
+
apply(primals: MlxArray[]): { value: MlxArray; grads: MlxArray[] } {
|
|
92
|
+
if (this.#disposed) throw new Error("ValueAndGrad used after dispose");
|
|
93
|
+
this.#closureError = null;
|
|
94
|
+
|
|
95
|
+
const handles = new BigUint64Array(primals.map((p) => p.handle));
|
|
96
|
+
const inVec = C.mlx_vector_array_new_data(ptr(handles), BigInt(primals.length));
|
|
97
|
+
|
|
98
|
+
const valueSlot = new BigUint64Array([C.mlx_vector_array_new()]);
|
|
99
|
+
const gradsSlot = new BigUint64Array([C.mlx_vector_array_new()]);
|
|
100
|
+
const st = C.mlx_closure_value_and_grad_apply(ptr(valueSlot), ptr(gradsSlot), this.#vag, inVec);
|
|
101
|
+
const valueVec = read.u64(ptr(valueSlot), 0);
|
|
102
|
+
const gradsVec = read.u64(ptr(gradsSlot), 0);
|
|
103
|
+
if (st !== 0) {
|
|
104
|
+
C.mlx_vector_array_free(valueVec);
|
|
105
|
+
C.mlx_vector_array_free(gradsVec);
|
|
106
|
+
C.mlx_vector_array_free(inVec);
|
|
107
|
+
// Surface whichever error fired: a JS throw inside the loss closure
|
|
108
|
+
// (#closureError) or MLX's own C-level error (takeMlxError) — e.g. a
|
|
109
|
+
// missing vjp for an op in the forward graph. Discarding the latter
|
|
110
|
+
// turned an "unsupported gradient" into an opaque failure.
|
|
111
|
+
const mlxErr = takeMlxError();
|
|
112
|
+
const detail = this.#closureError ?? mlxErr ?? "";
|
|
113
|
+
throw new Error(`value_and_grad_apply failed${detail ? `: ${detail}` : ""}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// value vector has exactly one entry (the scalar loss).
|
|
117
|
+
const value = vecGet(valueVec, 0);
|
|
118
|
+
|
|
119
|
+
const nGrads = Number(C.mlx_vector_array_size(gradsVec));
|
|
120
|
+
if (nGrads !== this.#argIdx.length) {
|
|
121
|
+
value.dispose();
|
|
122
|
+
C.mlx_vector_array_free(valueVec);
|
|
123
|
+
C.mlx_vector_array_free(gradsVec);
|
|
124
|
+
C.mlx_vector_array_free(inVec);
|
|
125
|
+
throw new Error(`expected ${this.#argIdx.length} grads, got ${nGrads}`);
|
|
126
|
+
}
|
|
127
|
+
const grads: MlxArray[] = [];
|
|
128
|
+
for (let i = 0; i < nGrads; i++) grads.push(vecGet(gradsVec, i));
|
|
129
|
+
|
|
130
|
+
C.mlx_vector_array_free(valueVec);
|
|
131
|
+
C.mlx_vector_array_free(gradsVec);
|
|
132
|
+
C.mlx_vector_array_free(inVec);
|
|
133
|
+
return { value, grads };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
dispose(): void {
|
|
137
|
+
if (this.#disposed) return;
|
|
138
|
+
this.#disposed = true;
|
|
139
|
+
C.mlx_closure_value_and_grad_free(this.#vag);
|
|
140
|
+
C.mlx_closure_free(this.#closure);
|
|
141
|
+
this.#cb.close();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
[Symbol.dispose](): void {
|
|
145
|
+
this.dispose();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Pull array `i` out of a vector_array into an owned MlxArray wrapper. */
|
|
150
|
+
function vecGet(vec: bigint, i: number): MlxArray {
|
|
151
|
+
const slot = new BigUint64Array([C.mlx_array_new()]);
|
|
152
|
+
const sp = ptr(slot);
|
|
153
|
+
if (C.mlx_vector_array_get(sp, vec, BigInt(i)) !== 0)
|
|
154
|
+
throw new Error(`vector_array_get(${i}) failed`);
|
|
155
|
+
return new MlxArray(read.u64(sp, 0));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Reverse-mode AD via mlx_vjp: given a function `fn(primals) -> outputs` and a
|
|
159
|
+
* cotangent per output, returns the cotangent w.r.t. EVERY primal. This is the
|
|
160
|
+
* natural primitive for segmented backward (segment forward + dh -> [dh_in,
|
|
161
|
+
* ...dLoRA]) — no surrogate scalar and no value_and_grad closure. Unlike
|
|
162
|
+
* ValueAndGrad it returns a vjp for ALL primals (not a selected argnum subset).
|
|
163
|
+
*
|
|
164
|
+
* `fn` must build its output graph from the input arrays in argument order and
|
|
165
|
+
* return them (most often a single array). It must not throw; a throw is
|
|
166
|
+
* captured and surfaced from apply(). The MlxArrays handed to `fn` are owned by
|
|
167
|
+
* mlx — do NOT dispose them. Lifecycle/house-rules mirror ValueAndGrad. */
|
|
168
|
+
export class Vjp {
|
|
169
|
+
readonly #cb: JSCallback;
|
|
170
|
+
readonly #closure: bigint;
|
|
171
|
+
readonly #nOut: number;
|
|
172
|
+
#closureError: string | null = null;
|
|
173
|
+
#disposed = false;
|
|
174
|
+
|
|
175
|
+
/** @param nOut number of arrays `fn` returns (length of the cotangent list). */
|
|
176
|
+
constructor(fn: (primals: MlxArray[]) => MlxArray[], nOut = 1) {
|
|
177
|
+
this.#nOut = nOut;
|
|
178
|
+
this.#cb = new JSCallback(
|
|
179
|
+
(outPtr: number, inVec: bigint, _payload: number): number => {
|
|
180
|
+
try {
|
|
181
|
+
const n = Number(C.mlx_vector_array_size(inVec));
|
|
182
|
+
const primals: MlxArray[] = [];
|
|
183
|
+
for (let i = 0; i < n; i++) {
|
|
184
|
+
const slot = new BigUint64Array([C.mlx_array_new()]);
|
|
185
|
+
const sp = ptr(slot);
|
|
186
|
+
if (C.mlx_vector_array_get(sp, inVec, BigInt(i)) !== 0)
|
|
187
|
+
throw new Error(`vector_array_get(${i}) failed`);
|
|
188
|
+
primals.push(new MlxArray(read.u64(sp, 0)));
|
|
189
|
+
}
|
|
190
|
+
const outs = fn(primals);
|
|
191
|
+
const handles = new BigUint64Array(outs.map((o) => o.handle));
|
|
192
|
+
if (C.mlx_vector_array_set_data(outPtr as never, ptr(handles), BigInt(outs.length)) !== 0)
|
|
193
|
+
throw new Error("vector_array_set_data failed");
|
|
194
|
+
for (const p of primals) p.dispose();
|
|
195
|
+
for (const o of outs) o.dispose();
|
|
196
|
+
return 0;
|
|
197
|
+
} catch (e) {
|
|
198
|
+
this.#closureError = e instanceof Error ? e.message : String(e);
|
|
199
|
+
return 1;
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
{ args: ["ptr", "u64", "ptr"], returns: "i32" },
|
|
203
|
+
);
|
|
204
|
+
this.#closure = C.mlx_closure_new_func_payload(this.#cb.ptr as never, null, null);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Run the vjp on `primals` with `cotangents` (one per output of `fn`).
|
|
208
|
+
* Returns the outputs (fn(primals)) and one cotangent per primal (in primal
|
|
209
|
+
* order). Caller owns all returned arrays. */
|
|
210
|
+
apply(primals: MlxArray[], cotangents: MlxArray[]): { outputs: MlxArray[]; vjps: MlxArray[] } {
|
|
211
|
+
if (this.#disposed) throw new Error("Vjp used after dispose");
|
|
212
|
+
if (cotangents.length !== this.#nOut)
|
|
213
|
+
throw new Error(`Vjp: expected ${this.#nOut} cotangents, got ${cotangents.length}`);
|
|
214
|
+
this.#closureError = null;
|
|
215
|
+
|
|
216
|
+
const pHandles = new BigUint64Array(primals.map((p) => p.handle));
|
|
217
|
+
const cHandles = new BigUint64Array(cotangents.map((c) => c.handle));
|
|
218
|
+
const inVec = C.mlx_vector_array_new_data(ptr(pHandles), BigInt(primals.length));
|
|
219
|
+
const cotVec = C.mlx_vector_array_new_data(ptr(cHandles), BigInt(cotangents.length));
|
|
220
|
+
|
|
221
|
+
const outSlot = new BigUint64Array([C.mlx_vector_array_new()]);
|
|
222
|
+
const vjpSlot = new BigUint64Array([C.mlx_vector_array_new()]);
|
|
223
|
+
const st = C.mlx_vjp(ptr(outSlot), ptr(vjpSlot), this.#closure, inVec, cotVec);
|
|
224
|
+
const outVec = read.u64(ptr(outSlot), 0);
|
|
225
|
+
const vjpVec = read.u64(ptr(vjpSlot), 0);
|
|
226
|
+
if (st !== 0) {
|
|
227
|
+
C.mlx_vector_array_free(outVec);
|
|
228
|
+
C.mlx_vector_array_free(vjpVec);
|
|
229
|
+
C.mlx_vector_array_free(inVec);
|
|
230
|
+
C.mlx_vector_array_free(cotVec);
|
|
231
|
+
const mlxErr = takeMlxError();
|
|
232
|
+
const detail = this.#closureError ?? mlxErr ?? "";
|
|
233
|
+
throw new Error(`mlx_vjp failed${detail ? `: ${detail}` : ""}`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const nVjp = Number(C.mlx_vector_array_size(vjpVec));
|
|
237
|
+
if (nVjp !== primals.length) {
|
|
238
|
+
C.mlx_vector_array_free(outVec);
|
|
239
|
+
C.mlx_vector_array_free(vjpVec);
|
|
240
|
+
C.mlx_vector_array_free(inVec);
|
|
241
|
+
C.mlx_vector_array_free(cotVec);
|
|
242
|
+
throw new Error(`Vjp: expected ${primals.length} vjps, got ${nVjp}`);
|
|
243
|
+
}
|
|
244
|
+
const nOut = Number(C.mlx_vector_array_size(outVec));
|
|
245
|
+
const outputs: MlxArray[] = [];
|
|
246
|
+
for (let i = 0; i < nOut; i++) outputs.push(vecGet(outVec, i));
|
|
247
|
+
const vjps: MlxArray[] = [];
|
|
248
|
+
for (let i = 0; i < nVjp; i++) vjps.push(vecGet(vjpVec, i));
|
|
249
|
+
|
|
250
|
+
C.mlx_vector_array_free(outVec);
|
|
251
|
+
C.mlx_vector_array_free(vjpVec);
|
|
252
|
+
C.mlx_vector_array_free(inVec);
|
|
253
|
+
C.mlx_vector_array_free(cotVec);
|
|
254
|
+
return { outputs, vjps };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
dispose(): void {
|
|
258
|
+
if (this.#disposed) return;
|
|
259
|
+
this.#disposed = true;
|
|
260
|
+
C.mlx_closure_free(this.#closure);
|
|
261
|
+
this.#cb.close();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
[Symbol.dispose](): void {
|
|
265
|
+
this.dispose();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Gradient checkpointing (rematerialization) via mlx-c mlx_checkpoint.
|
|
2
|
+
//
|
|
3
|
+
// Wraps a JS function (MlxArray[]) -> MlxArray[] into a closure whose forward
|
|
4
|
+
// activations are dropped and RECOMPUTED during the enclosing value_and_grad
|
|
5
|
+
// backward. Used to bound training memory on long sequences: instead of
|
|
6
|
+
// retaining every transformer layer's activations, each checkpointed unit is
|
|
7
|
+
// recomputed one at a time in the backward pass.
|
|
8
|
+
//
|
|
9
|
+
// Same FFI lifecycle as ValueAndGrad (src/mlx/autograd.ts): a JSCallback over
|
|
10
|
+
// the user fn → mlx_closure_new_func_payload → mlx_checkpoint → applied with
|
|
11
|
+
// mlx_closure_apply. The closure must not throw across the FFI boundary; a JS
|
|
12
|
+
// throw is captured and re-surfaced from apply().
|
|
13
|
+
|
|
14
|
+
import { JSCallback, ptr, read } from "bun:ffi";
|
|
15
|
+
import { C, takeMlxError } from "./ffi";
|
|
16
|
+
import { MlxArray } from "./array";
|
|
17
|
+
|
|
18
|
+
/** A reusable checkpointed wrapper over a JS-built subgraph.
|
|
19
|
+
*
|
|
20
|
+
* `fn(inputs)` receives the input arrays (in order) and returns one or more
|
|
21
|
+
* output arrays. Applying the checkpoint builds the same forward graph, but
|
|
22
|
+
* marks it for recomputation: the enclosing backward recomputes `fn` rather
|
|
23
|
+
* than reading retained activations. Gradients flow to the explicit inputs
|
|
24
|
+
* AND to any outer-trace leaves captured by `fn` (e.g. swapped-in LoRA
|
|
25
|
+
* primals), exactly as if `fn` had been inlined. */
|
|
26
|
+
export class Checkpoint {
|
|
27
|
+
readonly #cb: JSCallback;
|
|
28
|
+
readonly #closure: bigint;
|
|
29
|
+
readonly #ckpt: bigint;
|
|
30
|
+
#closureError: string | null = null;
|
|
31
|
+
#disposed = false;
|
|
32
|
+
|
|
33
|
+
constructor(fn: (inputs: MlxArray[]) => MlxArray[]) {
|
|
34
|
+
this.#cb = new JSCallback(
|
|
35
|
+
(outPtr: number, inVec: bigint, _payload: number): number => {
|
|
36
|
+
try {
|
|
37
|
+
const n = Number(C.mlx_vector_array_size(inVec));
|
|
38
|
+
const inputs: MlxArray[] = [];
|
|
39
|
+
for (let i = 0; i < n; i++) {
|
|
40
|
+
const slot = new BigUint64Array([C.mlx_array_new()]);
|
|
41
|
+
const sp = ptr(slot);
|
|
42
|
+
if (C.mlx_vector_array_get(sp, inVec, BigInt(i)) !== 0)
|
|
43
|
+
throw new Error(`vector_array_get(${i}) failed`);
|
|
44
|
+
inputs.push(new MlxArray(read.u64(sp, 0)));
|
|
45
|
+
}
|
|
46
|
+
const outs = fn(inputs);
|
|
47
|
+
const handles = new BigUint64Array(outs.map((o) => o.handle));
|
|
48
|
+
if (C.mlx_vector_array_set_data(outPtr as never, ptr(handles), BigInt(outs.length)) !== 0)
|
|
49
|
+
throw new Error("vector_array_set_data failed");
|
|
50
|
+
for (const p of inputs) p.dispose();
|
|
51
|
+
for (const o of outs) o.dispose();
|
|
52
|
+
return 0;
|
|
53
|
+
} catch (e) {
|
|
54
|
+
this.#closureError = e instanceof Error ? e.message : String(e);
|
|
55
|
+
return 1;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
{ args: ["ptr", "u64", "ptr"], returns: "i32" },
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
this.#closure = C.mlx_closure_new_func_payload(this.#cb.ptr as never, null, null);
|
|
62
|
+
|
|
63
|
+
const slot = new BigUint64Array([C.mlx_closure_new()]);
|
|
64
|
+
if (C.mlx_checkpoint(ptr(slot), this.#closure) !== 0) {
|
|
65
|
+
C.mlx_closure_free(this.#closure);
|
|
66
|
+
this.#cb.close();
|
|
67
|
+
throw new Error(`mlx_checkpoint failed: ${takeMlxError() ?? ""}`);
|
|
68
|
+
}
|
|
69
|
+
this.#ckpt = read.u64(ptr(slot), 0);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Apply the checkpointed fn. Returns its outputs as owned MlxArrays. */
|
|
73
|
+
apply(inputs: MlxArray[]): MlxArray[] {
|
|
74
|
+
if (this.#disposed) throw new Error("Checkpoint used after dispose");
|
|
75
|
+
this.#closureError = null;
|
|
76
|
+
|
|
77
|
+
const handles = new BigUint64Array(inputs.map((p) => p.handle));
|
|
78
|
+
const inVec = C.mlx_vector_array_new_data(ptr(handles), BigInt(inputs.length));
|
|
79
|
+
const outSlot = new BigUint64Array([C.mlx_vector_array_new()]);
|
|
80
|
+
const st = C.mlx_closure_apply(ptr(outSlot), this.#ckpt, inVec);
|
|
81
|
+
const outVec = read.u64(ptr(outSlot), 0);
|
|
82
|
+
if (st !== 0) {
|
|
83
|
+
C.mlx_vector_array_free(outVec);
|
|
84
|
+
C.mlx_vector_array_free(inVec);
|
|
85
|
+
const detail = this.#closureError ?? takeMlxError() ?? "";
|
|
86
|
+
throw new Error(`checkpoint apply failed${detail ? `: ${detail}` : ""}`);
|
|
87
|
+
}
|
|
88
|
+
const nOut = Number(C.mlx_vector_array_size(outVec));
|
|
89
|
+
const outs: MlxArray[] = [];
|
|
90
|
+
for (let i = 0; i < nOut; i++) {
|
|
91
|
+
const slot = new BigUint64Array([C.mlx_array_new()]);
|
|
92
|
+
const sp = ptr(slot);
|
|
93
|
+
if (C.mlx_vector_array_get(sp, outVec, BigInt(i)) !== 0) {
|
|
94
|
+
C.mlx_vector_array_free(outVec);
|
|
95
|
+
C.mlx_vector_array_free(inVec);
|
|
96
|
+
throw new Error(`checkpoint output get(${i}) failed`);
|
|
97
|
+
}
|
|
98
|
+
outs.push(new MlxArray(read.u64(sp, 0)));
|
|
99
|
+
}
|
|
100
|
+
C.mlx_vector_array_free(outVec);
|
|
101
|
+
C.mlx_vector_array_free(inVec);
|
|
102
|
+
return outs;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
dispose(): void {
|
|
106
|
+
if (this.#disposed) return;
|
|
107
|
+
this.#disposed = true;
|
|
108
|
+
C.mlx_closure_free(this.#ckpt);
|
|
109
|
+
C.mlx_closure_free(this.#closure);
|
|
110
|
+
this.#cb.close();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
[Symbol.dispose](): void {
|
|
114
|
+
this.dispose();
|
|
115
|
+
}
|
|
116
|
+
}
|