mlx-bun 0.0.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/README.md +71 -578
  2. package/bin/mlx-bun.mjs +1 -1
  3. package/docs/README.md +91 -0
  4. package/docs/{design → archive}/hlg-sampling.md +3 -3
  5. package/docs/{design → archive/investigations}/audio-input-plan.md +4 -4
  6. package/docs/{design → archive/investigations}/colibri-glm52-port.md +1 -1
  7. package/docs/{design → archive/investigations}/diffusion-gemma-port.md +3 -3
  8. package/docs/{design → archive/investigations}/faithful-l1-consolidation.md +4 -4
  9. package/docs/{investigations → archive/investigations}/hlg-sampling-investigation.md +1 -1
  10. package/docs/{design → archive/investigations}/minicpm5-decode-megakernel.md +11 -11
  11. package/docs/{design → archive/investigations}/optimization_plan.md +1 -1
  12. package/docs/archive/investigations/pareto-specialized-runtime-findings.md +92 -0
  13. package/docs/{design → archive/investigations}/pre-colibri-stabilization.md +5 -5
  14. package/docs/{design → archive/investigations}/the-dreaming-handoff.md +2 -2
  15. package/docs/{planning → archive/planning}/chat-ui-vision.md +1 -1
  16. package/docs/{planning → archive/planning}/chunk-task-roadmap.md +1 -1
  17. package/docs/{planning → archive/planning}/curve-sampler-research-plan.md +4 -4
  18. package/docs/{planning → archive/planning}/memory-docs-and-dag-plan.md +1 -1
  19. package/docs/{planning → archive/planning}/release-notes-v0.0.9.md +1 -1
  20. package/docs/archive/planning/release-notes-v0.2.0.md +49 -0
  21. package/docs/{planning → archive/planning}/website-readme-pass-plan.md +1 -1
  22. package/docs/design/batching.md +569 -0
  23. package/docs/design/decode-speed-program.md +3178 -169
  24. package/docs/design/dreaming-nightly-pipeline.md +675 -282
  25. package/docs/design/generic-model-support.md +579 -334
  26. package/docs/design/kv-cache.md +680 -0
  27. package/docs/design/orpo-training.md +673 -1239
  28. package/docs/design/speculative-decoding.md +1627 -0
  29. package/docs/design/turboquant.md +2102 -0
  30. package/docs/design/unified-engine-frontier-plan.md +1831 -727
  31. package/docs/design/web-chat-redesign.md +666 -1083
  32. package/docs/planning/PRODUCT_ROADMAP.md +34 -1
  33. package/docs/planning/release-notes-v0.3.0.md +35 -0
  34. package/docs/planning/video-series.md +421 -0
  35. package/docs/reference/benchmarks.md +1162 -0
  36. package/docs/reference/cli.md +395 -149
  37. package/docs/reference/distribution.md +321 -181
  38. package/docs/reference/environment.md +348 -0
  39. package/docs/reference/glossary.md +39 -0
  40. package/docs/reference/library-api.md +580 -142
  41. package/docs/reference/memory.md +227 -64
  42. package/docs/reference/models.md +137 -6
  43. package/docs/reference/server-api.md +938 -422
  44. package/docs/reference/server-config.md +652 -320
  45. package/docs/reference/training.md +393 -254
  46. package/docs/reference/troubleshooting.md +166 -0
  47. package/package.json +10 -5
  48. package/src/admission-plan.ts +18 -0
  49. package/src/anthropic.ts +92 -3
  50. package/src/audio/decode.ts +2 -2
  51. package/src/audio/features.ts +2 -2
  52. package/src/backends/mlx/autoregressive.ts +108 -0
  53. package/src/backends/mlx/batch-group.ts +1646 -0
  54. package/src/backends/mlx/diffusion.ts +39 -0
  55. package/src/backends/mlx/draft-target.ts +47 -0
  56. package/src/backends/mlx/evaluation.ts +105 -0
  57. package/src/backends/mlx/fill-append.ts +45 -0
  58. package/src/backends/mlx/gateway-binding.ts +71 -0
  59. package/src/backends/mlx/graph.ts +38 -0
  60. package/src/backends/mlx/memory-client.ts +189 -0
  61. package/src/backends/mlx/memory-guard.ts +40 -0
  62. package/src/backends/mlx/methods.ts +90 -0
  63. package/src/backends/mlx/model-prompt.ts +164 -0
  64. package/src/backends/mlx/model-serving.ts +79 -0
  65. package/src/backends/mlx/prefill.ts +33 -0
  66. package/src/backends/mlx/request-policy.ts +20 -0
  67. package/src/backends/mlx/rollback.ts +51 -0
  68. package/src/backends/mlx/serial-executor.ts +273 -0
  69. package/src/backends/mlx/speculative.ts +114 -0
  70. package/src/backends/mlx/state-views.ts +26 -0
  71. package/src/backends/mlx/text-engine.ts +73 -0
  72. package/src/cli.ts +189 -61
  73. package/src/client.ts +66 -0
  74. package/src/config.ts +21 -4
  75. package/src/contracts/completion.ts +16 -0
  76. package/src/contracts/execution.ts +49 -0
  77. package/src/contracts/generation.ts +103 -0
  78. package/src/contracts/host.ts +7 -0
  79. package/src/contracts/jobs.ts +66 -0
  80. package/src/contracts/pi-provider.ts +30 -0
  81. package/src/contracts/pi.ts +259 -0
  82. package/src/contracts/resources.ts +18 -0
  83. package/src/contracts/scheduling.ts +27 -0
  84. package/src/contracts/tsconfig.json +14 -0
  85. package/src/diffusion/diffusion-generate.ts +218 -153
  86. package/src/embed.ts +1 -1
  87. package/src/engine/admission.ts +59 -0
  88. package/src/engine/cancellation.ts +38 -0
  89. package/src/engine/engine.ts +56 -0
  90. package/src/engine/execution-coordinator.ts +70 -0
  91. package/src/engine/execution-plan.ts +51 -0
  92. package/src/engine/resources.ts +42 -0
  93. package/src/engine/scheduler.ts +67 -0
  94. package/src/engine/session.ts +247 -0
  95. package/src/eval/README.md +44 -1
  96. package/src/eval/kl.ts +263 -23
  97. package/src/eval/reference-logits.ts +207 -0
  98. package/src/eval/runner.ts +10 -79
  99. package/src/eval/tasks/bfcl.ts +2 -1
  100. package/src/eval/tasks/gsm8k.ts +2 -1
  101. package/src/eval/tasks/hashhop.ts +2 -1
  102. package/src/eval/tasks/humaneval.ts +5 -4
  103. package/src/eval/tasks/ifeval.ts +2 -1
  104. package/src/eval/tasks/mmlu.ts +2 -1
  105. package/src/expert-io.ts +3 -1
  106. package/src/expert-offload.ts +3 -1
  107. package/src/fill/echo-index.ts +188 -0
  108. package/src/fill/fill-session.ts +452 -0
  109. package/src/fill/proposal.ts +68 -0
  110. package/src/fill/schema-rows.ts +506 -0
  111. package/src/fill/tool-boundary.ts +103 -0
  112. package/src/fit.ts +24 -43
  113. package/src/generate.ts +740 -337
  114. package/src/grammar.ts +14 -8
  115. package/src/harness-pi.ts +15 -34
  116. package/src/hub-rest.ts +4 -4
  117. package/src/index.ts +27 -0
  118. package/src/inference/denoising.ts +17 -0
  119. package/src/inference/graph.ts +33 -0
  120. package/src/inference/prefill.ts +39 -0
  121. package/src/inference/rollback.ts +7 -0
  122. package/src/jobs/db.ts +4 -0
  123. package/src/jobs/index.ts +2 -0
  124. package/src/jobs/job-entry.ts +15 -14
  125. package/src/jobs/runner.ts +98 -13
  126. package/src/jobs/task-client.ts +19 -0
  127. package/src/jobs/types.ts +2 -58
  128. package/src/kv-scheme.ts +199 -0
  129. package/src/kv-store.ts +459 -234
  130. package/src/lab/README.md +18 -0
  131. package/src/{assets → lab/curve}/curve-designer.html +2 -2
  132. package/src/{curve-sampler.ts → lab/curve/curve-sampler.ts} +2 -2
  133. package/src/{expert-trace.ts → lab/expert-trace/expert-trace.ts} +7 -5
  134. package/src/{model → lab/paged-kv}/paged-kv.ts +9 -6
  135. package/src/library.ts +40 -0
  136. package/src/lora.ts +18 -0
  137. package/src/media-fetch.ts +20 -4
  138. package/src/memory/article.ts +1 -1
  139. package/src/memory/chunk.ts +1 -1
  140. package/src/memory/model.ts +32 -170
  141. package/src/memory/prompts.ts +1 -1
  142. package/src/memory/rest.ts +1 -1
  143. package/src/memory/schedule.ts +1 -1
  144. package/src/memory/stages.ts +4 -1
  145. package/src/memory/vault.ts +3 -4
  146. package/src/mlx/array.ts +9 -10
  147. package/src/mlx/compile.ts +12 -2
  148. package/src/mlx/ffi.ts +66 -22
  149. package/src/mlx/materialize.ts +23 -0
  150. package/src/mlx/metal-kernel.ts +10 -11
  151. package/src/mlx/ops.ts +64 -19
  152. package/src/mlx/quantized-rows.ts +36 -0
  153. package/src/mlx/token-bitmask.ts +52 -0
  154. package/src/mlx/turboquant-kv-decode.ts +82 -0
  155. package/src/mlx/turboquant-kv-inverse.ts +122 -0
  156. package/src/mlx/turboquant-ops.ts +33 -3
  157. package/src/mlx/turboquant-tables.ts +2 -2
  158. package/src/model/batched-mask.ts +9 -3
  159. package/src/model/batched-quant.ts +2 -2
  160. package/src/model/batched-rotating-quant.ts +45 -99
  161. package/src/model/batched-rotating-state.ts +73 -0
  162. package/src/model/batched-rotating.ts +57 -106
  163. package/src/model/batched-row-storage.ts +127 -0
  164. package/src/model/compiled-decode.ts +4 -3
  165. package/src/model/diffusion-gemma.ts +8 -8
  166. package/src/model/factory.ts +87 -49
  167. package/src/model/fingerprint.ts +1 -1
  168. package/src/model/flash-attention.ts +3 -3
  169. package/src/model/gemma4-base.ts +187 -17
  170. package/src/model/gemma4.ts +6 -6
  171. package/src/model/generated/gemma4-12b.ts +52 -148
  172. package/src/model/generated/gemma4-26b.ts +34 -94
  173. package/src/model/generated/gemma4-e4b.ts +28 -76
  174. package/src/model/glm52-cache.ts +19 -9
  175. package/src/model/glm52-dsa.ts +13 -9
  176. package/src/model/glm52-memory.ts +28 -1
  177. package/src/model/implementation.ts +69 -0
  178. package/src/model/minicpm5.ts +7 -8
  179. package/src/model/profile.ts +443 -0
  180. package/src/model/qwen-append.ts +12 -0
  181. package/src/model/qwen-conv.ts +52 -0
  182. package/src/model/qwen3-delta.ts +98 -2
  183. package/src/model/qwen3-mrope.ts +252 -0
  184. package/src/model/qwen3_5-checkpoint.ts +164 -0
  185. package/src/model/qwen3_5.ts +336 -60
  186. package/src/model/support.ts +1 -1
  187. package/src/model/trellis-balanced-scatter.ts +51 -0
  188. package/src/model/trellis-linear.ts +672 -0
  189. package/src/model/trellis-shared-m.ts +151 -0
  190. package/src/model/trellis-shared-scatter.ts +144 -0
  191. package/src/model/trellis-splitk-prefill.ts +158 -0
  192. package/src/model/trellis-tiled-prefill.ts +136 -0
  193. package/src/model/trellis-vector-expand.ts +62 -0
  194. package/src/model/trellis-wide-prefill.ts +94 -0
  195. package/src/model/universal/dense.ts +1 -1
  196. package/src/model/universal/modules.ts +8 -1
  197. package/src/native/frame_extract.swift +140 -0
  198. package/src/native-pack.ts +15 -7
  199. package/src/pi-provider.ts +6 -64
  200. package/src/pi-web.ts +14 -320
  201. package/src/prompt-cache.ts +97 -54
  202. package/src/quantize/allocator.ts +1 -1
  203. package/src/quantize/atomic-output.ts +38 -0
  204. package/src/quantize/calibration.ts +2 -1
  205. package/src/quantize/config-writer.ts +16 -3
  206. package/src/quantize/index.ts +28 -1
  207. package/src/quantize/job.ts +11 -0
  208. package/src/quantize/quantizer.ts +265 -100
  209. package/src/quantize/rotate.ts +603 -0
  210. package/src/quantize/safetensors-writer.ts +79 -1
  211. package/src/quantize/sensitivity.ts +41 -59
  212. package/src/quantize/trellis.ts +586 -0
  213. package/src/quantize/weight-transform.ts +292 -0
  214. package/src/responses.ts +130 -3
  215. package/src/runtime-config.ts +81 -0
  216. package/src/sampler.ts +276 -4
  217. package/src/serve/admin-routes.ts +184 -0
  218. package/src/serve/aux-routes.ts +132 -0
  219. package/src/serve/batch-scheduler.ts +8 -1558
  220. package/src/serve/chat-request.ts +391 -0
  221. package/src/serve/chat-stage.ts +195 -0
  222. package/src/serve/checkpoint-identity.ts +64 -0
  223. package/src/serve/completion-executor.ts +354 -0
  224. package/src/serve/completion-sink.ts +157 -0
  225. package/src/serve/discovery-routes.ts +204 -0
  226. package/src/serve/generation-gateway.ts +211 -243
  227. package/src/serve/http.ts +159 -0
  228. package/src/serve/inference-request.ts +79 -0
  229. package/src/serve/isolate.ts +297 -105
  230. package/src/serve/kv-budget.ts +14 -0
  231. package/src/serve/lab-routes.ts +341 -0
  232. package/src/serve/lane-registry.ts +2 -1
  233. package/src/serve/model-admin-routes.ts +155 -0
  234. package/src/serve/model-binding.ts +43 -0
  235. package/src/serve/model-host.ts +512 -0
  236. package/src/serve/openai-wire.ts +103 -0
  237. package/src/serve/parent-application.ts +56 -0
  238. package/src/serve/pipeline.ts +33 -0
  239. package/src/serve/preparation.ts +33 -0
  240. package/src/serve/prompt-response-trace.ts +147 -0
  241. package/src/serve/request-plan.ts +162 -0
  242. package/src/serve/request-prep.ts +346 -0
  243. package/src/serve/response-lease.ts +24 -0
  244. package/src/serve/responses-client.ts +69 -0
  245. package/src/serve/session-completion-engine.ts +110 -0
  246. package/src/serve/session-search.ts +1 -1
  247. package/src/serve/static-routes.ts +101 -0
  248. package/src/serve/text-completion-stage.ts +104 -0
  249. package/src/serve/token-streams.ts +519 -0
  250. package/src/server.ts +523 -3551
  251. package/src/spec/assistant-source.ts +10 -44
  252. package/src/spec/deepspec-source.ts +6 -6
  253. package/src/spec/dflash-source.ts +9 -8
  254. package/src/spec/dspark/ab-stats.ts +3 -3
  255. package/src/spec/dspark/calibration.ts +2 -2
  256. package/src/spec/dspark/deepspec-module.ts +2 -2
  257. package/src/spec/dspark/generate-dflash.ts +2 -2
  258. package/src/spec/dspark/generate.ts +2 -2
  259. package/src/spec/dspark/loader.ts +1 -1
  260. package/src/spec/dspark/module-dflash.ts +5 -4
  261. package/src/spec/dspark/module.ts +3 -3
  262. package/src/spec/dspark/quantize-drafter.ts +1 -1
  263. package/src/spec/generate.ts +1 -1
  264. package/src/spec/glm52-mtp-source.ts +9 -1
  265. package/src/spec/ngram-source.ts +1 -1
  266. package/src/spec/prefix-state.ts +45 -0
  267. package/src/spec/qwen-mtp-source.ts +528 -0
  268. package/src/spec/serve-loop.ts +179 -213
  269. package/src/spec/source.ts +42 -10
  270. package/src/spec/two-model.ts +1 -1
  271. package/src/ssd-cache.ts +95 -24
  272. package/src/ssd-durability.ts +207 -0
  273. package/src/tool-call.ts +51 -14
  274. package/src/train/flash-cce.ts +14 -13
  275. package/src/train/forward.ts +38 -1
  276. package/src/train/loss.ts +3 -2
  277. package/src/train/prefix-shared.ts +5 -1
  278. package/src/train/segmented.ts +9 -6
  279. package/src/train/trainer.ts +9 -8
  280. package/src/vision/preprocess.ts +1 -1
  281. package/src/vision/prompt.ts +48 -2
  282. package/src/vision/qwen3vl-preprocess.ts +409 -0
  283. package/src/vision/qwen3vl-prompt.ts +196 -0
  284. package/src/vision/qwen3vl-tower.ts +555 -0
  285. package/src/vision/video-frames.ts +148 -0
  286. package/src/web/app.html +1 -1
  287. package/src/web/app.js +15 -6
  288. package/src/web/src/adapters-panel.ts +3 -3
  289. package/src/web/src/assistant.ts +2 -36
  290. package/src/web/src/chat.ts +16 -9
  291. package/src/web/src/composer.ts +4 -4
  292. package/src/web/src/hub.ts +1 -1
  293. package/src/web/src/markdown.ts +0 -0
  294. package/src/web/src/memory-panel.ts +1 -1
  295. package/src/web/src/model-picker.ts +1 -1
  296. package/src/web/src/palette.ts +1 -1
  297. package/src/web/src/protocol.ts +3 -39
  298. package/src/web/src/sessions.ts +1 -1
  299. package/src/web/src/ui-catalog.ts +4 -18
  300. package/src/web-assets.ts +47 -0
  301. package/src/weights.ts +134 -33
  302. package/docs/archive/mlx-bun-lab-report.html +0 -275
  303. package/docs/archive/wwdc-mlx-bun.html +0 -848
  304. package/docs/design/adapters-end-to-end.md +0 -205
  305. package/docs/design/batching-perf-path.md +0 -255
  306. package/docs/design/batching-v2-plan.md +0 -529
  307. package/docs/design/bucketing-stage.md +0 -197
  308. package/docs/design/compat-cli-surface-design.md +0 -230
  309. package/docs/design/docs-reorg-plan.md +0 -165
  310. package/docs/design/dspark-serving-program.md +0 -371
  311. package/docs/design/dspark-speculative-decoding.md +0 -268
  312. package/docs/design/grammar-spec-batching-integration.md +0 -301
  313. package/docs/design/memory-inference-path.md +0 -422
  314. package/docs/design/memory-synthesis.md +0 -287
  315. package/docs/design/memory-system.md +0 -237
  316. package/docs/design/mlx-lm-tool-parity-plan.md +0 -545
  317. package/docs/design/omlx-adoption-map.md +0 -98
  318. package/docs/design/orpo-dynamic-lambda.md +0 -220
  319. package/docs/design/orpo-future-enhancements.md +0 -340
  320. package/docs/design/paged-kv-cache.md +0 -214
  321. package/docs/design/parallel-slots.md +0 -567
  322. package/docs/design/parity-tier-dag.md +0 -161
  323. package/docs/design/repo-cleanup-plan.md +0 -189
  324. package/docs/design/runtime-isolation.md +0 -263
  325. package/docs/design/segmented-backward-training.md +0 -543
  326. package/docs/design/spec-decode-larger-targets.md +0 -229
  327. package/docs/design/ssd-kv-cold-tier.md +0 -288
  328. package/docs/design/structured-output.md +0 -484
  329. package/docs/design/tauri-desktop-app.md +0 -127
  330. package/docs/design/the-dreaming-master-plan.md +0 -445
  331. package/docs/design/turboquant-kv.md +0 -235
  332. package/docs/design/w4a16-compute-precision-spike.md +0 -232
  333. package/docs/design/web-chat-beat-matrix.md +0 -315
  334. package/docs/design/write-pipeline-entity.md +0 -468
  335. package/docs/investigations/curve-runs/bisector-route.json +0 -98
  336. package/docs/investigations/curve-runs/bisector-trace.json +0 -1393
  337. package/docs/investigations/curve-runs/curve-terrain.json +0 -1179
  338. package/docs/investigations/curve-runs/curve-terrain.svg +0 -42
  339. package/docs/investigations/hlg-ab.html +0 -34
  340. package/docs/investigations/hlg-explorer.html +0 -238
  341. package/docs/investigations/hlg-figs/cliff.svg +0 -1
  342. package/docs/investigations/hlg-figs/cross.svg +0 -1
  343. package/docs/investigations/hlg-figs/edges.svg +0 -1
  344. package/docs/investigations/hlg-figs/k20-grids.svg +0 -1
  345. package/docs/investigations/hlg-figs/k20-peaks.svg +0 -1
  346. package/docs/investigations/hlg-figs/lw-curve.svg +0 -1
  347. package/docs/investigations/hlg-figs/terrain.svg +0 -1
  348. package/docs/investigations/hlg-report.html +0 -262
  349. package/docs/investigations/hlg-runs/hlg-ab.json +0 -149
  350. package/docs/investigations/hlg-runs/hlg-blind-prompts.md +0 -87
  351. package/docs/investigations/hlg-runs/hlg-blind.json +0 -107
  352. package/docs/investigations/hlg-runs/hlg-cliff.json +0 -197
  353. package/docs/investigations/hlg-runs/hlg-cross.json +0 -505
  354. package/docs/investigations/hlg-runs/hlg-edge.json +0 -388
  355. package/docs/investigations/hlg-runs/hlg-eval1.json +0 -25
  356. package/docs/investigations/hlg-runs/hlg-frontier.json +0 -86
  357. package/docs/investigations/hlg-runs/hlg-grid.json +0 -242
  358. package/docs/investigations/hlg-runs/hlg-grid2.json +0 -343
  359. package/docs/investigations/hlg-runs/hlg-lw-coarse.json +0 -110
  360. package/docs/investigations/hlg-runs/hlg-map.json +0 -383
  361. package/docs/investigations/hlg-runs/run0-original.log +0 -159
  362. package/docs/investigations/hlg-runs/runA-recommended.log +0 -131
  363. package/docs/investigations/hlg-runs/runAA-cliff-cpm5.log +0 -26
  364. package/docs/investigations/hlg-runs/runAB-grid2-e4b.log +0 -18
  365. package/docs/investigations/hlg-runs/runAC-peak-e4b-partial.log +0 -25
  366. package/docs/investigations/hlg-runs/runAD-ab-samples.log +0 -8
  367. package/docs/investigations/hlg-runs/runAE-edge-e4b.log +0 -51
  368. package/docs/investigations/hlg-runs/runAF-logit-calibration.log +0 -10
  369. package/docs/investigations/hlg-runs/runAG-eval-config2.log +0 -16
  370. package/docs/investigations/hlg-runs/runB-gain-variants.log +0 -192
  371. package/docs/investigations/hlg-runs/runC-pivots.log +0 -162
  372. package/docs/investigations/hlg-runs/runD-oetf.log +0 -132
  373. package/docs/investigations/hlg-runs/runE-eotf.log +0 -162
  374. package/docs/investigations/hlg-runs/runF-shaper-working.log +0 -86
  375. package/docs/investigations/hlg-runs/runG-shaper-sweep.log +0 -101
  376. package/docs/investigations/hlg-runs/runH-wsweep.log +0 -176
  377. package/docs/investigations/hlg-runs/runI-asweep.log +0 -176
  378. package/docs/investigations/hlg-runs/runJ-knobmap.log +0 -49
  379. package/docs/investigations/hlg-runs/runK-frontier.log +0 -19
  380. package/docs/investigations/hlg-runs/runL-widemap.log +0 -65
  381. package/docs/investigations/hlg-runs/runM-frontier-emb.log +0 -15
  382. package/docs/investigations/hlg-runs/runN-verify.log +0 -116
  383. package/docs/investigations/hlg-runs/runO-frontier-seed5000.log +0 -15
  384. package/docs/investigations/hlg-runs/runP-grid-AxSm.log +0 -15
  385. package/docs/investigations/hlg-runs/runQ-grid-tgW.log +0 -15
  386. package/docs/investigations/hlg-runs/runR-blind-transcript.log +0 -79
  387. package/docs/investigations/hlg-runs/runS-cross-coherence.log +0 -33
  388. package/docs/investigations/hlg-runs/runT-cross-cpm5.log +0 -33
  389. package/docs/investigations/hlg-runs/runU-cross-12b.log +0 -33
  390. package/docs/investigations/hlg-runs/runV-lw-e4b.log +0 -22
  391. package/docs/investigations/hlg-runs/runW-lw-12b.log +0 -22
  392. package/docs/investigations/hlg-runs/runX-lw-cpm5.log +0 -22
  393. package/docs/investigations/hlg-runs/runY-cliff-e4b.log +0 -26
  394. package/docs/investigations/hlg-runs/runZ-cliff-12b.log +0 -26
  395. package/docs/planning/IDEAS.md +0 -69
  396. package/docs/reference/embedding.md +0 -197
  397. package/docs/reference/features-matrix.md +0 -100
  398. package/docs/reference/orpo-quickstart.md +0 -135
  399. package/src/flags.ts +0 -13
  400. /package/docs/{investigations → archive/investigations}/chunk-finetune-experiment.md +0 -0
  401. /package/docs/{investigations → archive/investigations}/colibri-oracle-pin.md +0 -0
  402. /package/docs/{investigations → archive/investigations}/curve-bisector-routing.md +0 -0
  403. /package/docs/{investigations → archive/investigations}/decode-roofline-lookagain.md +0 -0
  404. /package/docs/{investigations → archive/investigations}/dspark-handoff.md +0 -0
  405. /package/docs/{investigations → archive/investigations}/expert-offload-single-user-moe.md +0 -0
  406. /package/docs/{investigations → archive/investigations}/indexshare-performance-spike.md +0 -0
  407. /package/docs/{investigations → archive/investigations}/kernel-perf-review-2026-07.md +0 -0
  408. /package/docs/{investigations → archive/investigations}/lab-build-journal.md +0 -0
  409. /package/docs/{investigations → archive/investigations}/openwiki-evaluation.md +0 -0
  410. /package/docs/{investigations → archive/investigations}/orpo-base-uf-experiment-and-directions.md +0 -0
  411. /package/docs/{investigations → archive/investigations}/orpo-flash-cce-pin-leak.md +0 -0
  412. /package/docs/{investigations → archive/investigations}/orpo-uf-testing-handoff.md +0 -0
  413. /package/docs/{investigations → archive/investigations}/pi-builtin-investigation.md +0 -0
  414. /package/docs/{investigations → archive/investigations}/segmented-backward-handoff.md +0 -0
  415. /package/docs/{investigations → archive/investigations}/starter-model-port-handoff.md +0 -0
  416. /package/docs/{investigations → archive/investigations}/steel-flash-cce-handoff.md +0 -0
  417. /package/docs/{investigations → archive/investigations}/trainer-validation-experiment.md +0 -0
  418. /package/docs/{planning → archive/planning}/chat-ui-vision-memory-first.md +0 -0
  419. /package/docs/{planning → archive/planning}/journal.md +0 -0
  420. /package/docs/{planning → archive/planning}/pi-integration-review.md +0 -0
  421. /package/docs/{planning → archive/planning}/release-notes-v0.0.10.md +0 -0
  422. /package/docs/{planning → archive/planning}/release-notes-v0.0.11.md +0 -0
  423. /package/docs/{planning → archive/planning}/release-notes-v0.0.12.md +0 -0
  424. /package/docs/{planning → archive/planning}/release-notes-v0.0.13.md +0 -0
  425. /package/docs/{planning → archive/planning}/web-ui-pass-plan.md +0 -0
  426. /package/{docs/investigations → src/serve/assets}/curve-terrain.html +0 -0
  427. /package/{docs/dag → src/serve/assets}/training-inference-map.html +0 -0
