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.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +362 -0
  3. package/THIRD_PARTY_LICENSES.md +41 -0
  4. package/bin/mlx-bun.mjs +32 -0
  5. package/docs/curve-designer.html +303 -0
  6. package/docs/design/adapters-end-to-end.md +201 -0
  7. package/docs/design/compat-cli-surface-design.md +227 -0
  8. package/docs/design/docs-reorg-plan.md +152 -0
  9. package/docs/design/hlg-sampling.md +340 -0
  10. package/docs/design/memory-system.md +339 -0
  11. package/docs/design/optimization_plan.md +344 -0
  12. package/docs/design/parallel-slots.md +515 -0
  13. package/docs/design/runtime-isolation.md +247 -0
  14. package/docs/design/segmented-backward-training.md +508 -0
  15. package/docs/investigations/chunk-finetune-experiment.md +84 -0
  16. package/docs/investigations/curve-bisector-routing.md +123 -0
  17. package/docs/investigations/curve-runs/bisector-route.json +98 -0
  18. package/docs/investigations/curve-runs/bisector-trace.json +1393 -0
  19. package/docs/investigations/curve-runs/curve-terrain.json +1179 -0
  20. package/docs/investigations/curve-runs/curve-terrain.svg +42 -0
  21. package/docs/investigations/curve-terrain.html +105 -0
  22. package/docs/investigations/expert-offload-single-user-moe.md +292 -0
  23. package/docs/investigations/hlg-ab.html +34 -0
  24. package/docs/investigations/hlg-explorer.html +238 -0
  25. package/docs/investigations/hlg-figs/cliff.svg +1 -0
  26. package/docs/investigations/hlg-figs/cross.svg +1 -0
  27. package/docs/investigations/hlg-figs/edges.svg +1 -0
  28. package/docs/investigations/hlg-figs/k20-grids.svg +1 -0
  29. package/docs/investigations/hlg-figs/k20-peaks.svg +1 -0
  30. package/docs/investigations/hlg-figs/lw-curve.svg +1 -0
  31. package/docs/investigations/hlg-figs/terrain.svg +1 -0
  32. package/docs/investigations/hlg-report.html +262 -0
  33. package/docs/investigations/hlg-runs/hlg-ab.json +149 -0
  34. package/docs/investigations/hlg-runs/hlg-blind-prompts.md +87 -0
  35. package/docs/investigations/hlg-runs/hlg-blind.json +107 -0
  36. package/docs/investigations/hlg-runs/hlg-cliff.json +197 -0
  37. package/docs/investigations/hlg-runs/hlg-cross.json +505 -0
  38. package/docs/investigations/hlg-runs/hlg-edge.json +388 -0
  39. package/docs/investigations/hlg-runs/hlg-eval1.json +25 -0
  40. package/docs/investigations/hlg-runs/hlg-frontier.json +86 -0
  41. package/docs/investigations/hlg-runs/hlg-grid.json +242 -0
  42. package/docs/investigations/hlg-runs/hlg-grid2.json +343 -0
  43. package/docs/investigations/hlg-runs/hlg-lw-coarse.json +110 -0
  44. package/docs/investigations/hlg-runs/hlg-map.json +383 -0
  45. package/docs/investigations/hlg-runs/run0-original.log +159 -0
  46. package/docs/investigations/hlg-runs/runA-recommended.log +131 -0
  47. package/docs/investigations/hlg-runs/runAA-cliff-cpm5.log +26 -0
  48. package/docs/investigations/hlg-runs/runAB-grid2-e4b.log +18 -0
  49. package/docs/investigations/hlg-runs/runAC-peak-e4b-partial.log +25 -0
  50. package/docs/investigations/hlg-runs/runAD-ab-samples.log +8 -0
  51. package/docs/investigations/hlg-runs/runAE-edge-e4b.log +51 -0
  52. package/docs/investigations/hlg-runs/runAF-logit-calibration.log +10 -0
  53. package/docs/investigations/hlg-runs/runAG-eval-config2.log +16 -0
  54. package/docs/investigations/hlg-runs/runB-gain-variants.log +192 -0
  55. package/docs/investigations/hlg-runs/runC-pivots.log +162 -0
  56. package/docs/investigations/hlg-runs/runD-oetf.log +132 -0
  57. package/docs/investigations/hlg-runs/runE-eotf.log +162 -0
  58. package/docs/investigations/hlg-runs/runF-shaper-working.log +86 -0
  59. package/docs/investigations/hlg-runs/runG-shaper-sweep.log +101 -0
  60. package/docs/investigations/hlg-runs/runH-wsweep.log +176 -0
  61. package/docs/investigations/hlg-runs/runI-asweep.log +176 -0
  62. package/docs/investigations/hlg-runs/runJ-knobmap.log +49 -0
  63. package/docs/investigations/hlg-runs/runK-frontier.log +19 -0
  64. package/docs/investigations/hlg-runs/runL-widemap.log +65 -0
  65. package/docs/investigations/hlg-runs/runM-frontier-emb.log +15 -0
  66. package/docs/investigations/hlg-runs/runN-verify.log +116 -0
  67. package/docs/investigations/hlg-runs/runO-frontier-seed5000.log +15 -0
  68. package/docs/investigations/hlg-runs/runP-grid-AxSm.log +15 -0
  69. package/docs/investigations/hlg-runs/runQ-grid-tgW.log +15 -0
  70. package/docs/investigations/hlg-runs/runR-blind-transcript.log +79 -0
  71. package/docs/investigations/hlg-runs/runS-cross-coherence.log +33 -0
  72. package/docs/investigations/hlg-runs/runT-cross-cpm5.log +33 -0
  73. package/docs/investigations/hlg-runs/runU-cross-12b.log +33 -0
  74. package/docs/investigations/hlg-runs/runV-lw-e4b.log +22 -0
  75. package/docs/investigations/hlg-runs/runW-lw-12b.log +22 -0
  76. package/docs/investigations/hlg-runs/runX-lw-cpm5.log +22 -0
  77. package/docs/investigations/hlg-runs/runY-cliff-e4b.log +26 -0
  78. package/docs/investigations/hlg-runs/runZ-cliff-12b.log +26 -0
  79. package/docs/investigations/hlg-sampling-investigation.md +970 -0
  80. package/docs/investigations/lab-build-journal.md +157 -0
  81. package/docs/investigations/pi-builtin-investigation.md +308 -0
  82. package/docs/investigations/starter-model-port-handoff.md +323 -0
  83. package/docs/planning/IDEAS.md +26 -0
  84. package/docs/planning/PRODUCT_ROADMAP.md +426 -0
  85. package/docs/planning/ResearchTopics.md +119 -0
  86. package/docs/planning/chunk-task-roadmap.md +77 -0
  87. package/docs/planning/journal.md +155 -0
  88. package/docs/reference/distribution.md +121 -0
  89. package/docs/reference/embedding.md +168 -0
  90. package/docs/reference/library-api.md +153 -0
  91. package/docs/reference/server-api.md +224 -0
  92. package/docs/reference/server-config.md +243 -0
  93. package/docs/segmented-backward-handoff.md +148 -0
  94. package/package.json +68 -0
  95. package/src/anthropic.ts +491 -0
  96. package/src/chat-template.ts +186 -0
  97. package/src/cli.ts +1075 -0
  98. package/src/config.ts +229 -0
  99. package/src/curve-sampler.ts +122 -0
  100. package/src/dataset/generators.ts +1087 -0
  101. package/src/dataset/index.ts +12 -0
  102. package/src/dataset/job.ts +81 -0
  103. package/src/dataset/llm.ts +71 -0
  104. package/src/dataset/registry.ts +528 -0
  105. package/src/download.ts +283 -0
  106. package/src/eval/README.md +86 -0
  107. package/src/eval/kl-prompts.ts +29 -0
  108. package/src/eval/kl.ts +294 -0
  109. package/src/eval/quality-db.ts +92 -0
  110. package/src/eval/runner.ts +102 -0
  111. package/src/eval/score.ts +49 -0
  112. package/src/eval/tasks/bfcl.ts +500 -0
  113. package/src/eval/tasks/gsm8k.ts +85 -0
  114. package/src/eval/tasks/hashhop.ts +109 -0
  115. package/src/eval/tasks/humaneval.ts +252 -0
  116. package/src/eval/tasks/ifeval.ts +354 -0
  117. package/src/eval/tasks/mmlu.ts +145 -0
  118. package/src/evaldb.ts +199 -0
  119. package/src/expert-offload-build.ts +77 -0
  120. package/src/expert-offload.ts +61 -0
  121. package/src/expert-trace.ts +67 -0
  122. package/src/fit.ts +254 -0
  123. package/src/generate.ts +451 -0
  124. package/src/harness-pi.ts +177 -0
  125. package/src/hf-push.ts +628 -0
  126. package/src/index.ts +22 -0
  127. package/src/jobs/db.ts +139 -0
  128. package/src/jobs/index.ts +29 -0
  129. package/src/jobs/job-entry.ts +106 -0
  130. package/src/jobs/runner.ts +304 -0
  131. package/src/jobs/sse.ts +114 -0
  132. package/src/jobs/types.ts +58 -0
  133. package/src/kv-store.ts +185 -0
  134. package/src/lora.ts +314 -0
  135. package/src/md-modules.d.ts +7 -0
  136. package/src/mlx/array.ts +237 -0
  137. package/src/mlx/autograd.ts +267 -0
  138. package/src/mlx/checkpoint.ts +116 -0
  139. package/src/mlx/compile.ts +158 -0
  140. package/src/mlx/custom-vjp.ts +140 -0
  141. package/src/mlx/ffi.ts +433 -0
  142. package/src/mlx/metal-kernel.ts +130 -0
  143. package/src/mlx/ops.ts +707 -0
  144. package/src/mmap.ts +90 -0
  145. package/src/model/batched-mask.ts +204 -0
  146. package/src/model/batched-rotating.ts +300 -0
  147. package/src/model/compiled-decode.ts +681 -0
  148. package/src/model/factory.ts +27 -0
  149. package/src/model/fingerprint.ts +33 -0
  150. package/src/model/flash-attention.ts +674 -0
  151. package/src/model/fused-decode-kernel.ts +305 -0
  152. package/src/model/fused-geglu-kernel.ts +87 -0
  153. package/src/model/gemma4-base.ts +1616 -0
  154. package/src/model/gemma4.ts +1012 -0
  155. package/src/model/generated/gemma4-12b.ts +526 -0
  156. package/src/model/generated/gemma4-26b.ts +500 -0
  157. package/src/model/generated/gemma4-e4b.ts +757 -0
  158. package/src/model/generated/index.ts +18 -0
  159. package/src/model/minicpm5.ts +278 -0
  160. package/src/model/qwen3-delta.ts +224 -0
  161. package/src/model/qwen3_5.ts +429 -0
  162. package/src/model/support.ts +46 -0
  163. package/src/native-pack.ts +152 -0
  164. package/src/pi-provider.ts +95 -0
  165. package/src/pi-terminal.ts +264 -0
  166. package/src/pi-web.ts +924 -0
  167. package/src/preflight.ts +123 -0
  168. package/src/prompt-cache.ts +113 -0
  169. package/src/quantize/allocator.ts +627 -0
  170. package/src/quantize/calibration.ts +180 -0
  171. package/src/quantize/config-writer.ts +132 -0
  172. package/src/quantize/index.ts +57 -0
  173. package/src/quantize/job.ts +136 -0
  174. package/src/quantize/quantizer.ts +462 -0
  175. package/src/quantize/safetensors-writer.ts +171 -0
  176. package/src/quantize/sensitivity.ts +234 -0
  177. package/src/registry.ts +336 -0
  178. package/src/responses.ts +774 -0
  179. package/src/safetensors.ts +158 -0
  180. package/src/sampler.ts +517 -0
  181. package/src/serve/batch-scheduler.ts +362 -0
  182. package/src/serve/generation-gateway.ts +160 -0
  183. package/src/server.ts +1891 -0
  184. package/src/spec/drafter.ts +261 -0
  185. package/src/spec/generate.ts +221 -0
  186. package/src/status-page.html +497 -0
  187. package/src/tokenizer.ts +38 -0
  188. package/src/tool-call.ts +242 -0
  189. package/src/train/dataset.ts +461 -0
  190. package/src/train/export.ts +32 -0
  191. package/src/train/forward.ts +229 -0
  192. package/src/train/index.ts +43 -0
  193. package/src/train/job.ts +148 -0
  194. package/src/train/lora-params.ts +194 -0
  195. package/src/train/loss.ts +342 -0
  196. package/src/train/merge.ts +195 -0
  197. package/src/train/optimizer.ts +176 -0
  198. package/src/train/rank.ts +101 -0
  199. package/src/train/segmented.ts +520 -0
  200. package/src/train/trainer.ts +600 -0
  201. package/src/tui.ts +161 -0
  202. package/src/vision/embedder.ts +168 -0
  203. package/src/vision/preprocess.ts +247 -0
  204. package/src/vision/prompt.ts +158 -0
  205. package/src/vision/siglip.ts +599 -0
  206. package/src/web/app.html +2471 -0
  207. package/src/web/skills/web-research/SKILL.md +44 -0
  208. package/src/web/skills.ts +59 -0
  209. package/src/web-tools.ts +426 -0
  210. package/src/weights.ts +91 -0
