mlx-bun 0.0.10 → 0.0.12
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 +107 -32
- package/THIRD_PARTY_LICENSES.md +10 -0
- package/docs/archive/mlx-bun-lab-report.html +275 -0
- package/docs/archive/wwdc-mlx-bun.html +848 -0
- package/docs/design/audio-input-plan.md +356 -0
- package/docs/design/batching-perf-path.md +58 -35
- package/docs/design/batching-v2-plan.md +23 -9
- package/docs/design/bucketing-stage.md +2 -1
- package/docs/design/colibri-glm52-port.md +1479 -0
- package/docs/design/compat-cli-surface-design.md +4 -3
- package/docs/design/decode-speed-program.md +172 -0
- package/docs/design/docs-reorg-plan.md +1 -1
- package/docs/design/dspark-serving-program.md +371 -0
- package/docs/design/dspark-speculative-decoding.md +167 -5
- package/docs/design/faithful-l1-consolidation.md +310 -0
- package/docs/design/generic-model-support.md +8 -5
- package/docs/design/grammar-spec-batching-integration.md +301 -0
- package/docs/design/minicpm5-decode-megakernel.md +16 -11
- package/docs/design/mlx-lm-tool-parity-plan.md +11 -1
- package/docs/design/omlx-adoption-map.md +14 -6
- package/docs/design/orpo-training.md +34 -30
- package/docs/design/paged-kv-cache.md +214 -0
- package/docs/design/parallel-slots.md +82 -49
- package/docs/design/parity-tier-dag.md +43 -33
- package/docs/design/pre-colibri-stabilization.md +329 -0
- package/docs/design/repo-cleanup-plan.md +189 -0
- package/docs/design/runtime-isolation.md +19 -3
- package/docs/design/segmented-backward-training.md +3 -2
- package/docs/design/ssd-kv-cold-tier.md +130 -0
- package/docs/design/structured-output.md +484 -0
- package/docs/design/the-dreaming-master-plan.md +2 -3
- package/docs/design/turboquant-kv.md +235 -0
- package/docs/design/unified-engine-frontier-plan.md +774 -0
- package/docs/design/web-chat-beat-matrix.md +315 -0
- package/docs/design/web-chat-redesign.md +1112 -0
- package/docs/investigations/colibri-oracle-pin.md +1284 -0
- package/docs/investigations/dspark-handoff.md +182 -16
- package/docs/investigations/indexshare-performance-spike.md +357 -0
- package/docs/investigations/lab-build-journal.md +2 -2
- package/docs/investigations/openwiki-evaluation.md +249 -0
- package/docs/planning/IDEAS.md +14 -0
- package/docs/planning/PRODUCT_ROADMAP.md +2 -3
- package/docs/planning/chat-ui-vision-memory-first.md +199 -0
- package/docs/planning/chat-ui-vision.md +50 -0
- package/docs/planning/memory-docs-and-dag-plan.md +15 -6
- package/docs/planning/release-notes-v0.0.11.md +239 -0
- package/docs/planning/release-notes-v0.0.12.md +80 -0
- package/docs/reference/cli.md +63 -18
- package/docs/reference/distribution.md +37 -6
- package/docs/reference/embedding.md +40 -16
- package/docs/reference/features-matrix.md +99 -0
- package/docs/reference/library-api.md +69 -20
- package/docs/reference/memory.md +26 -6
- package/docs/reference/models.md +60 -3
- package/docs/reference/orpo-quickstart.md +3 -4
- package/docs/reference/server-api.md +717 -24
- package/docs/reference/server-config.md +265 -129
- package/docs/reference/training.md +24 -16
- package/package.json +5 -3
- package/src/anthropic.ts +67 -44
- package/src/audio/conformer.ts +647 -0
- package/src/audio/decode.ts +133 -0
- package/src/audio/features.ts +202 -0
- package/src/audio/transcode.ts +67 -0
- package/src/chat-template.ts +155 -10
- package/src/cli.ts +483 -113
- package/src/config.ts +116 -24
- package/src/diffusion/diffusion-generate.ts +14 -8
- package/src/download.ts +143 -12
- package/src/eval/README.md +7 -6
- package/src/eval/ifeval.ts +63 -120
- package/src/eval/kl.ts +59 -3
- package/src/eval/quality-db.ts +2 -2
- package/src/eval/runner.ts +17 -8
- package/src/eval/tasks/ifeval.ts +167 -31
- package/src/expert-io.ts +391 -0
- package/src/expert-offload.ts +15 -2
- package/src/expert-residency.ts +1134 -0
- package/src/expert-usage.ts +415 -0
- package/src/flags.ts +13 -0
- package/src/generate.ts +438 -35
- package/src/grammar.ts +585 -0
- package/src/hf-push.ts +1 -1
- package/src/hub-rest.ts +242 -0
- package/src/index.ts +14 -2
- package/src/jobs/runner.ts +37 -18
- package/src/kv-store.ts +586 -93
- package/src/lora.ts +85 -14
- package/src/md-modules.d.ts +42 -0
- package/src/media-fetch.ts +426 -0
- package/src/memory/rest.ts +245 -0
- package/src/memory/vault.ts +74 -0
- package/src/mlx/array.ts +149 -19
- package/src/mlx/autograd.ts +53 -16
- package/src/mlx/checkpoint.ts +46 -13
- package/src/mlx/custom-vjp.ts +83 -35
- package/src/mlx/ffi.ts +27 -3
- package/src/mlx/metal-kernel.ts +7 -4
- package/src/mlx/ops.ts +153 -23
- package/src/mlx/turboquant-ops.ts +831 -0
- package/src/mlx/turboquant-tables.ts +237 -0
- package/src/model/batched-mask.ts +62 -1
- package/src/model/batched-quant.ts +206 -0
- package/src/model/batched-rotating-quant.ts +346 -0
- package/src/model/batched-rotating.ts +46 -1
- package/src/model/compiled-decode.ts +4 -15
- package/src/model/factory.ts +103 -6
- package/src/model/gemma4-base.ts +395 -39
- package/src/model/gemma4.ts +122 -33
- package/src/model/generated/gemma4-12b.ts +9 -13
- package/src/model/generated/gemma4-26b.ts +10 -5
- package/src/model/generated/gemma4-e4b.ts +14 -9
- 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/minicpm5.ts +58 -102
- package/src/model/paged-kv.ts +253 -0
- package/src/model/qwen3-delta.ts +76 -15
- package/src/model/qwen3-moe.ts +404 -0
- package/src/model/qwen3.ts +9 -8
- package/src/model/qwen3_5.ts +88 -23
- package/src/model/support.ts +19 -1
- package/src/model/universal/dense.ts +40 -5
- package/src/model/universal/rope.ts +36 -21
- package/src/native/expert_io.c +523 -0
- package/src/native-pack.ts +6 -4
- package/src/pi-web.ts +1299 -82
- package/src/preflight.ts +27 -8
- package/src/prompt-cache.ts +293 -33
- package/src/quantize/quantizer.ts +16 -1
- package/src/registry.ts +57 -2
- package/src/responses.ts +62 -49
- package/src/serve/batch-scheduler.ts +1050 -78
- package/src/serve/generation-gateway.ts +252 -24
- package/src/serve/isolate.ts +417 -0
- package/src/serve/lane-registry.ts +44 -0
- package/src/serve/session-search.ts +326 -0
- package/src/server.ts +1701 -175
- package/src/spec/assistant-source.ts +150 -0
- package/src/spec/deepspec-source.ts +143 -0
- package/src/spec/dflash-source.ts +124 -0
- package/src/spec/dspark/ab-stats.ts +136 -0
- package/src/spec/dspark/calibration.ts +112 -0
- package/src/spec/dspark/deepspec-module.ts +801 -0
- package/src/spec/dspark/generate-dflash.ts +72 -20
- package/src/spec/dspark/loader.ts +23 -0
- package/src/spec/dspark/module-dflash.ts +278 -36
- package/src/spec/dspark/quantize-drafter.ts +91 -0
- package/src/spec/generate.ts +59 -25
- package/src/spec/glm52-mtp-source.ts +392 -0
- package/src/spec/ngram-source.ts +132 -0
- package/src/spec/serve-loop.ts +617 -0
- package/src/spec/source.ts +118 -0
- package/src/spec/two-model.ts +171 -0
- package/src/ssd-cache.ts +111 -35
- package/src/tokenizer.ts +288 -2
- package/src/tool-approvals.ts +131 -0
- package/src/tool-call.ts +438 -22
- package/src/train/flash-cce.ts +2 -2
- package/src/train/job.ts +0 -12
- package/src/train/lora-params.ts +17 -6
- package/src/train/trainer.ts +60 -30
- package/src/vision/prompt.ts +217 -48
- package/src/web/app.html +1197 -1791
- package/src/web/app.js +5694 -0
- package/src/web/icon.svg +13 -0
- package/src/web/manifest.webmanifest +24 -0
- package/src/web/src/adapters-panel.ts +288 -0
- package/src/web/src/api.ts +57 -0
- package/src/web/src/assistant.ts +485 -0
- package/src/web/src/chat.ts +1050 -0
- package/src/web/src/composer.ts +959 -0
- package/src/web/src/dataset.ts +132 -0
- package/src/web/src/finetune.ts +267 -0
- package/src/web/src/hub.ts +428 -0
- package/src/web/src/main.ts +98 -0
- package/src/web/src/markdown.ts +0 -0
- package/src/web/src/memory-panel.ts +572 -0
- package/src/web/src/model-picker.ts +159 -0
- package/src/web/src/palette.ts +346 -0
- package/src/web/src/protocol.ts +62 -0
- package/src/web/src/quantize.ts +167 -0
- package/src/web/src/rag.ts +274 -0
- package/src/web/src/sessions.ts +469 -0
- package/src/web/src/shell.ts +804 -0
- package/src/web/src/status.ts +300 -0
- package/src/web/src/ui-catalog.ts +92 -0
- package/src/web/sw.js +71 -0
- package/src/web/vendor/README.md +61 -0
- package/src/web/vendor/hljs-LICENSE +29 -0
- package/src/web/vendor/hljs-theme.css +59 -0
- package/src/web/vendor/hljs.js +26 -0
- package/src/web-tools.ts +54 -2
- package/src/weights.ts +82 -19
- package/src/model/fused-decode-kernel.ts +0 -312
- package/src/model/fused-geglu-kernel.ts +0 -198
- package/src/model/fused-mlp-kernel.ts +0 -169
- package/src/model/fused-swiglu-kernel.ts +0 -240
- package/src/model/steel-linear-kernel.ts +0 -96
- package/src/status-page.html +0 -497
package/src/tool-call.ts
CHANGED
|
@@ -28,6 +28,12 @@ export interface ParsedToolCall {
|
|
|
28
28
|
name: string;
|
|
29
29
|
/** Parsed argument object (callers serialize for OpenAI's string field). */
|
|
30
30
|
arguments: Record<string, unknown>;
|
|
31
|
+
/** Set only when strict parsing failed and a repair pass recovered the
|
|
32
|
+
* call — never silent (Axis 7 self-healing beat row). `repairs` lists
|
|
33
|
+
* every malformation class that had to be corrected, in application
|
|
34
|
+
* order, so failures are observable (logs/telemetry) instead of masked. */
|
|
35
|
+
repaired?: true;
|
|
36
|
+
repairs?: RepairKind[];
|
|
31
37
|
}
|
|
32
38
|
|
|
33
39
|
interface ToolSpec {
|
|
@@ -60,7 +66,18 @@ export function gemmaArgsToJson(text: string): string {
|
|
|
60
66
|
return out;
|
|
61
67
|
}
|
|
62
68
|
|
|
63
|
-
/** Parse every `call:name{...}` block in a decoded tool-call segment.
|
|
69
|
+
/** Parse every `call:name{...}` block in a decoded tool-call segment.
|
|
70
|
+
*
|
|
71
|
+
* Strict scan first (unchanged behavior on well-formed input). On the two
|
|
72
|
+
* ways a small model mangles THIS family's syntax specifically —
|
|
73
|
+
* (a) generation truncated mid-call (an unterminated `<|"|>` string or a
|
|
74
|
+
* brace that never closes, both hit_max_tokens artifacts) and (b) a
|
|
75
|
+
* trailing comma surviving `gemmaArgsToJson`'s conversion to JSON — the
|
|
76
|
+
* repair pass recovers by treating "ran off the end of the text" as an
|
|
77
|
+
* implicit close (mirrors closeUnbalanced's brace-stack unwind, adapted
|
|
78
|
+
* for the `<|"|>`-quoted syntax) and re-running stripTrailingCommas on the
|
|
79
|
+
* converted JSON. Recovered calls are tagged repaired/repairs; a segment
|
|
80
|
+
* that still can't be recovered throws exactly as before. */
|
|
64
81
|
export function parseToolCalls(text: string): ParsedToolCall[] {
|
|
65
82
|
const calls: ParsedToolCall[] = [];
|
|
66
83
|
let i = 0;
|
|
@@ -71,10 +88,11 @@ export function parseToolCalls(text: string): ParsedToolCall[] {
|
|
|
71
88
|
// balanced-brace scan, skipping <|"|>-delimited strings
|
|
72
89
|
let depth = 0;
|
|
73
90
|
let j = nameEnd;
|
|
91
|
+
let unterminatedString = false;
|
|
74
92
|
while (j < text.length) {
|
|
75
93
|
if (text.startsWith(QUOTE, j)) {
|
|
76
94
|
const close = text.indexOf(QUOTE, j + QUOTE.length);
|
|
77
|
-
if (close === -1)
|
|
95
|
+
if (close === -1) { unterminatedString = true; break; }
|
|
78
96
|
j = close + QUOTE.length;
|
|
79
97
|
continue;
|
|
80
98
|
}
|
|
@@ -86,11 +104,55 @@ export function parseToolCalls(text: string): ParsedToolCall[] {
|
|
|
86
104
|
}
|
|
87
105
|
j++;
|
|
88
106
|
}
|
|
89
|
-
|
|
90
|
-
|
|
107
|
+
const truncated = unterminatedString || depth !== 0;
|
|
108
|
+
let argsBlock: string;
|
|
109
|
+
const repairs: RepairKind[] = [];
|
|
110
|
+
if (truncated) {
|
|
111
|
+
// Ran off the end of the text without closing — truncated generation.
|
|
112
|
+
// Close the dangling <|"|> string (if any) then append enough `}` to
|
|
113
|
+
// balance whatever braces are still open, using the SAME depth
|
|
114
|
+
// counter's remaining value (skip <|"|>-quoted spans again so a
|
|
115
|
+
// brace character inside a string doesn't miscount).
|
|
116
|
+
let closeDepth = 0;
|
|
117
|
+
let k = nameEnd;
|
|
118
|
+
let inQuote = false;
|
|
119
|
+
while (k < text.length) {
|
|
120
|
+
if (text.startsWith(QUOTE, k) && !inQuote) { inQuote = true; k += QUOTE.length; continue; }
|
|
121
|
+
if (inQuote) {
|
|
122
|
+
if (text.startsWith(QUOTE, k)) { inQuote = false; k += QUOTE.length; continue; }
|
|
123
|
+
k++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const c = text[k];
|
|
127
|
+
if (c === "{") closeDepth++;
|
|
128
|
+
else if (c === "}") closeDepth--;
|
|
129
|
+
k++;
|
|
130
|
+
}
|
|
131
|
+
argsBlock = text.slice(nameEnd) + (inQuote ? QUOTE : "") + "}".repeat(Math.max(closeDepth, 1));
|
|
132
|
+
repairs.push("unbalanced_braces");
|
|
133
|
+
j = text.length - 1;
|
|
134
|
+
} else {
|
|
135
|
+
argsBlock = text.slice(nameEnd, j + 1);
|
|
136
|
+
}
|
|
137
|
+
let converted = gemmaArgsToJson(argsBlock);
|
|
138
|
+
let parsed: unknown;
|
|
139
|
+
try {
|
|
140
|
+
parsed = JSON.parse(converted);
|
|
141
|
+
} catch {
|
|
142
|
+
const commas = stripTrailingCommas(converted);
|
|
143
|
+
if (!commas.changed) throw new Error("unbalanced braces in tool call");
|
|
144
|
+
try {
|
|
145
|
+
parsed = JSON.parse(commas.out);
|
|
146
|
+
} catch {
|
|
147
|
+
throw new Error("unbalanced braces in tool call");
|
|
148
|
+
}
|
|
149
|
+
converted = commas.out;
|
|
150
|
+
repairs.push("trailing_commas");
|
|
151
|
+
}
|
|
91
152
|
calls.push({
|
|
92
153
|
name: m[1]!,
|
|
93
|
-
arguments:
|
|
154
|
+
arguments: parsed as Record<string, unknown>,
|
|
155
|
+
...(repairs.length ? { repaired: true, repairs } : {}),
|
|
94
156
|
});
|
|
95
157
|
i = j + 1;
|
|
96
158
|
}
|
|
@@ -100,6 +162,8 @@ export function parseToolCalls(text: string): ParsedToolCall[] {
|
|
|
100
162
|
const TOOL_CALL_BLOCK_RE = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/gi;
|
|
101
163
|
const XML_FUNCTION_EQUALS_RE = /^\s*<function=([^>\s]+)>\s*([\s\S]*?)\s*<\/function>\s*$/i;
|
|
102
164
|
const XML_PARAMETER_EQUALS_RE = /<parameter=([^>\s]+)>\s*([\s\S]*?)\s*<\/parameter>/gi;
|
|
165
|
+
const GLM52_ARG_KEY_RE = /<arg_key>/i;
|
|
166
|
+
const GLM52_ARG_PAIR_RE = /<arg_key>\s*([\s\S]*?)\s*<\/arg_key>\s*<arg_value>\s*([\s\S]*?)\s*<\/arg_value>/gi;
|
|
103
167
|
const XML_FUNCTION_ATTR_RE = /<function\s+name=["']([^"']+)["']\s*>\s*([\s\S]*?)\s*<\/function>/gi;
|
|
104
168
|
// CDATA alternative first so a `</param>` inside a CDATA block never
|
|
105
169
|
// terminates the value early.
|
|
@@ -159,28 +223,327 @@ function decodeToolValue(value: string, schema: Record<string, unknown> | null):
|
|
|
159
223
|
}
|
|
160
224
|
}
|
|
161
225
|
|
|
226
|
+
// ---- Repair layer (Axis 7 self-healing beat row) ---------------------
|
|
227
|
+
//
|
|
228
|
+
// pi-ai (node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js)
|
|
229
|
+
// already ships a generic JSON repair pass for cloud-model streaming
|
|
230
|
+
// tool calls: `repairJson`/`parseJsonWithRepair` fix invalid backslash
|
|
231
|
+
// escapes and raw control characters inside strings, and
|
|
232
|
+
// `parseStreamingJson` falls back to the `partial-json` package for
|
|
233
|
+
// truncated mid-stream JSON. Its `validateToolArguments`
|
|
234
|
+
// (utils/validation.js) additionally coerces JSON-Schema primitive
|
|
235
|
+
// TYPES (string "3" -> number 3, etc.) once a call is already
|
|
236
|
+
// structurally valid JSON. None of that touches the STRUCTURAL
|
|
237
|
+
// malformations small local models actually produce here: single
|
|
238
|
+
// quotes instead of double, trailing commas, unbalanced/truncated
|
|
239
|
+
// braces, a whole call wrapped in a markdown ```json fence, stray
|
|
240
|
+
// prose ("Sure, here's the call:") glued in front of the JSON, or the
|
|
241
|
+
// function name landing inside `arguments` instead of the envelope
|
|
242
|
+
// (toolCallFromPayload above already handles that last one for
|
|
243
|
+
// already-valid JSON — the repair pass below reuses it once the text
|
|
244
|
+
// is coerced to valid JSON). This layer is therefore purely additive
|
|
245
|
+
// to pi-ai's, applied ONLY when strict parsing has already failed, and
|
|
246
|
+
// every repair is tagged on the returned ParsedToolCall (`repaired`,
|
|
247
|
+
// `repairs`) rather than silently swallowed — see ParsedToolCall above.
|
|
248
|
+
export type RepairKind =
|
|
249
|
+
| "fenced_wrapper" // ```json ... ``` or ``` ... ``` wrapper stripped
|
|
250
|
+
| "prose_prefix" // leading non-JSON prose trimmed to the first { or [
|
|
251
|
+
| "single_quotes" // 'like this' -> "like this" (keys and string values)
|
|
252
|
+
| "trailing_commas" // {"a":1,} / [1,2,] -> valid JSON
|
|
253
|
+
| "unbalanced_braces" // truncated generation: missing closing }/]/" appended
|
|
254
|
+
| "python_literals" // True/False/None -> true/false/null
|
|
255
|
+
| "name_in_args"; // function name found inside `arguments` instead of the envelope
|
|
256
|
+
|
|
257
|
+
/** Strip a ```json fenced block (or bare ```) wrapping the whole payload. */
|
|
258
|
+
function stripFence(text: string): { out: string; changed: boolean } {
|
|
259
|
+
const m = /^\s*```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/i.exec(text.trim());
|
|
260
|
+
if (!m) return { out: text, changed: false };
|
|
261
|
+
return { out: m[1] ?? "", changed: true };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Trim stray prose before the first `{`/`[` and after the matching
|
|
265
|
+
* document's last `}`/`]` (a small model narrating "Sure, here's the
|
|
266
|
+
* call: {...}" or trailing chatter after the JSON). Leaves the text
|
|
267
|
+
* alone if it doesn't start with prose (no-op safe to always run). */
|
|
268
|
+
function stripProsePrefix(text: string): { out: string; changed: boolean } {
|
|
269
|
+
const trimmed = text.trim();
|
|
270
|
+
const firstBrace = trimmed.search(/[{[]/);
|
|
271
|
+
if (firstBrace <= 0) return { out: trimmed, changed: false };
|
|
272
|
+
// Only strip when what precedes genuinely looks like prose (no braces
|
|
273
|
+
// of its own) — never chew into legitimate leading whitespace-only JSON.
|
|
274
|
+
const prefix = trimmed.slice(0, firstBrace);
|
|
275
|
+
if (/[{}[\]]/.test(prefix)) return { out: trimmed, changed: false };
|
|
276
|
+
const lastClose = Math.max(trimmed.lastIndexOf("}"), trimmed.lastIndexOf("]"));
|
|
277
|
+
const out = lastClose >= firstBrace ? trimmed.slice(firstBrace, lastClose + 1) : trimmed.slice(firstBrace);
|
|
278
|
+
return { out, changed: true };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Convert Python-ish literals (True/False/None) used outside string
|
|
282
|
+
* literals into JSON ones. Scans char-by-char tracking string state so
|
|
283
|
+
* a value like "Nonetheless" or a string containing "True" is untouched. */
|
|
284
|
+
function pythonLiteralsToJson(text: string): { out: string; changed: boolean } {
|
|
285
|
+
let out = "";
|
|
286
|
+
let changed = false;
|
|
287
|
+
let inString: '"' | "'" | null = null;
|
|
288
|
+
for (let i = 0; i < text.length; i++) {
|
|
289
|
+
const ch = text[i]!;
|
|
290
|
+
if (inString) {
|
|
291
|
+
out += ch;
|
|
292
|
+
if (ch === "\\") { out += text[++i] ?? ""; continue; }
|
|
293
|
+
if (ch === inString) inString = null;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (ch === '"' || ch === "'") { inString = ch; out += ch; continue; }
|
|
297
|
+
const rest = text.slice(i);
|
|
298
|
+
const wordMatch = /^(True|False|None)\b/.exec(rest);
|
|
299
|
+
if (wordMatch) {
|
|
300
|
+
const replacement = wordMatch[1] === "True" ? "true" : wordMatch[1] === "False" ? "false" : "null";
|
|
301
|
+
out += replacement;
|
|
302
|
+
i += wordMatch[1]!.length - 1;
|
|
303
|
+
changed = true;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
out += ch;
|
|
307
|
+
}
|
|
308
|
+
return { out, changed };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Convert single-quoted JSON (keys and string values) to double-quoted,
|
|
312
|
+
* tracking string state so an apostrophe INSIDE a double-quoted string
|
|
313
|
+
* (e.g. "don't") is left alone. Only fires when the text has no double
|
|
314
|
+
* quotes at all in "quote position" — i.e. looks like it was written
|
|
315
|
+
* with single quotes throughout — to avoid mangling a string that
|
|
316
|
+
* legitimately contains a single quote inside double-quoted JSON. */
|
|
317
|
+
function singleQuotesToDouble(text: string): { out: string; changed: boolean } {
|
|
318
|
+
if (!/'/.test(text)) return { out: text, changed: false };
|
|
319
|
+
// Heuristic gate: real JSON never opens a key/value with a bare `'`.
|
|
320
|
+
// If the text already parses with plain JSON.parse it wouldn't have
|
|
321
|
+
// reached here, so any '"'-delimited string is assumed intentional and
|
|
322
|
+
// left byte-for-byte; only '...'-delimited runs are retargeted.
|
|
323
|
+
let out = "";
|
|
324
|
+
let changed = false;
|
|
325
|
+
let inDouble = false;
|
|
326
|
+
let inSingle = false;
|
|
327
|
+
for (let i = 0; i < text.length; i++) {
|
|
328
|
+
const ch = text[i]!;
|
|
329
|
+
if (inDouble) {
|
|
330
|
+
out += ch;
|
|
331
|
+
if (ch === "\\") { out += text[++i] ?? ""; continue; }
|
|
332
|
+
if (ch === '"') inDouble = false;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (inSingle) {
|
|
336
|
+
if (ch === "\\") { out += ch + (text[++i] ?? ""); continue; }
|
|
337
|
+
if (ch === "'") { out += '"'; inSingle = false; continue; }
|
|
338
|
+
if (ch === '"') { out += '\\"'; continue; } // embedded " must be escaped now
|
|
339
|
+
out += ch;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if (ch === '"') { inDouble = true; out += ch; continue; }
|
|
343
|
+
if (ch === "'") { inSingle = true; changed = true; out += '"'; continue; }
|
|
344
|
+
out += ch;
|
|
345
|
+
}
|
|
346
|
+
return { out, changed };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Remove trailing commas before a closing `}`/`]` (whitespace/newlines
|
|
350
|
+
* between the comma and the close are preserved otherwise). */
|
|
351
|
+
function stripTrailingCommas(text: string): { out: string; changed: boolean } {
|
|
352
|
+
let changed = false;
|
|
353
|
+
const out = text.replace(/,(\s*[}\]])/g, (_m, close) => { changed = true; return close; });
|
|
354
|
+
return { out, changed };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Append the minimal closers to balance braces/brackets/an unterminated
|
|
358
|
+
* string — a small model that got truncated (or just stopped early)
|
|
359
|
+
* mid-object. Walks once tracking a stack of open delimiters and string
|
|
360
|
+
* state; on EOF, closes the open string (if any) then unwinds the stack
|
|
361
|
+
* in reverse. No-op (unchanged) when already balanced. */
|
|
362
|
+
function closeUnbalanced(text: string): { out: string; changed: boolean } {
|
|
363
|
+
const stack: ("}" | "]")[] = [];
|
|
364
|
+
let inString = false;
|
|
365
|
+
for (let i = 0; i < text.length; i++) {
|
|
366
|
+
const ch = text[i]!;
|
|
367
|
+
if (inString) {
|
|
368
|
+
if (ch === "\\") { i++; continue; }
|
|
369
|
+
if (ch === '"') inString = false;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (ch === '"') { inString = true; continue; }
|
|
373
|
+
if (ch === "{") stack.push("}");
|
|
374
|
+
else if (ch === "[") stack.push("]");
|
|
375
|
+
else if (ch === "}" || ch === "]") stack.pop();
|
|
376
|
+
}
|
|
377
|
+
if (!inString && stack.length === 0) return { out: text, changed: false };
|
|
378
|
+
let out = text;
|
|
379
|
+
if (inString) out += '"';
|
|
380
|
+
out += stack.reverse().join("");
|
|
381
|
+
return { out, changed: true };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Try strict JSON.parse first (pi-ai's own escape-level repair already
|
|
385
|
+
* ran upstream where applicable — see the comment above); on failure,
|
|
386
|
+
* apply the structural repair passes in order, re-testing after each so
|
|
387
|
+
* only the ones that were actually needed get tagged. Returns null (no
|
|
388
|
+
* throw) when nothing recovers a parseable object — callers decide how
|
|
389
|
+
* to surface that. */
|
|
390
|
+
function repairJsonToolText(text: string): { value: unknown; repairs: RepairKind[] } | null {
|
|
391
|
+
const repairs: RepairKind[] = [];
|
|
392
|
+
let candidate = text;
|
|
393
|
+
|
|
394
|
+
const fence = stripFence(candidate);
|
|
395
|
+
if (fence.changed) { candidate = fence.out; repairs.push("fenced_wrapper"); }
|
|
396
|
+
|
|
397
|
+
const prose = stripProsePrefix(candidate);
|
|
398
|
+
if (prose.changed) { candidate = prose.out; repairs.push("prose_prefix"); }
|
|
399
|
+
|
|
400
|
+
const tryParse = (s: string): unknown | undefined => {
|
|
401
|
+
try { return JSON.parse(s); } catch { return undefined; }
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
let parsed = tryParse(candidate);
|
|
405
|
+
if (parsed !== undefined) return { value: parsed, repairs };
|
|
406
|
+
|
|
407
|
+
const literals = pythonLiteralsToJson(candidate);
|
|
408
|
+
if (literals.changed) {
|
|
409
|
+
parsed = tryParse(literals.out);
|
|
410
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "python_literals"] };
|
|
411
|
+
candidate = literals.out;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const commas = stripTrailingCommas(candidate);
|
|
415
|
+
if (commas.changed) {
|
|
416
|
+
parsed = tryParse(commas.out);
|
|
417
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "trailing_commas"] };
|
|
418
|
+
candidate = commas.out;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const closed = closeUnbalanced(candidate);
|
|
422
|
+
if (closed.changed) {
|
|
423
|
+
parsed = tryParse(closed.out);
|
|
424
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "unbalanced_braces"] };
|
|
425
|
+
candidate = closed.out;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const quotes = singleQuotesToDouble(candidate);
|
|
429
|
+
if (quotes.changed) {
|
|
430
|
+
parsed = tryParse(quotes.out);
|
|
431
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "single_quotes"] };
|
|
432
|
+
candidate = quotes.out;
|
|
433
|
+
// Single-quote conversion can itself leave a trailing comma or an
|
|
434
|
+
// unbalanced document (e.g. `{'a': 1,}` truncated) — retry those two
|
|
435
|
+
// passes once more on the requoted text before giving up.
|
|
436
|
+
const commas2 = stripTrailingCommas(candidate);
|
|
437
|
+
if (commas2.changed) {
|
|
438
|
+
parsed = tryParse(commas2.out);
|
|
439
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "single_quotes", "trailing_commas"] };
|
|
440
|
+
candidate = commas2.out;
|
|
441
|
+
}
|
|
442
|
+
const closed2 = closeUnbalanced(candidate);
|
|
443
|
+
if (closed2.changed) {
|
|
444
|
+
parsed = tryParse(closed2.out);
|
|
445
|
+
if (parsed !== undefined) return { value: parsed, repairs: [...repairs, "single_quotes", "unbalanced_braces"] };
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Lenient JSON.parse used for argument STRINGS nested inside an already
|
|
453
|
+
* JSON-valid envelope (e.g. `"arguments": "{'a': 1}"`, a small model
|
|
454
|
+
* double-encoding with the wrong quote style). Falls back through the
|
|
455
|
+
* same repair passes; throws (not silently {}) when nothing recovers,
|
|
456
|
+
* same contract as JSON.parse for its callers. */
|
|
457
|
+
function parseJsonLoose(text: string): unknown {
|
|
458
|
+
try {
|
|
459
|
+
return JSON.parse(text);
|
|
460
|
+
} catch (err) {
|
|
461
|
+
const repaired = repairJsonToolText(text);
|
|
462
|
+
if (repaired) return repaired.value;
|
|
463
|
+
throw err;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Build a ParsedToolCall from an already-parsed JSON payload (object or
|
|
468
|
+
* {function:{name,arguments}} envelope). Shared by the strict and
|
|
469
|
+
* repaired paths so name/arguments extraction logic lives once. Handles
|
|
470
|
+
* the "name-in-args confusion" malformation: a small model sometimes
|
|
471
|
+
* emits the function name INSIDE the arguments object instead of (or in
|
|
472
|
+
* addition to) the envelope's own `name` field — e.g.
|
|
473
|
+
* {"arguments":{"name":"read","path":"x"}} with no top-level name at
|
|
474
|
+
* all. When the envelope has no usable name, an args-embedded `name` (or
|
|
475
|
+
* `function`) string is promoted and stripped out of the arguments. */
|
|
476
|
+
function toolCallFromPayload(
|
|
477
|
+
payload: unknown,
|
|
478
|
+
): { name: string; arguments: Record<string, unknown>; nameInArgs: boolean } | null {
|
|
479
|
+
if (!payload || typeof payload !== "object") return null;
|
|
480
|
+
const obj = payload as Record<string, any>;
|
|
481
|
+
const fn = obj.function && typeof obj.function === "object" ? obj.function : obj;
|
|
482
|
+
let name = typeof fn.name === "string" ? fn.name.trim() : "";
|
|
483
|
+
let args = fn.arguments ?? obj.arguments ?? {};
|
|
484
|
+
if (typeof args === "string") {
|
|
485
|
+
const parsed = args.trim() ? parseJsonLoose(args) : {};
|
|
486
|
+
args = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
487
|
+
}
|
|
488
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) return null;
|
|
489
|
+
const argsObj = { ...(args as Record<string, unknown>) };
|
|
490
|
+
let nameInArgs = false;
|
|
491
|
+
if (!name) {
|
|
492
|
+
const embedded = argsObj.name ?? argsObj.function;
|
|
493
|
+
if (typeof embedded === "string" && embedded.trim()) {
|
|
494
|
+
name = embedded.trim();
|
|
495
|
+
delete argsObj.name;
|
|
496
|
+
delete argsObj.function;
|
|
497
|
+
nameInArgs = true;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (!name) return null;
|
|
501
|
+
return { name, arguments: argsObj, nameInArgs };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Shape guard for the wrapper-less last-resort repair path only (see its
|
|
505
|
+
* call site in parseGeneratedToolCalls). A `<tool_call>`/`<function...>`
|
|
506
|
+
* tag already proves the model intended a tool call, so toolCallFromPayload
|
|
507
|
+
* can be lenient there; a bare JSON object with NO such tag is ambiguous —
|
|
508
|
+
* it could just as easily be an ordinary conversational reply that happens
|
|
509
|
+
* to be JSON-shaped (e.g. `{"name": "read", "age": 42}` answering "give me
|
|
510
|
+
* an example record"). Require an actual envelope shape: a `function`
|
|
511
|
+
* wrapper object, or a top-level/nested `arguments` object (including the
|
|
512
|
+
* name-in-args case, where the name lives inside that same `arguments`
|
|
513
|
+
* object) — never just a bare `name`/`function` string sitting next to
|
|
514
|
+
* unrelated fields. */
|
|
515
|
+
function looksLikeToolEnvelope(payload: unknown): boolean {
|
|
516
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
|
|
517
|
+
const obj = payload as Record<string, unknown>;
|
|
518
|
+
if (obj.function && typeof obj.function === "object" && !Array.isArray(obj.function)) return true;
|
|
519
|
+
const args = obj.arguments;
|
|
520
|
+
if (args && typeof args === "object" && !Array.isArray(args)) return true;
|
|
521
|
+
if (typeof args === "string") return true; // double-encoded arguments string
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
|
|
162
525
|
function parseJsonToolCall(block: string): ParsedToolCall | null {
|
|
163
526
|
let payload: unknown;
|
|
527
|
+
let repairs: RepairKind[] = [];
|
|
164
528
|
try {
|
|
165
529
|
payload = JSON.parse(block);
|
|
166
530
|
} catch {
|
|
167
|
-
|
|
531
|
+
// Strict JSON.parse failed — this is the ONLY point the syntax-repair
|
|
532
|
+
// pass engages (never attempted when the model emitted valid JSON). A
|
|
533
|
+
// repair failure here returns null (not throw): parseGeneratedToolCalls
|
|
534
|
+
// falls through to the XML parsers next, which is the right behavior
|
|
535
|
+
// for a `<tool_call>` block that isn't actually JSON-shaped at all.
|
|
536
|
+
const repaired = repairJsonToolText(block);
|
|
537
|
+
if (!repaired) return null;
|
|
538
|
+
payload = repaired.value;
|
|
539
|
+
repairs = repaired.repairs;
|
|
168
540
|
}
|
|
169
541
|
if (!payload || typeof payload !== "object") throw new Error("JSON tool_call payload must be an object");
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if (typeof args === "string") {
|
|
176
|
-
const parsed = args.trim() ? JSON.parse(args) : {};
|
|
177
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
178
|
-
throw new Error("tool_call arguments must be a JSON object");
|
|
179
|
-
return { name, arguments: parsed as Record<string, unknown> };
|
|
180
|
-
}
|
|
181
|
-
if (!args || typeof args !== "object" || Array.isArray(args))
|
|
182
|
-
throw new Error("tool_call arguments must be a JSON object");
|
|
183
|
-
return { name, arguments: args as Record<string, unknown> };
|
|
542
|
+
const result = toolCallFromPayload(payload);
|
|
543
|
+
if (!result) throw new Error("tool_call arguments must be a JSON object");
|
|
544
|
+
if (result.nameInArgs) repairs = [...repairs, "name_in_args"];
|
|
545
|
+
const { nameInArgs: _nameInArgs, ...call } = result;
|
|
546
|
+
return repairs.length ? { ...call, repaired: true, repairs } : call;
|
|
184
547
|
}
|
|
185
548
|
|
|
186
549
|
function parseXmlEqualsToolCall(block: string, tools: ToolSpec[]): ParsedToolCall | null {
|
|
@@ -199,6 +562,29 @@ function parseXmlEqualsToolCall(block: string, tools: ToolSpec[]): ParsedToolCal
|
|
|
199
562
|
return { name, arguments: args };
|
|
200
563
|
}
|
|
201
564
|
|
|
565
|
+
function parseGlm52ToolCall(block: string, tools: ToolSpec[]): ParsedToolCall | null {
|
|
566
|
+
const firstArg = block.search(GLM52_ARG_KEY_RE);
|
|
567
|
+
const name = (firstArg < 0 ? block : block.slice(0, firstArg)).trim();
|
|
568
|
+
if (!name || !/^[^\s<>]+$/.test(name)) return null;
|
|
569
|
+
if (firstArg < 0) return { name, arguments: {} };
|
|
570
|
+
|
|
571
|
+
const body = block.slice(firstArg);
|
|
572
|
+
const args: Record<string, unknown> = {};
|
|
573
|
+
let cursor = 0;
|
|
574
|
+
let matched = false;
|
|
575
|
+
for (const pair of body.matchAll(GLM52_ARG_PAIR_RE)) {
|
|
576
|
+
if (body.slice(cursor, pair.index).trim()) return null;
|
|
577
|
+
const key = pair[1]!.trim();
|
|
578
|
+
if (!key) throw new Error(`tool '${name}' contains an empty argument name`);
|
|
579
|
+
args[key] = decodeToolValue(pair[2]!, toolParameterSchema(tools, name, key));
|
|
580
|
+
cursor = pair.index + pair[0].length;
|
|
581
|
+
matched = true;
|
|
582
|
+
}
|
|
583
|
+
GLM52_ARG_PAIR_RE.lastIndex = 0;
|
|
584
|
+
if (!matched || body.slice(cursor).trim()) return null;
|
|
585
|
+
return { name, arguments: args };
|
|
586
|
+
}
|
|
587
|
+
|
|
202
588
|
function parseXmlAttrToolCalls(text: string, tools: ToolSpec[]): ParsedToolCall[] {
|
|
203
589
|
const calls: ParsedToolCall[] = [];
|
|
204
590
|
for (const fn of text.matchAll(XML_FUNCTION_ATTR_RE)) {
|
|
@@ -221,7 +607,8 @@ function parseXmlAttrToolCalls(text: string, tools: ToolSpec[]): ParsedToolCall[
|
|
|
221
607
|
* after generation, and only when tools are active; tokenizer ids are
|
|
222
608
|
* model-family-specific and must not be used globally. Supports the
|
|
223
609
|
* OpenAI JSON `<tool_call>...</tool_call>` contract, Qwen-style
|
|
224
|
-
* `<function=name><parameter=...>`,
|
|
610
|
+
* `<function=name><parameter=...>`, GLM-5.2's
|
|
611
|
+
* `name<arg_key>...<arg_value>...`, and MiniCPM5's native
|
|
225
612
|
* `<function name="..."><param name="...">...` template shape. */
|
|
226
613
|
export function parseGeneratedToolCalls(text: string, tools: ToolSpec[]): ParsedToolCall[] {
|
|
227
614
|
if (!tools.length) return [];
|
|
@@ -229,12 +616,41 @@ export function parseGeneratedToolCalls(text: string, tools: ToolSpec[]): Parsed
|
|
|
229
616
|
const calls: ParsedToolCall[] = [];
|
|
230
617
|
for (const block of text.matchAll(TOOL_CALL_BLOCK_RE)) {
|
|
231
618
|
const body = block[1]!.trim();
|
|
232
|
-
const parsed = parseJsonToolCall(body) ??
|
|
619
|
+
const parsed = parseJsonToolCall(body) ??
|
|
620
|
+
parseXmlEqualsToolCall(body, tools) ??
|
|
621
|
+
parseGlm52ToolCall(body, tools);
|
|
233
622
|
if (!parsed) throw new Error("unsupported tool_call payload format");
|
|
234
623
|
calls.push(parsed);
|
|
235
624
|
}
|
|
236
625
|
TOOL_CALL_BLOCK_RE.lastIndex = 0;
|
|
237
626
|
if (calls.length === 0) calls.push(...parseXmlAttrToolCalls(text, tools));
|
|
627
|
+
// Last-resort repair: no `<tool_call>` tags AND no `<function name=...>`
|
|
628
|
+
// XML matched at all — a small model sometimes drops the wrapper tags
|
|
629
|
+
// entirely and emits just (possibly fenced/prose-prefixed/malformed)
|
|
630
|
+
// JSON. Only attempted when everything else found nothing, so a
|
|
631
|
+
// genuinely tool-free assistant reply never risks being misread as a
|
|
632
|
+
// call. Tagged repaired like every other path here.
|
|
633
|
+
//
|
|
634
|
+
// Unlike the `<tool_call>`-wrapped path, there is no surrounding markup
|
|
635
|
+
// here to prove the model actually intended a tool call — an ordinary
|
|
636
|
+
// conversational reply can itself BE a bare JSON object (e.g. "give me
|
|
637
|
+
// an example record" -> `{"name": "read", "age": 42}`), which happens to
|
|
638
|
+
// collide with a real tool name. Require the recovered payload to
|
|
639
|
+
// actually look like a tool-call envelope (an `arguments`/
|
|
640
|
+
// `function.arguments` object, or a `function` wrapper, or the
|
|
641
|
+
// name-in-args shape) before accepting it — a flat object whose only
|
|
642
|
+
// tool-shaped feature is a `name` key that matches a tool is NOT enough
|
|
643
|
+
// signal on its own.
|
|
644
|
+
if (calls.length === 0) {
|
|
645
|
+
const repaired = repairJsonToolText(text.trim());
|
|
646
|
+
if (repaired && looksLikeToolEnvelope(repaired.value)) {
|
|
647
|
+
const result = toolCallFromPayload(repaired.value);
|
|
648
|
+
if (result) {
|
|
649
|
+
const repairs = result.nameInArgs ? [...repaired.repairs, "name_in_args" as const] : repaired.repairs;
|
|
650
|
+
calls.push({ name: result.name, arguments: result.arguments, repaired: true, repairs });
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
238
654
|
for (const c of calls) {
|
|
239
655
|
if (!known.has(c.name)) throw new Error(`unknown tool '${c.name}'`);
|
|
240
656
|
}
|
package/src/train/flash-cce.ts
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
// DIVERGENCES (why this isn't a line-for-line port):
|
|
22
22
|
// 1. Our classifier C is the QUANTIZED head (4/8-bit affine). Apple loads C
|
|
23
23
|
// dense (bf16); we keep the in-Metal dequant for `tl.dot` (the qdot pattern
|
|
24
|
-
// from
|
|
24
|
+
// from mlx's quantized.h qdot pattern). This is the one substantive change.
|
|
25
25
|
// 2. The head is FROZEN (not a LoRA target) → we need only dE (=dh), NOT dC.
|
|
26
26
|
// 3. The LSE cross-vocab-block merge is done in cheap MLX ops on per-block
|
|
27
27
|
// partials, not Metal atomic-logaddexp spinlocks (simpler, same result).
|
|
@@ -289,7 +289,7 @@ const FWD_SG_SOURCE = String.raw`
|
|
|
289
289
|
// memory each step (coalesced). The lane-partial dots reduce with simd_sum. The
|
|
290
290
|
// threadgroup's 4 simdgroups process 4 rows in parallel; BLOCK_B tokens amortize
|
|
291
291
|
// the dequant (each row dequantized once, reused across tokens). Same coalesced
|
|
292
|
-
// pattern as
|
|
292
|
+
// pattern as mlx's quantized.h qdot. h is passed TRANSPOSED [H, M].
|
|
293
293
|
const SGN = TG / 32; // simdgroups per threadgroup (4)
|
|
294
294
|
const FWD_LANE_SOURCE = String.raw`
|
|
295
295
|
const uint tokBlk = threadgroup_position_in_grid.z;
|
package/src/train/job.ts
CHANGED
|
@@ -123,18 +123,6 @@ function parseConfig(raw: Record<string, unknown>): { modelDir: string; dataDir:
|
|
|
123
123
|
export const finetuneRunner: JobRunner = async (emit, config) => {
|
|
124
124
|
const { modelDir, dataDir, cfg } = parseConfig(config);
|
|
125
125
|
|
|
126
|
-
// Gemma/e4b needs these training env flags set BEFORE the model loads — same
|
|
127
|
-
// as the `mlx-bun train` CLI. The subprocess job path doesn't inherit them
|
|
128
|
-
// from the server, so without this a web-submitted ORPO/SFT run on Gemma uses
|
|
129
|
-
// the wrong kernels. ??= so an explicit env (or the CLI) still wins.
|
|
130
|
-
try {
|
|
131
|
-
const isGemma = (await Bun.file(`${modelDir}/config.json`).text()).toLowerCase().includes("gemma");
|
|
132
|
-
if (isGemma) {
|
|
133
|
-
process.env.MLX_BUN_PERF_KERNEL ??= "0";
|
|
134
|
-
process.env.MLX_BUN_FUSED_GELU ??= "0";
|
|
135
|
-
}
|
|
136
|
-
} catch {}
|
|
137
|
-
|
|
138
126
|
emit({ type: "stage", stage: "load", progress: 0.01, message: `loading model ${modelDir}` });
|
|
139
127
|
|
|
140
128
|
const { loadModelConfig } = await import("../config");
|
package/src/train/lora-params.ts
CHANGED
|
@@ -165,15 +165,21 @@ export interface SaveAdapterConfig {
|
|
|
165
165
|
rsLora?: boolean;
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
export interface SaveAdapterOptions {
|
|
169
|
+
/** Override config-file writes for deterministic durability tests. */
|
|
170
|
+
writeFile?: (path: string, data: string) => Promise<unknown>;
|
|
171
|
+
}
|
|
172
|
+
|
|
168
173
|
/** Save the trained adapter into `dir` in the AdapterManager.mount format:
|
|
169
174
|
* adapters.safetensors (lora_a / lora_b tensor names), optiq_lora_config.json,
|
|
170
175
|
* and a PEFT-compatible adapter_config.json. */
|
|
171
|
-
export function saveAdapter(
|
|
176
|
+
export async function saveAdapter(
|
|
172
177
|
lora: TrainableLora,
|
|
173
178
|
dir: string,
|
|
174
179
|
cfg: SaveAdapterConfig,
|
|
175
180
|
appliedRanks: Record<string, number>,
|
|
176
|
-
|
|
181
|
+
options: SaveAdapterOptions = {},
|
|
182
|
+
): Promise<void> {
|
|
177
183
|
mkdirSync(dir, { recursive: true });
|
|
178
184
|
|
|
179
185
|
// Build the native string→array map and insert lora_a / lora_b per target.
|
|
@@ -211,8 +217,6 @@ export function saveAdapter(
|
|
|
211
217
|
applied_ranks: appliedRanks,
|
|
212
218
|
source_model: cfg.baseModel,
|
|
213
219
|
};
|
|
214
|
-
Bun.write(`${dir}/optiq_lora_config.json`, JSON.stringify(optiqCfg, null, 2) + "\n");
|
|
215
|
-
|
|
216
220
|
// PEFT-compatible adapter_config.json (loadable by mlx-lm / PEFT).
|
|
217
221
|
const peftCfg = {
|
|
218
222
|
fine_tune_type: "lora",
|
|
@@ -223,15 +227,22 @@ export function saveAdapter(
|
|
|
223
227
|
fan_in_fan_out: false,
|
|
224
228
|
inference_mode: false,
|
|
225
229
|
init_lora_weights: true,
|
|
226
|
-
|
|
230
|
+
// mlx-bun's `scale` is the numerator before rsLoRA's √rank division.
|
|
231
|
+
// Ordinary PEFT needs alpha/r = scale; rsLoRA needs alpha/√r = scale/√r.
|
|
232
|
+
lora_alpha: cfg.rsLora ? cfg.scale : Math.round(cfg.rank * cfg.scale),
|
|
227
233
|
lora_dropout: 0.0,
|
|
228
234
|
peft_type: "LORA",
|
|
229
235
|
r: cfg.rank,
|
|
230
236
|
target_modules: cfg.targetModules,
|
|
231
237
|
task_type: "CAUSAL_LM",
|
|
238
|
+
use_rslora: cfg.rsLora ?? false,
|
|
232
239
|
optiq: { rank_scaling: cfg.rankScaling, applied_ranks: appliedRanks },
|
|
233
240
|
};
|
|
234
|
-
|
|
241
|
+
const writeFile = options.writeFile ?? ((path: string, data: string) => Bun.write(path, data));
|
|
242
|
+
await Promise.all([
|
|
243
|
+
writeFile(`${dir}/optiq_lora_config.json`, JSON.stringify(optiqCfg, null, 2) + "\n"),
|
|
244
|
+
writeFile(`${dir}/adapter_config.json`, JSON.stringify(peftCfg, null, 2) + "\n"),
|
|
245
|
+
]);
|
|
235
246
|
}
|
|
236
247
|
|
|
237
248
|
/** Dispose all trainable leaves (frees A/B). */
|