@@ -0,0 +1,512 @@
1
+ // Model-host lifecycle: load a model directory into the ServerContext that
2
+ // createServer serves (model + tokenizer + template + lazy vision/audio
3
+ // towers + adapters + optional draft), and the on-demand tower getters.
4
+ // Extracted from src/server.ts (repo-taming Phase 4).
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { bindLegacyDraftTarget } from "../backends/mlx/draft-target";
7
+ import { loadModelConfig, type KvQuantSpec, type ModelConfig } from "../config";
8
+ import { Weights } from "../weights";
9
+ import { Gemma4Model } from "../model/gemma4";
10
+ import {
11
+ createModel,
12
+ openGlm52RuntimeModel,
13
+ type Glm52RuntimeOpenOptions,
14
+ type RuntimeModel,
15
+ } from "../model/factory";
16
+ import { Glm52Model } from "../model/glm52";
17
+ import { type Glm52MemoryPlan } from "../model/glm52-memory";
18
+ import { resolveModelProfile, type ResolvedModelProfile } from "../model/profile";
19
+ import { Glm52NativeMtpProvider } from "../spec/glm52-mtp-source";
20
+ import { ChatTemplate } from "../chat-template";
21
+ import { loadTokenizer, type LoadedTokenizer } from "../tokenizer";
22
+ import { AdapterManager } from "../lora";
23
+ import { VisionTower } from "../vision/embedder";
24
+ import { SiglipVisionTower, parseSiglipConfig } from "../vision/siglip";
25
+ import { Qwen3VLVisionTower } from "../vision/qwen3vl-tower";
26
+ import { Qwen35Model } from "../model/qwen3_5";
27
+ import type { AudioTokenIds, VisionTokenIds, VisionEncoder } from "../vision/prompt";
28
+ import { AudioTower, parseAudioConfig } from "../audio/conformer";
29
+ import { sidecarShipsAudioTower } from "../registry";
30
+ import { fit } from "../fit";
31
+ import type { ModelImplementationProvider } from "../model/implementation";
32
+ import type { ServedModelInfo } from "./model-binding";
33
+
34
+ export interface AdapterService extends Pick<AdapterManager, keyof AdapterManager> {}
35
+
36
+ export interface ServerContext<Model = RuntimeModel> {
37
+ serving?: import("./model-binding").ModelServingBinding;
38
+ /** State serialization supplied by this model/backend implementation. */
39
+ stateCodecs?: import("../kv-store").CacheCodecProvider;
40
+ model: Model;
41
+ /** Declared external artifact/family profile that selected model
42
+ * construction. Request-level methods are resolved separately. */
43
+ profile: ResolvedModelProfile;
44
+ tokenizer: LoadedTokenizer;
45
+ template: ChatTemplate;
46
+ modelId: string;
47
+ /** Lazily-loaded vision tower cache — null until the first image request
48
+ * (see `getVisionTower`). The tower (SigLIP ~hundreds of MB, encoder-free
49
+ * smaller) is not loaded for text-only sessions. */
50
+ vision: VisionEncoder | null;
51
+ /** Loads + selects the vision tower on demand; null when the model has no
52
+ * (supported) vision sidecar. Invoked at most once, then cached in
53
+ * `vision`. */
54
+ loadVision: (() => VisionEncoder) | null;
55
+ visionTokenIds: VisionTokenIds;
56
+ /** Lazily-loaded Conformer audio tower — null until the first audio
57
+ * request (see `getAudioTower`). Same sidecar file as vision
58
+ * (optiq_vision.safetensors), separate tower; text-only sessions never
59
+ * pay for it. */
60
+ audio: AudioTower | null;
61
+ /** Loads the audio tower on demand; null when the model can't do audio
62
+ * (no `audio_config` in config.json or no sidecar). No flags — audio
63
+ * auto-enables exactly like vision. */
64
+ loadAudio: (() => AudioTower) | null;
65
+ /** null when the model has no `audio_config` (audio-incapable). */
66
+ audioTokenIds: AudioTokenIds | null;
67
+ adapters: AdapterService;
68
+ /** Per-layer KV quantization from the repo's kv_config.json (null if
69
+ * absent). Applied by default — optiq serve's headline behavior;
70
+ * ServerOptions.kvQuant overrides ("off" | uniform bits). */
71
+ kvConfig: KvQuantSpec[] | null;
72
+ /** Model-author recommended sampling from generation_config.json —
73
+ * optiq serve injects these as server defaults (gen_config.py);
74
+ * explicit request fields always win. */
75
+ genDefaults: GenSamplingDefaults;
76
+ /** Speculative decoding (`serve --draft-model`, mlx_lm.server parity).
77
+ * Server-level: when set, EVERY request routes to the serial lane
78
+ * (upstream: is_batchable = draft is None) and spec-eligible ones decode
79
+ * through src/spec/serve-loop.ts. null = no draft configured. */
80
+ draft?: {
81
+ provider: import("../spec/source").DraftProvider;
82
+ numDraftTokens: number;
83
+ } | null;
84
+ /** Present only for the direct Colibri GLM runtime. This is the exact
85
+ * header-derived process equation used before opening resident state. */
86
+ glmMemoryPlan?: Glm52MemoryPlan | null;
87
+ }
88
+
89
+ export type ServingContext = ServerContext<import("./model-binding").ServedModelInfo>;
90
+
91
+ export interface ModelHostSource {
92
+ readonly modelDir: string;
93
+ readonly modelId: string | undefined;
94
+ readonly options: Omit<LoadContextOptions, "implementations">;
95
+ }
96
+
97
+ export interface LoadContextOptions<Model extends ServedModelInfo = RuntimeModel> {
98
+ /** Engine-owned complete implementations may own their loader and methods.
99
+ * Selection happens before opening the default resident or streamed weights. */
100
+ implementations?: ModelImplementationProvider<ModelHostSource, Promise<ServerContext<Model>>>;
101
+ profiles?: import("../model/profile").ResolveModelProfileOptions;
102
+ memoryBudgetBytes?: number;
103
+ /** Direct Colibri runtime/resource overrides. Ignored by other models. */
104
+ glm?: Glm52RuntimeOpenOptions;
105
+ /** Snapshot dir of a draft model for speculative decoding
106
+ * (`--draft-model`). Loaded alongside the target; the pair must share
107
+ * a tokenizer family. */
108
+ draftModelDir?: string;
109
+ /** Drafts per round (`--num-draft-tokens`, mlx_lm.server default 3). */
110
+ numDraftTokens?: number;
111
+ /** Draft-provider kind override (`--draft-kind`). */
112
+ draftKind?: DraftKind;
113
+ ngramMax?: number;
114
+ ngramMin?: number;
115
+ }
116
+
117
+ export interface GenSamplingDefaults {
118
+ temperature?: number;
119
+ topP?: number;
120
+ topK?: number;
121
+ repetitionPenalty?: number;
122
+ }
123
+
124
+ export type DraftKind = "dspark" | "deepspec" | "assistant" | "two-model" | "ngram" | "mtp";
125
+
126
+ /** Detect the draft artifact's kind so the right provider is loaded. All
127
+ * providers share ONE serve loop (src/spec/serve-loop.ts). Exported for the
128
+ * bench harness (scripts/bench-matrix.ts features) — one detection, no drift.
129
+ * "ngram" is never detected — it has no artifact (model-free prompt lookup,
130
+ * src/spec/ngram-source.ts) and mounts via an explicit `--draft-kind ngram`. */
131
+ export async function detectDraftKind(dir: string): Promise<DraftKind> {
132
+ if (await Bun.file(`${dir}/dspark.json`).exists()) return "dspark"; // our trained module
133
+ try {
134
+ const cfg = (await Bun.file(`${dir}/config.json`).json()) as {
135
+ model_type?: string;
136
+ architectures?: string[];
137
+ };
138
+ // DeepSeek's released DSpark drafters (DeepSpec reference): no
139
+ // dspark.json, plain HF config stamped Gemma4DSparkModel.
140
+ if (cfg.architectures?.[0] === "Gemma4DSparkModel") return "deepspec";
141
+ if (String(cfg.model_type ?? "").includes("assistant")) return "assistant";
142
+ // Native MTP heads split from a qwen3_5-family release
143
+ // (mlx-community/Qwen3.8-27B-MTP-*): model_type "qwen3_5_mtp". The
144
+ // target's recurrent DeltaNet caches roll back via the serve loop's
145
+ // spec-round snapshot/replay contract (SSMCache.specRound*).
146
+ if (String(cfg.model_type ?? "").endsWith("_mtp")) return "mtp";
147
+ } catch {
148
+ // no/unreadable config → fall through to a full second model
149
+ }
150
+ return "two-model";
151
+ }
152
+
153
+ async function loadGenSamplingDefaults(modelDir: string): Promise<GenSamplingDefaults> {
154
+ const file = Bun.file(`${modelDir}/generation_config.json`);
155
+ if (!(await file.exists())) return {};
156
+ try {
157
+ const raw = (await file.json()) as Record<string, unknown>;
158
+ const num = (v: unknown) => (typeof v === "number" ? v : undefined);
159
+ return {
160
+ temperature: num(raw.temperature),
161
+ topP: num(raw.top_p),
162
+ topK: num(raw.top_k),
163
+ repetitionPenalty: num(raw.repetition_penalty),
164
+ };
165
+ } catch {
166
+ return {};
167
+ }
168
+ }
169
+
170
+ export function loadContext<Model extends ServedModelInfo>(
171
+ modelDir: string, modelId: string | undefined,
172
+ opts: LoadContextOptions<Model> & {
173
+ implementations: ModelImplementationProvider<ModelHostSource, Promise<ServerContext<Model>>>;
174
+ },
175
+ ): Promise<ServerContext<Model>>;
176
+ export function loadContext(modelDir: string, modelId?: string, opts?: LoadContextOptions): Promise<ServerContext>;
177
+ export function loadContext<Model extends ServedModelInfo>(
178
+ modelDir: string, modelId: string | undefined, opts: LoadContextOptions<Model>,
179
+ ): Promise<ServingContext>;
180
+ export async function loadContext(
181
+ modelDir: string, modelId?: string,
182
+ opts: LoadContextOptions<ServedModelInfo> = {},
183
+ ): Promise<ServingContext> {
184
+ const config = await loadModelConfig(modelDir);
185
+ const profile = resolveModelProfile(config, opts.profiles);
186
+ if (opts.implementations) {
187
+ const implementation = opts.implementations.select(config, profile);
188
+ const { implementations: _provider, ...options } = opts;
189
+ return implementation.create({ modelDir, modelId, options }, config, profile);
190
+ }
191
+ const glm = profile.profile.execution.loader === "colibri";
192
+ // Bundled MTP companion: `--draft-kind mtp` with no --draft-model resolves
193
+ // to the artifact's own mtp/ subfolder (single-repo packaging — the
194
+ // companion is a complete model dir the provider already loads). Explicit
195
+ // --draft-model still wins; a missing bundle is a clear refusal below.
196
+ if (opts.draftKind === "mtp" && !opts.draftModelDir) {
197
+ const bundled = `${modelDir}/mtp`;
198
+ if (await Bun.file(`${bundled}/config.json`).exists()) {
199
+ opts = { ...opts, draftModelDir: bundled };
200
+ } else {
201
+ throw new Error(
202
+ `--draft-kind mtp needs a companion: pass --draft-model <dir> or use ` +
203
+ `an artifact that bundles one at <model>/mtp/ (none at ${bundled})`,
204
+ );
205
+ }
206
+ }
207
+ const externalDraft = opts.draftModelDir !== undefined || opts.draftKind !== undefined;
208
+ const resolvedDraftKind = opts.draftModelDir
209
+ ? opts.draftKind ?? await detectDraftKind(opts.draftModelDir)
210
+ : opts.draftKind;
211
+ if (glm && externalDraft && opts.glm?.enableMtp === true)
212
+ throw new Error("native GLM MTP and --draft-model/--draft-kind are mutually exclusive");
213
+ let weights: Weights | null = null;
214
+ let model!: RuntimeModel;
215
+ let glmMemoryPlan: Glm52MemoryPlan | null = null;
216
+ if (glm) {
217
+ const enableNativeMtp = !externalDraft && opts.glm?.enableMtp !== false;
218
+ const opened = await openGlm52RuntimeModel(modelDir, {
219
+ ...opts.glm,
220
+ memoryBudgetBytes: opts.memoryBudgetBytes ?? opts.glm?.memoryBudgetBytes,
221
+ // Every drafter owns the serial speculative lane. Do not reserve a
222
+ // simultaneous ordinary batch that cannot be admitted while it is live.
223
+ batchSize: enableNativeMtp || externalDraft ? 1 : opts.glm?.batchSize,
224
+ // An explicit alternate drafter owns the one speculative lane.
225
+ enableMtp: enableNativeMtp,
226
+ });
227
+ model = opened.model;
228
+ glmMemoryPlan = opened.plan;
229
+ } else {
230
+ weights = await Weights.open(modelDir);
231
+ }
232
+ // memoryBudget enforcement at load (Phase 5): Weights.open only mmaps
233
+ // (no GPU allocation yet), so a model whose weights can never serve
234
+ // within the budget is refused HERE — before any unified-memory
235
+ // commitment — with an actionable error instead of a Metal OOM later.
236
+ if (!glm && opts.memoryBudgetBytes) {
237
+ const weightsBytes = [...weights!.shards.files.values()]
238
+ .reduce((a, f) => a + f.mmap.size, 0);
239
+ const report = fit(config, weightsBytes, 1, undefined, undefined, 0, opts.memoryBudgetBytes);
240
+ if (report.maxSafeContext < 1)
241
+ throw new Error(
242
+ `model does not fit the memory budget: weights ${(weightsBytes / 1e9).toFixed(2)} GB ` +
243
+ `+ prefill transient leave no room for any context within ` +
244
+ `${(opts.memoryBudgetBytes / 1e9).toFixed(2)} GB`,
245
+ );
246
+ }
247
+ if (!glm) model = createModel(weights!, config, profile);
248
+ const tokenizer = await loadTokenizer(modelDir);
249
+ // Generation must stop on the tokenizer's eos_token — the chat turn
250
+ // terminator (e.g. Qwen <|im_end|> = 248046). Some configs (Qwen3.5-4B)
251
+ // declare a different eos_token_id in config.json than the chat format
252
+ // emits, so without this a turn never ends and generation runs away,
253
+ // hallucinating both sides of the dialogue until max_tokens. mlx-lm stops on
254
+ // the tokenizer eos; union it in. No-op when already present (Gemma, 27B).
255
+ if (tokenizer.eosTokenId != null && !config.eosTokenIds.includes(tokenizer.eosTokenId))
256
+ config.eosTokenIds = [...config.eosTokenIds, tokenizer.eosTokenId];
257
+
258
+ // Speculative decoding: load the draft (mlx_lm.server --draft-model). The
259
+ // draft artifact's KIND selects the provider — all three share ONE serve
260
+ // loop (src/spec/serve-loop.ts): dspark.json → DSpark (KV-injected), a
261
+ // *_assistant config → the optiq KV-borrowing Gemma drafter, otherwise a
262
+ // full second model (mlx-lm parity). `--draft-kind` overrides the detect.
263
+ let draft: ServerContext["draft"] = null;
264
+ if (opts.draftKind === "ngram") {
265
+ // Model-free prompt lookup: no artifact, no dir, no probe/budget concerns
266
+ // (weightsBytes 0, open() never throws). Default γ=10 per the reference
267
+ // implementation — drafting is free, so wide blocks cost only verify-window
268
+ // width when wrong.
269
+ if (opts.draftModelDir)
270
+ throw new Error(
271
+ "--draft-kind ngram is model-free — drop --draft-model (it would be ignored)",
272
+ );
273
+ const { NgramProvider } = await import("../spec/ngram-source");
274
+ draft = {
275
+ provider: new NgramProvider({ max: opts.ngramMax, min: opts.ngramMin }),
276
+ numDraftTokens: Math.max(1, opts.numDraftTokens ?? 10),
277
+ };
278
+ } else if (opts.draftModelDir) {
279
+ const dir = opts.draftModelDir;
280
+ const kind = resolvedDraftKind!;
281
+ let provider: import("../spec/source").DraftProvider;
282
+ let numDraftTokens = Math.max(1, opts.numDraftTokens ?? 3);
283
+ if (kind === "dspark") {
284
+ const { DflashProvider } = await import("../spec/dflash-source");
285
+ const p = await DflashProvider.load(dir);
286
+ provider = p;
287
+ // Pin to the trained block width — the serve loop must never ask for
288
+ // more positions than the DSpark block was trained for (n ≤ cfg.gamma).
289
+ numDraftTokens = Math.max(1, Math.min(opts.numDraftTokens ?? p.gamma, p.gamma));
290
+ } else if (kind === "deepspec") {
291
+ const { DeepspecProvider } = await import("../spec/deepspec-source");
292
+ const p = await DeepspecProvider.load(dir);
293
+ provider = p;
294
+ // Same pin, from their config's block_size (e.g. 7 for the released
295
+ // dspark_gemma4_12b_block7).
296
+ numDraftTokens = Math.max(1, Math.min(opts.numDraftTokens ?? p.gamma, p.gamma));
297
+ } else if (kind === "assistant") {
298
+ const { AssistantProvider } = await import("../spec/assistant-source");
299
+ provider = await AssistantProvider.load(dir);
300
+ } else if (kind === "mtp") {
301
+ const { QwenMtpProvider } = await import("../spec/qwen-mtp-source");
302
+ const p = await QwenMtpProvider.load(dir);
303
+ provider = p;
304
+ // Default the round width to the head's trained block (block_size 3 →
305
+ // 2 recursive drafts + the pending row per round; the head was trained
306
+ // multi-step, so an explicit larger --num-draft-tokens is allowed but
307
+ // acceptance decides whether it pays).
308
+ const block = (await Bun.file(`${dir}/config.json`).json() as { block_size?: number }).block_size;
309
+ if (opts.numDraftTokens === undefined && typeof block === "number")
310
+ numDraftTokens = Math.max(1, block - 1);
311
+ } else {
312
+ const { TwoModelProvider } = await import("../spec/two-model");
313
+ provider = await TwoModelProvider.load(dir, config.text.vocabSize);
314
+ // Tokenizer-family hard check — two-model ONLY (it ships its own
315
+ // tokenizer). Exact-token-match acceptance is meaningful only when both
316
+ // models tokenize identically; a probe that ENCODES differently means
317
+ // different families — refuse instead of silently accepting ~0% of
318
+ // drafts. The KV-borrowing drafters share the target's tokenization by
319
+ // construction, so this check does not apply to them.
320
+ const draftTok = await loadTokenizer(dir);
321
+ const probe = "The 3 quick brown foxes jumped över the lazy dog?! 🦊";
322
+ if (JSON.stringify(tokenizer.encode(probe)) !== JSON.stringify(draftTok.encode(probe))) {
323
+ provider.dispose();
324
+ throw new Error(
325
+ `--draft-model tokenizer differs from the target's (probe string encodes ` +
326
+ `differently) — speculation needs the same tokenizer family`,
327
+ );
328
+ }
329
+ }
330
+ // Fail-fast pairing validation (2026-07-07 review): the KV-borrowing
331
+ // sources validate the (target, drafter) pairing in open() — non-Gemma4
332
+ // target, DeepSpec target-layer-count mismatch — which used to surface
333
+ // as a 500 from inside specServeRun on EVERY text request. Probe-open
334
+ // once with throwaway caches here so a mismatch refuses at load; open()
335
+ // allocates no per-request tensors before prefill/draft, so this is
336
+ // free. The probe sampler is never called during open().
337
+ {
338
+ const probeCaches = model.makeCache();
339
+ try {
340
+ provider
341
+ .open({
342
+ sampler: () => { throw new Error("probe sampler never samples"); },
343
+ target: bindLegacyDraftTarget(model, probeCaches),
344
+ })
345
+ .dispose();
346
+ } catch (err) {
347
+ provider.dispose();
348
+ throw new Error(
349
+ `--draft-model is incompatible with this target: ${err instanceof Error ? err.message : String(err)}`,
350
+ );
351
+ } finally {
352
+ for (const c of probeCaches) c.dispose();
353
+ }
354
+ }
355
+ if (opts.memoryBudgetBytes) {
356
+ const targetBytes = weights
357
+ ? [...weights.shards.files.values()].reduce((a, f) => a + f.mmap.size, 0)
358
+ : model.weightsBytes;
359
+ // Draft weights shrink the target's envelope. Draft KV is not modeled
360
+ // (small relative to its weights at serve contexts); admission stays
361
+ // approximately conservative via the combined-weights term.
362
+ const report = fit(config, targetBytes + provider.weightsBytes, 1, undefined, undefined, 0, opts.memoryBudgetBytes);
363
+ if (report.maxSafeContext < 1) {
364
+ provider.dispose();
365
+ throw new Error(
366
+ `target + draft do not fit the memory budget (draft adds ` +
367
+ `${(provider.weightsBytes / 1e9).toFixed(2)} GB)`,
368
+ );
369
+ }
370
+ }
371
+ draft = { provider, numDraftTokens };
372
+ } else if (opts.draftKind) {
373
+ // Every other kind names an artifact to load — refuse instead of silently
374
+ // serving without speculation.
375
+ throw new Error(`--draft-kind ${opts.draftKind} requires --draft-model`);
376
+ }
377
+
378
+ // GLM's checkpoint-native MTP row is the production default. It uses the
379
+ // already-planned bounded auxiliary expert tier and the same tokenizer, so
380
+ // there is no second artifact or compatibility probe to load.
381
+ if (!draft && model instanceof Glm52Model && glmMemoryPlan?.enableMtp) {
382
+ draft = {
383
+ provider: new Glm52NativeMtpProvider(model),
384
+ numDraftTokens: glmMemoryPlan.mtpDraftTokens,
385
+ };
386
+ }
387
+
388
+ return {
389
+ draft,
390
+ model,
391
+ profile,
392
+ glmMemoryPlan,
393
+ adapters: new AdapterManager(model),
394
+ kvConfig: config.kvQuant,
395
+ genDefaults: await loadGenSamplingDefaults(modelDir),
396
+ tokenizer,
397
+ template: await ChatTemplate.load(modelDir),
398
+ modelId: modelId ?? modelDir.split("/").filter(Boolean).at(-1)!,
399
+ // Vision is loaded lazily (getVisionTower) — text-only sessions never
400
+ // pay for the tower. The loader picks the encoder-free gemma4_unified
401
+ // (12B) tower vs the SigLIP encoder (e2b/e4b/26B/31B) by the sidecar's
402
+ // vision_config.model_type. Vision sidecars are a Gemma4 feature;
403
+ // MiniCPM5 never ships one.
404
+ vision: null,
405
+ loadVision: makeVisionLoader(modelDir, model, config),
406
+ visionTokenIds: {
407
+ imageTokenId: (config.raw.image_token_id as number) ?? 258880,
408
+ boiTokenId: (config.raw.boi_token_id as number) ?? 255999,
409
+ eoiTokenId: (config.raw.eoi_token_id as number) ?? 258882,
410
+ },
411
+ // Audio mirrors vision: lazy tower from the same sidecar, loaded on the
412
+ // first audio request only (docs/design/generic-model-support.md A4).
413
+ audio: null,
414
+ loadAudio: makeAudioLoader(modelDir, model, config),
415
+ audioTokenIds: config.raw.audio_config
416
+ ? {
417
+ audioTokenId: (config.raw.audio_token_id as number) ?? 258881,
418
+ boaTokenId: (config.raw.boa_token_id as number) ?? 256000,
419
+ eoaTokenId: (config.raw.eoa_token_id as number) ?? 258883,
420
+ }
421
+ : null,
422
+ };
423
+ }
424
+
425
+ /** Build the on-demand vision-tower loader, selecting the encoder-free
426
+ * (gemma4_unified, 12B) tower vs the SigLIP encoder (gemma4_vision:
427
+ * e2b/e4b/26B/31B) by the sidecar's vision_config.model_type. Returns null
428
+ * when the model has no usable vision sidecar. */
429
+ export function makeVisionLoader(
430
+ modelDir: string, model: RuntimeModel, config: ModelConfig,
431
+ ): (() => VisionEncoder) | null {
432
+ // Qwen3.5/3.8: the tower ships as optiq/optiq_vision.safetensors (the
433
+ // artifact's bf16 sidecar). The returned tower is a Qwen3VLVisionTower —
434
+ // it rides the same lazy slot/capability flags; the qwen chat branch is
435
+ // the only consumer and casts it back (the gemma branches are gated on
436
+ // `instanceof Gemma4Model`, so the union never crosses).
437
+ if (model instanceof Qwen35Model) {
438
+ // Vision weights arrive either as the OptiQ-convention sidecar OR in-main
439
+ // (mlx-vlm convention; our artifacts ship one copy in-main since
440
+ // 2026-08-18 — the tower loader handles both).
441
+ const hasSidecar = existsSync(`${modelDir}/optiq/optiq_vision.safetensors`);
442
+ const hasInMain = config.raw.vision_config !== undefined;
443
+ if (!hasSidecar && !hasInMain) return null;
444
+ return () =>
445
+ Qwen3VLVisionTower.load(modelDir) as unknown as VisionEncoder;
446
+ }
447
+ if (!(config.hasVisionSidecar && model instanceof Gemma4Model)) return null;
448
+ const vc = config.raw.vision_config as Record<string, any> | undefined;
449
+ if (vc?.model_type === "gemma4_vision") {
450
+ const sigCfg = parseSiglipConfig(vc);
451
+ return () => SiglipVisionTower.load(modelDir, sigCfg, model.embedScale);
452
+ }
453
+ // gemma4_unified_vision (or unlabelled): the encoder-free patch embedder.
454
+ return () => VisionTower.load(modelDir, model.embedScale, config.text.rmsNormEps);
455
+ }
456
+
457
+ /** Lazily load + cache the vision tower on first use. A sidecar that fails
458
+ * to load is a capability gap, not a fatal error: returns null and the
459
+ * request is answered with a 400 (the loader is cleared so we don't retry
460
+ * a known-bad load every request). */
461
+ export function getVisionTower(ctx: ServerContext): VisionEncoder | null {
462
+ if (ctx.vision) return ctx.vision;
463
+ if (!ctx.loadVision) return null;
464
+ try {
465
+ ctx.vision = ctx.loadVision();
466
+ return ctx.vision;
467
+ } catch (e) {
468
+ console.warn(`vision sidecar not loadable (${(e as Error).message}) — serving text-only`);
469
+ ctx.loadVision = null;
470
+ return null;
471
+ }
472
+ }
473
+
474
+ /** Build the on-demand audio-tower loader (gemma-4 Conformer, A4 of
475
+ * docs/design/generic-model-support.md). Auto-enables — no flags — when
476
+ * config.json carries an `audio_config` AND the optiq_vision.safetensors
477
+ * sidecar exists (the audio tensors ship in the same sidecar as vision).
478
+ * Returns null when the model can't do audio (no audio_config: 26B-A4B,
479
+ * DiffusionGemma, bf16 assistants — architectural, not a porting gap). */
480
+ export function makeAudioLoader(
481
+ modelDir: string, model: RuntimeModel, config: ModelConfig,
482
+ ): (() => AudioTower) | null {
483
+ if (!(config.hasVisionSidecar && config.raw.audio_config && model instanceof Gemma4Model))
484
+ return null;
485
+ // The sidecar header must actually name the Conformer tensors: the local
486
+ // 12B snapshot pairs audio_config with a STUB sidecar (embed_audio only),
487
+ // and a non-null loader here is what advertises `audio: true` on every
488
+ // capability surface (ws handshake, /v1/models). Header-only read.
489
+ if (!sidecarShipsAudioTower(`${modelDir}/optiq_vision.safetensors`)) return null;
490
+ const audioCfg = parseAudioConfig(config.raw.audio_config as Record<string, any>);
491
+ return () => AudioTower.load(modelDir, audioCfg, model.embedScale);
492
+ }
493
+
494
+ /** Lazily load + cache the audio tower on first use. Unlike vision's
495
+ * warn-and-continue (text-only degrade is correct for requests WITHOUT
496
+ * images), this is only ever consulted for requests WITH audio — the
497
+ * caller turns null into an explicit 400, never a silent text-only
498
+ * degrade. A failed load is not retried every request. (The stub-sidecar
499
+ * case — the local 12B state — never gets here: makeAudioLoader checks the
500
+ * sidecar header and returns a null loader.) */
501
+ export function getAudioTower(ctx: ServerContext): AudioTower | null {
502
+ if (ctx.audio) return ctx.audio;
503
+ if (!ctx.loadAudio) return null;
504
+ try {
505
+ ctx.audio = ctx.loadAudio();
506
+ return ctx.audio;
507
+ } catch (e) {
508
+ console.warn(`audio sidecar not loadable (${(e as Error).message})`);
509
+ ctx.loadAudio = null;
510
+ return null;
511
+ }
512
+ }
@@ -0,0 +1,103 @@
1
+ // OpenAI wire formats: InferenceResult → chat.completion / text_completion
2
+ // JSON, and the SSE chunk protocols for both. Anthropic and Responses have
3
+ // their own (src/anthropic.ts, src/responses.ts); all three implement the
4
+ // same CompletionStreamProtocol so the HTTP writer (http.ts) is shared.
5
+ import type { CompletionSummary, CompletionUsage } from "./completion-executor";
6
+ import type { CompletionEvent, CompletionStreamProtocol } from "./completion-sink";
7
+ import type { InferenceResult } from "./inference-request";
8
+
9
+ export interface OpenAiResponseMeta {
10
+ id: string;
11
+ created: number;
12
+ model: string;
13
+ }
14
+
15
+ /** OpenAI usage block from the executor's live/terminal usage view. */
16
+ export const openAiUsage = (usage: CompletionUsage) => ({
17
+ prompt_tokens: usage.promptTokens,
18
+ completion_tokens: usage.completionTokens,
19
+ total_tokens: usage.totalTokens,
20
+ prompt_tokens_details: { cached_tokens: usage.cachedTokens },
21
+ ...(usage.speculation ? { speculation: usage.speculation } : {}),
22
+ ...(usage.fill ? { fill: usage.fill } : {}),
23
+ });
24
+
25
+ /** Terminal usage: the wire block plus mlx-bun's `lane` (batch|serial|…). */
26
+ export const openAiSummaryUsage = (summary: CompletionSummary) => ({
27
+ ...openAiUsage(summary.usage),
28
+ lane: summary.lane,
29
+ });
30
+
31
+ export function chatCompletionJson(result: InferenceResult, meta: OpenAiResponseMeta) {
32
+ return {
33
+ ...meta, object: "chat.completion",
34
+ choices: [{
35
+ index: 0,
36
+ message: {
37
+ role: "assistant",
38
+ content: result.content || (result.toolCalls.length ? null : ""),
39
+ ...(result.reasoning ? { reasoning: result.reasoning } : {}),
40
+ ...(result.toolCalls.length ? { tool_calls: result.toolCalls } : {}),
41
+ },
42
+ ...(result.logprobs ? { logprobs: result.logprobs } : {}),
43
+ finish_reason: result.finishReason,
44
+ }],
45
+ usage: openAiSummaryUsage(result),
46
+ };
47
+ }
48
+
49
+ export function textCompletionJson(result: InferenceResult, meta: OpenAiResponseMeta) {
50
+ return {
51
+ ...meta, object: "text_completion",
52
+ choices: [{
53
+ index: 0, text: result.content,
54
+ ...(result.logprobs ? { logprobs: result.logprobs } : {}),
55
+ finish_reason: result.finishReason,
56
+ }],
57
+ usage: openAiSummaryUsage(result),
58
+ };
59
+ }
60
+
61
+ const sse = (obj: unknown) => `data: ${JSON.stringify(obj)}\n\n`;
62
+ const DONE = "data: [DONE]\n\n";
63
+
64
+ /** OpenAI chat SSE: a role primer chunk, one chunk per event (content /
65
+ * reasoning / tool_calls delta), a terminal chunk carrying finish_reason +
66
+ * usage, then the bare `[DONE]` sentinel strict SDK clients require. An
67
+ * error mid-stream is a single `{error}` frame and nothing after it. */
68
+ export function chatCompletionStream(meta: OpenAiResponseMeta): CompletionStreamProtocol {
69
+ const chunk = (delta: Record<string, unknown>, finish: string | null) => ({
70
+ ...meta, object: "chat.completion.chunk",
71
+ choices: [{ index: 0, delta, finish_reason: finish }],
72
+ });
73
+ let errored = false;
74
+ return {
75
+ start: () => [sse(chunk({ role: "assistant", content: "" }, null))],
76
+ addEvents: (events: CompletionEvent[]) => events.map((event) =>
77
+ event.type === "reasoning" ? sse(chunk({ reasoning: event.text }, null))
78
+ : event.type === "content" ? sse(chunk({ content: event.text }, null))
79
+ : sse(chunk({ tool_calls: event.calls.map((call, index) => ({ index, ...call })) }, null))),
80
+ finish: (reason, usage) => errored ? [] : [sse({ ...chunk({}, reason), usage }), DONE],
81
+ error: (message) => { errored = true; return [sse({ error: { message } })]; },
82
+ };
83
+ }
84
+
85
+ /** OpenAI text-completion SSE: content deltas as `text`, then a final chunk
86
+ * with finish_reason + usage (mlx-lm gates usage behind
87
+ * stream_options.include_usage; we always attach it — an additive superset
88
+ * OpenAI clients ignore), then `[DONE]`. */
89
+ export function textCompletionStream(meta: OpenAiResponseMeta): CompletionStreamProtocol {
90
+ const chunk = (text: string, finish: string | null) => ({
91
+ ...meta, object: "text_completion",
92
+ choices: [{ index: 0, text, finish_reason: finish }],
93
+ });
94
+ let errored = false;
95
+ return {
96
+ start: () => [],
97
+ addEvents: (events: CompletionEvent[]) => events
98
+ .filter((event) => event.type === "content")
99
+ .map((event) => sse(chunk((event as { text: string }).text, null))),
100
+ finish: (reason, usage) => errored ? [] : [sse({ ...chunk("", reason), usage }), DONE],
101
+ error: (message) => { errored = true; return [sse({ error: { message } })]; },
102
+ };
103
+ }
@@ -0,0 +1,56 @@
1
+ import { handleStaticRoute } from "./static-routes";
2
+ import { STATIC_ROUTE_ASSETS } from "../web-assets";
3
+ import { createResponsesClient } from "./responses-client";
4
+ import type { DisposableResource } from "../contracts/resources";
5
+ import type { JobStore } from "../jobs/db";
6
+ import { handleLabRoute, matchLabRoute } from "./lab-routes";
7
+ import { handleAdminRoute, matchAdminRoute } from "./admin-routes";
8
+
9
+ /** CPU application state stays in the parent when model workers restart/evict.
10
+ * Native inspection/merge/export routes still execute inside a model worker. */
11
+ export function createParentApplication(options: {
12
+ acquireGpu(signal: AbortSignal): Promise<DisposableResource>;
13
+ serverPort(): number | undefined;
14
+ invalidateLibrary(): void;
15
+ createJobStore?(): Promise<JobStore>;
16
+ }) {
17
+ const responses = createResponsesClient();
18
+ let jobs: Promise<JobStore> | undefined;
19
+ let closed = false;
20
+ const ensureJobs = () => {
21
+ if (closed) return Promise.reject(new Error("application host is closed"));
22
+ return jobs ??= (async () => {
23
+ const { JobStore, registerRunner } = await import("../jobs");
24
+ const store = options.createJobStore ? await options.createJobStore() : new JobStore();
25
+ store.markZombies();
26
+ const { datasetRunner } = await import("../dataset/job");
27
+ registerRunner("dataset", datasetRunner);
28
+ return store;
29
+ })();
30
+ };
31
+ return {
32
+ get responseStats() { return responses.stats; },
33
+ async handle(request: Request, forward?: (request: Request) => Promise<Response>): Promise<Response | null> {
34
+ const url = new URL(request.url);
35
+ const staticResponse = handleStaticRoute(url, request, STATIC_ROUTE_ASSETS);
36
+ if (staticResponse) return staticResponse;
37
+ if (forward && request.method === "POST" && url.pathname === "/v1/responses")
38
+ return responses.forward(request, forward);
39
+ const admin = matchAdminRoute(request.method, url.pathname);
40
+ if (admin) return handleAdminRoute(url, request, { ensureJobs, invalidateLibrary: options.invalidateLibrary });
41
+ const route = matchLabRoute(request.method, url.pathname);
42
+ if (route !== "quantize-submit" && route !== "finetune-submit" &&
43
+ route !== "dataset-submit" && route !== "dataset-templates") return null;
44
+ return handleLabRoute(url, request, { ensureJobs, acquireGpu: options.acquireGpu,
45
+ serverPort: options.serverPort, invalidateLibrary: options.invalidateLibrary });
46
+ },
47
+ async close() {
48
+ closed = true;
49
+ if (!jobs) return;
50
+ const store = await jobs;
51
+ const { closeSubprocessJobs, closeInProcessJobs } = await import("../jobs");
52
+ await Promise.all([closeSubprocessJobs(store), closeInProcessJobs(store)]);
53
+ store.close();
54
+ },
55
+ };
56
+ }