@@ -0,0 +1,461 @@
1
+ // Training dataset loading + batching. Ports the SFT shape from
2
+ // mlx_lm/tuner/datasets.py (chat / completions / text) and the DPO shape
3
+ // from optiq/lora/dpo.py (_tokenize_pair, _make_batch).
4
+ //
5
+ // v1 is batch_size=1 (no padding needed): the batch carries a single
6
+ // example's ids as an Int32Array plus a prompt boundary. The batch shape
7
+ // is designed so a future B>1 pad path slots in without changing callers.
8
+
9
+ import type { LoadedTokenizer } from "../tokenizer";
10
+ import type { ChatTemplate, ChatMessage } from "../chat-template";
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // SFT
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /** One tokenized SFT example. `promptLen` marks where the response begins;
17
+ * loss is masked to positions in [promptLen, ids.length). */
18
+ export interface SftExample {
19
+ ids: number[];
20
+ promptLen: number;
21
+ }
22
+
23
+ /** A single SFT training batch. `ids` is `[B][L]` row-major, every row padded
24
+ * to the common batch length `L`. `promptLens[i]` is row i's prompt boundary
25
+ * (loss starts at that position) and `lengths[i]` is row i's true unpadded
26
+ * length — positions `>= lengths[i]` are padding and are excluded from both
27
+ * the loss mask and the attention mask. For B=1 every row's `lengths[i]`
28
+ * equals its `ids[i].length` (no padding), so the loss/forward paths are
29
+ * bit-identical to the pre-batch single-example trainer. */
30
+ export interface SftBatch {
31
+ ids: number[][];
32
+ promptLens: number[];
33
+ /** Per-row true (unpadded) length; defaults to `ids[i].length` when absent
34
+ * (the B=1 no-padding case, kept for back-compat with single-row callers). */
35
+ lengths?: number[];
36
+ }
37
+
38
+ /** Row i's valid length: explicit `lengths[i]` if present, else the row's full
39
+ * (unpadded) id count. Centralizes the back-compat default so loss/forward
40
+ * treat a length-less B=1 batch exactly as before. */
41
+ export function rowLength(batch: SftBatch, i: number): number {
42
+ return batch.lengths?.[i] ?? batch.ids[i]!.length;
43
+ }
44
+
45
+ export type SftRowFormat = "messages" | "prompt-completion" | "text";
46
+
47
+ /** Detect a row's format from its keys. */
48
+ export function sftRowFormat(row: Record<string, unknown>): SftRowFormat {
49
+ if (Array.isArray(row.messages)) return "messages";
50
+ if (typeof row.prompt === "string" && typeof row.completion === "string")
51
+ return "prompt-completion";
52
+ if (typeof row.text === "string") return "text";
53
+ throw new Error(
54
+ `unrecognized SFT row: expected {messages}, {prompt,completion}, or {text}; got keys [${Object.keys(row).join(", ")}]`,
55
+ );
56
+ }
57
+
58
+ /** Render+tokenize one SFT row to ids + a prompt boundary.
59
+ *
60
+ * - messages: render full conversation (addGenerationPrompt:false); the
61
+ * prompt boundary is the render of all-but-last-turn with
62
+ * addGenerationPrompt:true (so the assistant's response is the unmasked
63
+ * region). Prefix-match fallback if the boundary render isn't a prefix.
64
+ * - prompt-completion: encode(prompt) is the boundary; full = prompt+completion.
65
+ * - text: bare text, promptLen=0 (no boundary — full-sequence loss). */
66
+ export function encodeSftRow(
67
+ row: Record<string, unknown>,
68
+ tok: LoadedTokenizer,
69
+ tmpl: ChatTemplate,
70
+ ): SftExample {
71
+ const fmt = sftRowFormat(row);
72
+
73
+ if (fmt === "text") {
74
+ const ids = tok.encode(row.text as string);
75
+ return { ids, promptLen: 0 };
76
+ }
77
+
78
+ if (fmt === "prompt-completion") {
79
+ const promptIds = tok.encode(row.prompt as string);
80
+ const fullIds = tok.encode((row.prompt as string) + (row.completion as string));
81
+ const promptLen = prefixBoundary(fullIds, promptIds);
82
+ return { ids: fullIds, promptLen };
83
+ }
84
+
85
+ // messages
86
+ const messages = row.messages as ChatMessage[];
87
+ const fullText = tmpl.render(messages, { addGenerationPrompt: false });
88
+ const fullIds = tok.encode(fullText);
89
+
90
+ // Boundary: render conversation up to (but excluding) the last assistant
91
+ // turn, with addGenerationPrompt:true so the rendered text ends exactly
92
+ // where the assistant response would begin.
93
+ const lastAssistantIdx = lastIndex(messages, (m) => m.role === "assistant");
94
+ if (lastAssistantIdx <= 0) {
95
+ // No assistant turn (or it's the first message) — nothing to mask.
96
+ return { ids: fullIds, promptLen: 0 };
97
+ }
98
+ const promptMessages = messages.slice(0, lastAssistantIdx);
99
+ const promptText = tmpl.render(promptMessages, { addGenerationPrompt: true });
100
+ const promptIds = tok.encode(promptText);
101
+ const promptLen = prefixBoundary(fullIds, promptIds);
102
+ return { ids: fullIds, promptLen };
103
+ }
104
+
105
+ /** Locate the prompt/response boundary. If `promptIds` is a token prefix of
106
+ * `fullIds`, the boundary is its length; otherwise fall back to the longest
107
+ * common prefix (handles tokenizers that merge across the seam). Always
108
+ * clamped to < fullIds.length so at least one response token is supervised. */
109
+ function prefixBoundary(fullIds: number[], promptIds: number[]): number {
110
+ let i = 0;
111
+ const max = Math.min(promptIds.length, fullIds.length);
112
+ while (i < max && fullIds[i] === promptIds[i]) i++;
113
+ return Math.min(i, Math.max(0, fullIds.length - 1));
114
+ }
115
+
116
+ function lastIndex<T>(arr: T[], pred: (x: T) => boolean): number {
117
+ for (let i = arr.length - 1; i >= 0; i--) if (pred(arr[i]!)) return i;
118
+ return -1;
119
+ }
120
+
121
+ /** Load + tokenize an SFT split (train.jsonl / valid.jsonl). */
122
+ export async function loadSftDataset(
123
+ path: string,
124
+ tok: LoadedTokenizer,
125
+ tmpl: ChatTemplate,
126
+ ): Promise<SftExample[]> {
127
+ const rows = await readJsonl(path);
128
+ return rows.map((r) => encodeSftRow(r, tok, tmpl));
129
+ }
130
+
131
+ /** mlx-lm iterate_batches pad granularity. Each batch is padded to
132
+ * `1 + PAD_TO * ceil(maxLenInBatch / PAD_TO)` (then capped at maxSeqLen). */
133
+ export const PAD_TO = 32;
134
+
135
+ /** Iterate SFT batches. Examples are length-sorted (mlx-lm iterate_batches),
136
+ * grouped into contiguous runs of `batchSize`, and the *batch order* is
137
+ * shuffled with `seed` each epoch. Examples longer than `maxSeqLen` are
138
+ * right-truncated (preserving the prompt-boundary clamp). `loop=false`
139
+ * yields one epoch then stops.
140
+ *
141
+ * B=1: yields one example per step with NO padding and no pad-to rounding —
142
+ * bit-identical to the original single-example trainer.
143
+ *
144
+ * B>1: faithful to mlx-lm. Sort ascending by length, take contiguous
145
+ * windows `idx[i : i+B]` for `i in 0, B, 2B, …` (the trailing remainder
146
+ * that does not fill a batch is dropped, matching mlx-lm's range bound),
147
+ * permute batch order, and pad every row to
148
+ * `min(1 + PAD_TO·ceil(max_len/PAD_TO), maxSeqLen)` with `padId`. Each row
149
+ * carries its true (truncated) length so the loss + attention masks ignore
150
+ * padding. `padId` defaults to 0 (mlx-lm SFT uses np.zeros); pass the eos id
151
+ * to pad with a real sentinel — the padded positions are masked out either
152
+ * way, so the choice does not change the loss. */
153
+ export function* iterateSftBatches(
154
+ examples: SftExample[],
155
+ batchSize: number,
156
+ maxSeqLen: number,
157
+ seed: number,
158
+ loop: boolean,
159
+ padId = 0,
160
+ ): Generator<SftBatch> {
161
+ if (batchSize < 1) throw new Error("iterateSftBatches: batchSize must be >= 1");
162
+ if (examples.length === 0) throw new Error("iterateSftBatches: empty dataset");
163
+ if (examples.length < batchSize)
164
+ throw new Error(
165
+ `iterateSftBatches: dataset has ${examples.length} examples but batchSize=${batchSize}`,
166
+ );
167
+
168
+ const order = [...examples.keys()].sort(
169
+ (a, b) => examples[a]!.ids.length - examples[b]!.ids.length,
170
+ );
171
+ const rng = mulberry32(seed >>> 0);
172
+
173
+ if (batchSize === 1) {
174
+ // Original single-example path: shuffle EXAMPLE order (not batch order),
175
+ // no padding, no pad-to rounding. Kept verbatim for bit-identical B=1.
176
+ do {
177
+ const shuffled = [...order];
178
+ for (let i = shuffled.length - 1; i > 0; i--) {
179
+ const j = Math.floor(rng() * (i + 1));
180
+ [shuffled[i], shuffled[j]] = [shuffled[j]!, shuffled[i]!];
181
+ }
182
+ for (const idx of shuffled) {
183
+ const ex = examples[idx]!;
184
+ let ids = ex.ids;
185
+ let promptLen = ex.promptLen;
186
+ if (ids.length > maxSeqLen) {
187
+ ids = ids.slice(0, maxSeqLen);
188
+ promptLen = Math.min(promptLen, Math.max(0, ids.length - 1));
189
+ }
190
+ yield { ids: [ids], promptLens: [promptLen], lengths: [ids.length] };
191
+ }
192
+ } while (loop);
193
+ return;
194
+ }
195
+
196
+ // B>1: contiguous length-sorted windows; drop the trailing remainder.
197
+ const batches: number[][] = [];
198
+ for (let i = 0; i + batchSize <= order.length; i += batchSize)
199
+ batches.push(order.slice(i, i + batchSize));
200
+
201
+ do {
202
+ const perm = [...batches.keys()];
203
+ for (let i = perm.length - 1; i > 0; i--) {
204
+ const j = Math.floor(rng() * (i + 1));
205
+ [perm[i], perm[j]] = [perm[j]!, perm[i]!];
206
+ }
207
+ for (const bi of perm) yield padSftBatch(batches[bi]!.map((k) => examples[k]!), maxSeqLen, padId);
208
+ } while (loop);
209
+ }
210
+
211
+ /** Pad a window of examples to a common length (mlx-lm pad-to rule) and
212
+ * collect prompt boundaries + true lengths. */
213
+ function padSftBatch(rows: SftExample[], maxSeqLen: number, padId: number): SftBatch {
214
+ const lens = rows.map((r) => Math.min(r.ids.length, maxSeqLen));
215
+ const maxLen = Math.max(...lens);
216
+ const L = Math.min(1 + PAD_TO * Math.ceil(maxLen / PAD_TO), maxSeqLen);
217
+ const ids: number[][] = [];
218
+ const promptLens: number[] = [];
219
+ const lengths: number[] = [];
220
+ for (const r of rows) {
221
+ const trueLen = Math.min(r.ids.length, L);
222
+ let promptLen = r.promptLen;
223
+ if (r.ids.length > L) promptLen = Math.min(promptLen, Math.max(0, L - 1));
224
+ const row = new Array<number>(L).fill(padId);
225
+ for (let t = 0; t < trueLen; t++) row[t] = r.ids[t]!;
226
+ ids.push(row);
227
+ promptLens.push(promptLen);
228
+ lengths.push(trueLen);
229
+ }
230
+ return { ids, promptLens, lengths };
231
+ }
232
+
233
+ // ---------------------------------------------------------------------------
234
+ // DPO
235
+ // ---------------------------------------------------------------------------
236
+
237
+ /** One DPO preference triple → tokenized chosen/rejected with response masks. */
238
+ export interface DpoExample {
239
+ chosenIds: number[];
240
+ rejectedIds: number[];
241
+ /** 1 at response positions, 0 over the prompt; length matches the ids. */
242
+ chosenMask: number[];
243
+ rejectedMask: number[];
244
+ }
245
+
246
+ /** A single DPO batch. Each branch is padded to the longest sequence of its
247
+ * kind within the batch (port of dpo.py _make_batch). The response masks are
248
+ * 0 at both prompt AND pad positions, so per-sequence log-probs naturally
249
+ * ignore padding without a separate length array. For B=1 there is no padding
250
+ * and the masks/forward are bit-identical to the single-example trainer. */
251
+ export interface DpoBatch {
252
+ chosenIds: number[][];
253
+ rejectedIds: number[][];
254
+ chosenMask: number[][];
255
+ rejectedMask: number[][];
256
+ /** Per-row true (unpadded) length of the chosen branch — drives the chosen
257
+ * attention mask. Absent ⇒ no padding (B=1), so `chosenIds[i].length`. */
258
+ chosenLengths?: number[];
259
+ /** Per-row true (unpadded) length of the rejected branch. */
260
+ rejectedLengths?: number[];
261
+ }
262
+
263
+ /** Tokenize prompt+response, returning (ids, promptLen) — port of
264
+ * dpo.py _tokenize_pair, including the left-truncation that preserves the
265
+ * response when prompt+response exceeds maxLength. */
266
+ export function tokenizePair(
267
+ prompt: string,
268
+ response: string,
269
+ tok: LoadedTokenizer,
270
+ maxLength: number,
271
+ ): { ids: number[]; promptLen: number } {
272
+ const promptIds = tok.encode(prompt);
273
+ let fullIds = tok.encode(prompt + response);
274
+ let promptLen: number;
275
+ if (isPrefix(fullIds, promptIds)) {
276
+ promptLen = promptIds.length;
277
+ } else {
278
+ promptLen = promptIds.length;
279
+ const responseIds = tok.encode(response);
280
+ fullIds = [...promptIds, ...responseIds];
281
+ }
282
+ if (fullIds.length > maxLength) {
283
+ const excess = fullIds.length - maxLength;
284
+ if (excess >= promptLen) {
285
+ fullIds = fullIds.slice(fullIds.length - maxLength);
286
+ promptLen = 0;
287
+ } else {
288
+ fullIds = fullIds.slice(excess);
289
+ promptLen -= excess;
290
+ }
291
+ }
292
+ return { ids: fullIds, promptLen };
293
+ }
294
+
295
+ /** Encode one DPO triple. `prompt` may be a string or chat messages. */
296
+ export function encodeDpoRow(
297
+ row: Record<string, unknown>,
298
+ tok: LoadedTokenizer,
299
+ tmpl: ChatTemplate,
300
+ maxLength: number,
301
+ ): DpoExample {
302
+ if (typeof row.chosen !== "string" || typeof row.rejected !== "string")
303
+ throw new Error("DPO row must have string `chosen` and `rejected`");
304
+ const promptStr = renderDpoPrompt(row.prompt, tmpl);
305
+ const c = tokenizePair(promptStr, row.chosen, tok, maxLength);
306
+ const r = tokenizePair(promptStr, row.rejected, tok, maxLength);
307
+ return {
308
+ chosenIds: c.ids,
309
+ rejectedIds: r.ids,
310
+ chosenMask: respMask(c.ids.length, c.promptLen),
311
+ rejectedMask: respMask(r.ids.length, r.promptLen),
312
+ };
313
+ }
314
+
315
+ function renderDpoPrompt(prompt: unknown, tmpl: ChatTemplate): string {
316
+ if (typeof prompt === "string") return prompt;
317
+ if (Array.isArray(prompt))
318
+ return tmpl.render(prompt as ChatMessage[], { addGenerationPrompt: true, enableThinking: false });
319
+ throw new Error("DPO row `prompt` must be a string or a list of chat messages");
320
+ }
321
+
322
+ function respMask(len: number, promptLen: number): number[] {
323
+ const m = new Array<number>(len).fill(0);
324
+ for (let i = promptLen; i < len; i++) m[i] = 1;
325
+ return m;
326
+ }
327
+
328
+ /** Load + tokenize a DPO split. */
329
+ export async function loadDpoDataset(
330
+ path: string,
331
+ tok: LoadedTokenizer,
332
+ tmpl: ChatTemplate,
333
+ maxLength: number,
334
+ ): Promise<DpoExample[]> {
335
+ const rows = await readJsonl(path);
336
+ return rows.map((r) => encodeDpoRow(r, tok, tmpl, maxLength));
337
+ }
338
+
339
+ /** Row length of a DPO branch (port of _make_batch helpers). */
340
+ export function dpoChosenLength(batch: DpoBatch, i: number): number {
341
+ return batch.chosenLengths?.[i] ?? batch.chosenIds[i]!.length;
342
+ }
343
+ export function dpoRejectedLength(batch: DpoBatch, i: number): number {
344
+ return batch.rejectedLengths?.[i] ?? batch.rejectedIds[i]!.length;
345
+ }
346
+
347
+ /** Iterate DPO batches. Sequential examples grouped into runs of `batchSize`,
348
+ * example order reshuffled with `seed` each epoch (port of dpo.py _batch_at +
349
+ * _make_batch). The trailing remainder that does not fill a batch is dropped.
350
+ *
351
+ * B=1: one example per step, no padding — bit-identical to the original.
352
+ *
353
+ * B>1: each branch is padded to the longest of its kind in the batch with
354
+ * `padId` (chosen/rejected padded independently, exactly like _make_batch).
355
+ * Response masks are 0 at pad positions; per-row branch lengths are recorded
356
+ * so the batched attention masks exclude padded keys. `padId` defaults to 0
357
+ * (pad/eos resolved by the caller); padded scores are masked out regardless. */
358
+ export function* iterateDpoBatches(
359
+ examples: DpoExample[],
360
+ batchSize: number,
361
+ seed: number,
362
+ loop: boolean,
363
+ padId = 0,
364
+ ): Generator<DpoBatch> {
365
+ if (batchSize < 1) throw new Error("iterateDpoBatches: batchSize must be >= 1");
366
+ if (examples.length === 0) throw new Error("iterateDpoBatches: empty dataset");
367
+ if (examples.length < batchSize)
368
+ throw new Error(
369
+ `iterateDpoBatches: dataset has ${examples.length} examples but batchSize=${batchSize}`,
370
+ );
371
+
372
+ const rng = mulberry32(seed >>> 0);
373
+ const order = [...examples.keys()];
374
+ do {
375
+ for (let i = order.length - 1; i > 0; i--) {
376
+ const j = Math.floor(rng() * (i + 1));
377
+ [order[i], order[j]] = [order[j]!, order[i]!];
378
+ }
379
+ if (batchSize === 1) {
380
+ for (const idx of order) {
381
+ const ex = examples[idx]!;
382
+ yield {
383
+ chosenIds: [ex.chosenIds],
384
+ rejectedIds: [ex.rejectedIds],
385
+ chosenMask: [ex.chosenMask],
386
+ rejectedMask: [ex.rejectedMask],
387
+ chosenLengths: [ex.chosenIds.length],
388
+ rejectedLengths: [ex.rejectedIds.length],
389
+ };
390
+ }
391
+ } else {
392
+ for (let i = 0; i + batchSize <= order.length; i += batchSize)
393
+ yield makeDpoBatch(order.slice(i, i + batchSize).map((k) => examples[k]!), padId);
394
+ }
395
+ } while (loop);
396
+ }
397
+
398
+ /** Pad chosen/rejected branches each to their own batch-max length, masks 0 at
399
+ * pad positions (port of dpo.py _make_batch.pad). */
400
+ function makeDpoBatch(rows: DpoExample[], padId: number): DpoBatch {
401
+ const Lc = Math.max(...rows.map((r) => r.chosenIds.length));
402
+ const Lr = Math.max(...rows.map((r) => r.rejectedIds.length));
403
+ const padRow = (src: number[], L: number, fill: number): number[] => {
404
+ const out = new Array<number>(L).fill(fill);
405
+ for (let t = 0; t < src.length; t++) out[t] = src[t]!;
406
+ return out;
407
+ };
408
+ return {
409
+ chosenIds: rows.map((r) => padRow(r.chosenIds, Lc, padId)),
410
+ rejectedIds: rows.map((r) => padRow(r.rejectedIds, Lr, padId)),
411
+ chosenMask: rows.map((r) => padRow(r.chosenMask, Lc, 0)),
412
+ rejectedMask: rows.map((r) => padRow(r.rejectedMask, Lr, 0)),
413
+ chosenLengths: rows.map((r) => r.chosenIds.length),
414
+ rejectedLengths: rows.map((r) => r.rejectedIds.length),
415
+ };
416
+ }
417
+
418
+ // ---------------------------------------------------------------------------
419
+ // shared
420
+ // ---------------------------------------------------------------------------
421
+
422
+ /** Format probe for inspect-dataset: peek the first row's keys. */
423
+ export type DatasetFormat = "messages" | "prompt-completion" | "text" | "dpo" | "unknown";
424
+
425
+ export function probeFormat(row: Record<string, unknown>): DatasetFormat {
426
+ if (typeof row.chosen === "string" && typeof row.rejected === "string") return "dpo";
427
+ try {
428
+ return sftRowFormat(row);
429
+ } catch {
430
+ return "unknown";
431
+ }
432
+ }
433
+
434
+ async function readJsonl(path: string): Promise<Record<string, unknown>[]> {
435
+ const text = await Bun.file(path).text();
436
+ const out: Record<string, unknown>[] = [];
437
+ for (const line of text.split("\n")) {
438
+ const t = line.trim();
439
+ if (!t) continue;
440
+ out.push(JSON.parse(t) as Record<string, unknown>);
441
+ }
442
+ return out;
443
+ }
444
+
445
+ function isPrefix(full: number[], prefix: number[]): boolean {
446
+ if (prefix.length > full.length) return false;
447
+ for (let i = 0; i < prefix.length; i++) if (full[i] !== prefix[i]) return false;
448
+ return true;
449
+ }
450
+
451
+ /** Small deterministic PRNG (mulberry32) — seedable, no deps. */
452
+ function mulberry32(seed: number): () => number {
453
+ let a = seed || 1;
454
+ return () => {
455
+ a |= 0;
456
+ a = (a + 0x6d2b79f5) | 0;
457
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
458
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
459
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
460
+ };
461
+ }
@@ -0,0 +1,32 @@
1
+ // Adapter export manifest (v1): a small JSON pointing at the base model and
2
+ // the adapter directory, so a downstream consumer can mount the adapter
3
+ // without rediscovering its base.
4
+
5
+ import { mkdirSync } from "node:fs";
6
+
7
+ export interface ExportManifest {
8
+ version: 1;
9
+ base_model: string;
10
+ adapter_path: string;
11
+ method?: string;
12
+ created_at: string;
13
+ }
14
+
15
+ /** Write `manifest.json` into `outputDir` describing an exported adapter. */
16
+ export async function exportAdapter(
17
+ outputDir: string,
18
+ baseModel: string,
19
+ adapterPath: string,
20
+ method?: string,
21
+ ): Promise<ExportManifest> {
22
+ mkdirSync(outputDir, { recursive: true });
23
+ const manifest: ExportManifest = {
24
+ version: 1,
25
+ base_model: baseModel,
26
+ adapter_path: adapterPath,
27
+ method,
28
+ created_at: new Date().toISOString(),
29
+ };
30
+ await Bun.write(`${outputDir}/manifest.json`, JSON.stringify(manifest, null, 2) + "\n");
31
+ return manifest;
32
+ }