mlx-bun 0.2.0 → 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 (364) hide show
  1. package/README.md +71 -588
  2. package/docs/README.md +91 -0
  3. package/docs/{design → archive/investigations}/audio-input-plan.md +4 -4
  4. package/docs/{design → archive/investigations}/diffusion-gemma-port.md +3 -3
  5. package/docs/{design → archive/investigations}/faithful-l1-consolidation.md +4 -4
  6. package/docs/{design → archive/investigations}/minicpm5-decode-megakernel.md +11 -11
  7. package/docs/{design → archive/investigations}/optimization_plan.md +1 -1
  8. package/docs/{design → archive/investigations}/pre-colibri-stabilization.md +5 -5
  9. package/docs/{design → archive/investigations}/the-dreaming-handoff.md +2 -2
  10. package/docs/design/batching.md +569 -0
  11. package/docs/design/decode-speed-program.md +3178 -169
  12. package/docs/design/dreaming-nightly-pipeline.md +675 -282
  13. package/docs/design/generic-model-support.md +579 -334
  14. package/docs/design/kv-cache.md +680 -0
  15. package/docs/design/orpo-training.md +673 -1239
  16. package/docs/design/speculative-decoding.md +1627 -0
  17. package/docs/design/turboquant.md +2102 -0
  18. package/docs/design/unified-engine-frontier-plan.md +1831 -727
  19. package/docs/design/web-chat-redesign.md +666 -1083
  20. package/docs/planning/PRODUCT_ROADMAP.md +34 -1
  21. package/docs/planning/release-notes-v0.3.0.md +35 -0
  22. package/docs/planning/video-series.md +2 -2
  23. package/docs/reference/benchmarks.md +1162 -0
  24. package/docs/reference/cli.md +394 -159
  25. package/docs/reference/distribution.md +321 -182
  26. package/docs/reference/environment.md +348 -0
  27. package/docs/reference/glossary.md +39 -0
  28. package/docs/reference/library-api.md +566 -168
  29. package/docs/reference/memory.md +227 -64
  30. package/docs/reference/models.md +104 -6
  31. package/docs/reference/server-api.md +886 -425
  32. package/docs/reference/server-config.md +638 -330
  33. package/docs/reference/training.md +393 -254
  34. package/docs/reference/troubleshooting.md +166 -0
  35. package/package.json +9 -4
  36. package/src/audio/decode.ts +2 -2
  37. package/src/audio/features.ts +2 -2
  38. package/src/backends/mlx/autoregressive.ts +108 -0
  39. package/src/backends/mlx/batch-group.ts +1646 -0
  40. package/src/backends/mlx/diffusion.ts +39 -0
  41. package/src/backends/mlx/draft-target.ts +47 -0
  42. package/src/backends/mlx/evaluation.ts +105 -0
  43. package/src/backends/mlx/fill-append.ts +45 -0
  44. package/src/backends/mlx/gateway-binding.ts +71 -0
  45. package/src/backends/mlx/graph.ts +38 -0
  46. package/src/backends/mlx/memory-client.ts +189 -0
  47. package/src/backends/mlx/memory-guard.ts +40 -0
  48. package/src/backends/mlx/methods.ts +90 -0
  49. package/src/backends/mlx/model-prompt.ts +164 -0
  50. package/src/backends/mlx/model-serving.ts +79 -0
  51. package/src/backends/mlx/prefill.ts +33 -0
  52. package/src/backends/mlx/request-policy.ts +20 -0
  53. package/src/backends/mlx/rollback.ts +51 -0
  54. package/src/backends/mlx/serial-executor.ts +273 -0
  55. package/src/backends/mlx/speculative.ts +114 -0
  56. package/src/backends/mlx/state-views.ts +26 -0
  57. package/src/backends/mlx/text-engine.ts +73 -0
  58. package/src/cli.ts +58 -25
  59. package/src/client.ts +66 -0
  60. package/src/config.ts +21 -4
  61. package/src/contracts/completion.ts +16 -0
  62. package/src/contracts/execution.ts +49 -0
  63. package/src/contracts/generation.ts +103 -0
  64. package/src/contracts/host.ts +7 -0
  65. package/src/contracts/jobs.ts +66 -0
  66. package/src/contracts/pi-provider.ts +30 -0
  67. package/src/contracts/pi.ts +259 -0
  68. package/src/contracts/resources.ts +18 -0
  69. package/src/contracts/scheduling.ts +27 -0
  70. package/src/contracts/tsconfig.json +14 -0
  71. package/src/diffusion/diffusion-generate.ts +218 -153
  72. package/src/embed.ts +1 -1
  73. package/src/engine/admission.ts +59 -0
  74. package/src/engine/cancellation.ts +38 -0
  75. package/src/engine/engine.ts +56 -0
  76. package/src/engine/execution-coordinator.ts +70 -0
  77. package/src/engine/execution-plan.ts +51 -0
  78. package/src/engine/resources.ts +42 -0
  79. package/src/engine/scheduler.ts +67 -0
  80. package/src/engine/session.ts +247 -0
  81. package/src/eval/README.md +44 -1
  82. package/src/eval/kl.ts +236 -3
  83. package/src/eval/reference-logits.ts +207 -0
  84. package/src/eval/runner.ts +8 -96
  85. package/src/fill/echo-index.ts +188 -0
  86. package/src/fill/fill-session.ts +452 -0
  87. package/src/fill/proposal.ts +68 -0
  88. package/src/fill/schema-rows.ts +506 -0
  89. package/src/fill/tool-boundary.ts +103 -0
  90. package/src/fit.ts +1 -1
  91. package/src/generate.ts +656 -268
  92. package/src/grammar.ts +12 -7
  93. package/src/harness-pi.ts +14 -33
  94. package/src/hub-rest.ts +4 -4
  95. package/src/index.ts +7 -0
  96. package/src/inference/denoising.ts +17 -0
  97. package/src/inference/graph.ts +33 -0
  98. package/src/inference/prefill.ts +39 -0
  99. package/src/inference/rollback.ts +7 -0
  100. package/src/jobs/db.ts +4 -0
  101. package/src/jobs/index.ts +2 -0
  102. package/src/jobs/job-entry.ts +12 -12
  103. package/src/jobs/runner.ts +98 -13
  104. package/src/jobs/task-client.ts +19 -0
  105. package/src/jobs/types.ts +2 -58
  106. package/src/kv-store.ts +109 -49
  107. package/src/lab/README.md +18 -0
  108. package/src/{assets → lab/curve}/curve-designer.html +2 -2
  109. package/src/{curve-sampler.ts → lab/curve/curve-sampler.ts} +2 -2
  110. package/src/{expert-trace.ts → lab/expert-trace/expert-trace.ts} +5 -5
  111. package/src/{model → lab/paged-kv}/paged-kv.ts +9 -6
  112. package/src/library.ts +40 -0
  113. package/src/lora.ts +18 -0
  114. package/src/media-fetch.ts +1 -1
  115. package/src/memory/article.ts +1 -1
  116. package/src/memory/chunk.ts +1 -1
  117. package/src/memory/model.ts +30 -169
  118. package/src/memory/prompts.ts +1 -1
  119. package/src/memory/rest.ts +1 -1
  120. package/src/memory/schedule.ts +1 -1
  121. package/src/memory/stages.ts +4 -1
  122. package/src/memory/vault.ts +1 -3
  123. package/src/mlx/array.ts +9 -10
  124. package/src/mlx/compile.ts +12 -2
  125. package/src/mlx/ffi.ts +58 -11
  126. package/src/mlx/materialize.ts +23 -0
  127. package/src/mlx/metal-kernel.ts +10 -11
  128. package/src/mlx/ops.ts +33 -13
  129. package/src/mlx/quantized-rows.ts +36 -0
  130. package/src/mlx/token-bitmask.ts +52 -0
  131. package/src/mlx/turboquant-kv-decode.ts +82 -0
  132. package/src/mlx/turboquant-kv-inverse.ts +122 -0
  133. package/src/mlx/turboquant-ops.ts +33 -3
  134. package/src/mlx/turboquant-tables.ts +2 -2
  135. package/src/model/batched-mask.ts +8 -2
  136. package/src/model/batched-quant.ts +1 -1
  137. package/src/model/batched-rotating-quant.ts +2 -2
  138. package/src/model/batched-rotating.ts +1 -1
  139. package/src/model/compiled-decode.ts +1 -1
  140. package/src/model/diffusion-gemma.ts +8 -8
  141. package/src/model/factory.ts +76 -33
  142. package/src/model/fingerprint.ts +1 -1
  143. package/src/model/flash-attention.ts +3 -3
  144. package/src/model/gemma4-base.ts +26 -9
  145. package/src/model/gemma4.ts +6 -6
  146. package/src/model/generated/gemma4-12b.ts +2 -2
  147. package/src/model/generated/gemma4-26b.ts +2 -2
  148. package/src/model/generated/gemma4-e4b.ts +2 -2
  149. package/src/model/glm52-dsa.ts +13 -9
  150. package/src/model/glm52-memory.ts +1 -1
  151. package/src/model/implementation.ts +69 -0
  152. package/src/model/minicpm5.ts +6 -8
  153. package/src/model/profile.ts +12 -2
  154. package/src/model/qwen-append.ts +12 -0
  155. package/src/model/qwen-conv.ts +52 -0
  156. package/src/model/qwen3_5-checkpoint.ts +164 -0
  157. package/src/model/qwen3_5.ts +140 -56
  158. package/src/model/support.ts +1 -1
  159. package/src/model/trellis-balanced-scatter.ts +51 -0
  160. package/src/model/trellis-linear.ts +672 -0
  161. package/src/model/trellis-shared-m.ts +151 -0
  162. package/src/model/trellis-shared-scatter.ts +144 -0
  163. package/src/model/trellis-splitk-prefill.ts +158 -0
  164. package/src/model/trellis-tiled-prefill.ts +136 -0
  165. package/src/model/trellis-vector-expand.ts +62 -0
  166. package/src/model/trellis-wide-prefill.ts +94 -0
  167. package/src/model/universal/dense.ts +1 -1
  168. package/src/model/universal/modules.ts +8 -1
  169. package/src/native-pack.ts +6 -5
  170. package/src/pi-provider.ts +6 -64
  171. package/src/pi-web.ts +8 -315
  172. package/src/prompt-cache.ts +96 -53
  173. package/src/quantize/allocator.ts +1 -1
  174. package/src/quantize/config-writer.ts +10 -3
  175. package/src/quantize/rotate.ts +4 -4
  176. package/src/quantize/trellis.ts +586 -0
  177. package/src/responses.ts +28 -1
  178. package/src/runtime-config.ts +18 -4
  179. package/src/sampler.ts +4 -4
  180. package/src/serve/batch-scheduler.ts +8 -1671
  181. package/src/serve/chat-request.ts +391 -0
  182. package/src/serve/chat-stage.ts +195 -0
  183. package/src/serve/checkpoint-identity.ts +64 -0
  184. package/src/serve/completion-executor.ts +15 -7
  185. package/src/serve/discovery-routes.ts +12 -13
  186. package/src/serve/generation-gateway.ts +154 -193
  187. package/src/serve/http.ts +159 -0
  188. package/src/serve/inference-request.ts +79 -0
  189. package/src/serve/isolate.ts +297 -105
  190. package/src/serve/lab-routes.ts +3 -0
  191. package/src/serve/lane-registry.ts +2 -1
  192. package/src/serve/model-admin-routes.ts +7 -5
  193. package/src/serve/model-binding.ts +43 -0
  194. package/src/serve/model-host.ts +512 -0
  195. package/src/serve/openai-wire.ts +103 -0
  196. package/src/serve/parent-application.ts +56 -0
  197. package/src/serve/pipeline.ts +33 -0
  198. package/src/serve/preparation.ts +33 -0
  199. package/src/serve/request-plan.ts +19 -15
  200. package/src/serve/request-prep.ts +346 -0
  201. package/src/serve/response-lease.ts +24 -0
  202. package/src/serve/responses-client.ts +69 -0
  203. package/src/serve/session-completion-engine.ts +110 -0
  204. package/src/serve/session-search.ts +1 -1
  205. package/src/serve/static-routes.ts +5 -5
  206. package/src/serve/text-completion-stage.ts +104 -0
  207. package/src/serve/token-streams.ts +519 -0
  208. package/src/server.ts +317 -2649
  209. package/src/spec/assistant-source.ts +10 -44
  210. package/src/spec/deepspec-source.ts +6 -6
  211. package/src/spec/dflash-source.ts +8 -8
  212. package/src/spec/dspark/ab-stats.ts +3 -3
  213. package/src/spec/dspark/calibration.ts +2 -2
  214. package/src/spec/dspark/deepspec-module.ts +2 -2
  215. package/src/spec/dspark/generate-dflash.ts +2 -2
  216. package/src/spec/dspark/generate.ts +2 -2
  217. package/src/spec/dspark/loader.ts +1 -1
  218. package/src/spec/dspark/module-dflash.ts +4 -3
  219. package/src/spec/dspark/module.ts +3 -3
  220. package/src/spec/dspark/quantize-drafter.ts +1 -1
  221. package/src/spec/generate.ts +1 -1
  222. package/src/spec/glm52-mtp-source.ts +1 -1
  223. package/src/spec/ngram-source.ts +1 -1
  224. package/src/spec/prefix-state.ts +45 -0
  225. package/src/spec/qwen-mtp-source.ts +166 -69
  226. package/src/spec/serve-loop.ts +154 -156
  227. package/src/spec/source.ts +42 -10
  228. package/src/spec/two-model.ts +1 -1
  229. package/src/ssd-cache.ts +80 -12
  230. package/src/ssd-durability.ts +25 -13
  231. package/src/tool-call.ts +51 -14
  232. package/src/train/flash-cce.ts +2 -2
  233. package/src/train/forward.ts +6 -0
  234. package/src/train/loss.ts +1 -1
  235. package/src/train/prefix-shared.ts +5 -1
  236. package/src/train/segmented.ts +5 -3
  237. package/src/train/trainer.ts +6 -6
  238. package/src/vision/prompt.ts +1 -1
  239. package/src/vision/qwen3vl-tower.ts +52 -10
  240. package/src/web/app.html +1 -1
  241. package/src/web/app.js +5 -3
  242. package/src/web/src/adapters-panel.ts +3 -3
  243. package/src/web/src/assistant.ts +2 -36
  244. package/src/web/src/chat.ts +4 -4
  245. package/src/web/src/composer.ts +4 -4
  246. package/src/web/src/hub.ts +1 -1
  247. package/src/web/src/markdown.ts +0 -0
  248. package/src/web/src/memory-panel.ts +1 -1
  249. package/src/web/src/model-picker.ts +1 -1
  250. package/src/web/src/palette.ts +1 -1
  251. package/src/web/src/protocol.ts +3 -39
  252. package/src/web/src/sessions.ts +1 -1
  253. package/src/web/src/ui-catalog.ts +4 -18
  254. package/src/web-assets.ts +47 -0
  255. package/src/weights.ts +55 -9
  256. package/docs/archive/investigations/curve-runs/bisector-route.json +0 -98
  257. package/docs/archive/investigations/curve-runs/bisector-trace.json +0 -1393
  258. package/docs/archive/investigations/curve-runs/curve-terrain.json +0 -1179
  259. package/docs/archive/investigations/curve-runs/curve-terrain.svg +0 -42
  260. package/docs/archive/investigations/hlg-ab.html +0 -34
  261. package/docs/archive/investigations/hlg-explorer.html +0 -238
  262. package/docs/archive/investigations/hlg-figs/cliff.svg +0 -1
  263. package/docs/archive/investigations/hlg-figs/cross.svg +0 -1
  264. package/docs/archive/investigations/hlg-figs/edges.svg +0 -1
  265. package/docs/archive/investigations/hlg-figs/k20-grids.svg +0 -1
  266. package/docs/archive/investigations/hlg-figs/k20-peaks.svg +0 -1
  267. package/docs/archive/investigations/hlg-figs/lw-curve.svg +0 -1
  268. package/docs/archive/investigations/hlg-figs/terrain.svg +0 -1
  269. package/docs/archive/investigations/hlg-report.html +0 -262
  270. package/docs/archive/investigations/hlg-runs/hlg-ab.json +0 -149
  271. package/docs/archive/investigations/hlg-runs/hlg-blind-prompts.md +0 -87
  272. package/docs/archive/investigations/hlg-runs/hlg-blind.json +0 -107
  273. package/docs/archive/investigations/hlg-runs/hlg-cliff.json +0 -197
  274. package/docs/archive/investigations/hlg-runs/hlg-cross.json +0 -505
  275. package/docs/archive/investigations/hlg-runs/hlg-edge.json +0 -388
  276. package/docs/archive/investigations/hlg-runs/hlg-eval1.json +0 -25
  277. package/docs/archive/investigations/hlg-runs/hlg-frontier.json +0 -86
  278. package/docs/archive/investigations/hlg-runs/hlg-grid.json +0 -242
  279. package/docs/archive/investigations/hlg-runs/hlg-grid2.json +0 -343
  280. package/docs/archive/investigations/hlg-runs/hlg-lw-coarse.json +0 -110
  281. package/docs/archive/investigations/hlg-runs/hlg-map.json +0 -383
  282. package/docs/archive/investigations/hlg-runs/run0-original.log +0 -159
  283. package/docs/archive/investigations/hlg-runs/runA-recommended.log +0 -131
  284. package/docs/archive/investigations/hlg-runs/runAA-cliff-cpm5.log +0 -26
  285. package/docs/archive/investigations/hlg-runs/runAB-grid2-e4b.log +0 -18
  286. package/docs/archive/investigations/hlg-runs/runAC-peak-e4b-partial.log +0 -25
  287. package/docs/archive/investigations/hlg-runs/runAD-ab-samples.log +0 -8
  288. package/docs/archive/investigations/hlg-runs/runAE-edge-e4b.log +0 -51
  289. package/docs/archive/investigations/hlg-runs/runAF-logit-calibration.log +0 -10
  290. package/docs/archive/investigations/hlg-runs/runAG-eval-config2.log +0 -16
  291. package/docs/archive/investigations/hlg-runs/runB-gain-variants.log +0 -192
  292. package/docs/archive/investigations/hlg-runs/runC-pivots.log +0 -162
  293. package/docs/archive/investigations/hlg-runs/runD-oetf.log +0 -132
  294. package/docs/archive/investigations/hlg-runs/runE-eotf.log +0 -162
  295. package/docs/archive/investigations/hlg-runs/runF-shaper-working.log +0 -86
  296. package/docs/archive/investigations/hlg-runs/runG-shaper-sweep.log +0 -101
  297. package/docs/archive/investigations/hlg-runs/runH-wsweep.log +0 -176
  298. package/docs/archive/investigations/hlg-runs/runI-asweep.log +0 -176
  299. package/docs/archive/investigations/hlg-runs/runJ-knobmap.log +0 -49
  300. package/docs/archive/investigations/hlg-runs/runK-frontier.log +0 -19
  301. package/docs/archive/investigations/hlg-runs/runL-widemap.log +0 -65
  302. package/docs/archive/investigations/hlg-runs/runM-frontier-emb.log +0 -15
  303. package/docs/archive/investigations/hlg-runs/runN-verify.log +0 -116
  304. package/docs/archive/investigations/hlg-runs/runO-frontier-seed5000.log +0 -15
  305. package/docs/archive/investigations/hlg-runs/runP-grid-AxSm.log +0 -15
  306. package/docs/archive/investigations/hlg-runs/runQ-grid-tgW.log +0 -15
  307. package/docs/archive/investigations/hlg-runs/runR-blind-transcript.log +0 -79
  308. package/docs/archive/investigations/hlg-runs/runS-cross-coherence.log +0 -33
  309. package/docs/archive/investigations/hlg-runs/runT-cross-cpm5.log +0 -33
  310. package/docs/archive/investigations/hlg-runs/runU-cross-12b.log +0 -33
  311. package/docs/archive/investigations/hlg-runs/runV-lw-e4b.log +0 -22
  312. package/docs/archive/investigations/hlg-runs/runW-lw-12b.log +0 -22
  313. package/docs/archive/investigations/hlg-runs/runX-lw-cpm5.log +0 -22
  314. package/docs/archive/investigations/hlg-runs/runY-cliff-e4b.log +0 -26
  315. package/docs/archive/investigations/hlg-runs/runZ-cliff-12b.log +0 -26
  316. package/docs/archive/mlx-bun-lab-report.html +0 -275
  317. package/docs/archive/wwdc-mlx-bun.html +0 -848
  318. package/docs/design/adapters-end-to-end.md +0 -205
  319. package/docs/design/batching-perf-path.md +0 -255
  320. package/docs/design/batching-v2-plan.md +0 -529
  321. package/docs/design/bucketing-stage.md +0 -197
  322. package/docs/design/compat-cli-surface-design.md +0 -230
  323. package/docs/design/docs-reorg-plan.md +0 -165
  324. package/docs/design/dspark-serving-program.md +0 -371
  325. package/docs/design/dspark-speculative-decoding.md +0 -318
  326. package/docs/design/grammar-spec-batching-integration.md +0 -301
  327. package/docs/design/memory-inference-path.md +0 -422
  328. package/docs/design/memory-synthesis.md +0 -287
  329. package/docs/design/memory-system.md +0 -237
  330. package/docs/design/mlx-lm-serving-execution-seam.md +0 -81
  331. package/docs/design/mlx-lm-tool-parity-plan.md +0 -545
  332. package/docs/design/omlx-adoption-map.md +0 -98
  333. package/docs/design/orpo-dynamic-lambda.md +0 -220
  334. package/docs/design/orpo-future-enhancements.md +0 -340
  335. package/docs/design/paged-kv-cache.md +0 -214
  336. package/docs/design/parallel-slots.md +0 -567
  337. package/docs/design/parity-tier-dag.md +0 -161
  338. package/docs/design/repo-cleanup-plan.md +0 -231
  339. package/docs/design/runtime-isolation.md +0 -263
  340. package/docs/design/segmented-backward-training.md +0 -543
  341. package/docs/design/spec-decode-larger-targets.md +0 -229
  342. package/docs/design/ssd-kv-cold-tier.md +0 -415
  343. package/docs/design/structured-output.md +0 -484
  344. package/docs/design/tauri-desktop-app.md +0 -127
  345. package/docs/design/the-dreaming-master-plan.md +0 -445
  346. package/docs/design/turboquant-kv.md +0 -235
  347. package/docs/design/turboquant-weights.md +0 -467
  348. package/docs/design/w4a16-compute-precision-spike.md +0 -232
  349. package/docs/design/web-chat-beat-matrix.md +0 -315
  350. package/docs/design/write-pipeline-entity.md +0 -468
  351. package/docs/planning/IDEAS.md +0 -69
  352. package/docs/reference/embedding.md +0 -197
  353. package/docs/reference/features-matrix.md +0 -101
  354. package/docs/reference/orpo-quickstart.md +0 -135
  355. package/src/flags.ts +0 -11
  356. /package/docs/{design → archive/investigations}/colibri-glm52-port.md +0 -0
  357. /package/docs/{planning → archive/planning}/chunk-task-roadmap.md +0 -0
  358. /package/docs/{planning → archive/planning}/curve-sampler-research-plan.md +0 -0
  359. /package/docs/{planning → archive/planning}/memory-docs-and-dag-plan.md +0 -0
  360. /package/docs/{planning → archive/planning}/pi-integration-review.md +0 -0
  361. /package/docs/{planning → archive/planning}/release-notes-v0.2.0.md +0 -0
  362. /package/src/{memory-plan.ts → admission-plan.ts} +0 -0
  363. /package/{docs/archive/investigations → src/serve/assets}/curve-terrain.html +0 -0
  364. /package/{docs/dag → src/serve/assets}/training-inference-map.html +0 -0
@@ -0,0 +1,43 @@
1
+ import type { ModelConfig } from "../config";
2
+ import type { MlxArray } from "../mlx/array";
3
+ import type { MlxGatewayBinding } from "../backends/mlx/gateway-binding";
4
+ import type { MlxSerialServices } from "../backends/mlx/serial-executor";
5
+ import type { SsdCacheStore, SsdIndexEntry } from "../ssd-cache";
6
+ import type { ChatRequestParams } from "./chat-request";
7
+ import type { SerialRun, Vision } from "./generation-gateway";
8
+ import type { RequestOwnership } from "./request-plan";
9
+ import type { RequestPrep } from "./request-prep";
10
+
11
+ export interface ServedModelInfo {
12
+ readonly config: ModelConfig;
13
+ readonly weightsBytes: number;
14
+ }
15
+
16
+ export interface BuiltPrompt {
17
+ promptIds: number[];
18
+ vision: Vision | undefined;
19
+ startInThinking: boolean;
20
+ probeStableLen: boolean;
21
+ diffusionPixels: MlxArray | null;
22
+ }
23
+
24
+ export interface ModelPromptBuilder {
25
+ (body: ChatRequestParams, tools: ChatRequestParams["tools"] | null,
26
+ ownership: RequestOwnership, prep: RequestPrep): Promise<BuiltPrompt>;
27
+ }
28
+
29
+ /** Model-owned native services. A replacement supplies this one binding;
30
+ * routes and sessions consume it without requiring a concrete model class. */
31
+ export interface ModelServingBinding {
32
+ /** Opaque identity of the backend numerics that produced persisted state. */
33
+ readonly stateCompatibility: string;
34
+ readonly gateway: MlxGatewayBinding;
35
+ createSerial(services: MlxSerialServices): SerialRun;
36
+ readonly buildPrompt: ModelPromptBuilder;
37
+ restore(store: SsdCacheStore, entry: SsdIndexEntry): ReturnType<SsdCacheStore["restore"]>;
38
+ signal(promptIds: number[], bins: number, minimum: number): Promise<{ bins: number[]; vocab: number }>;
39
+ diagnostics(): Record<string, unknown>;
40
+ readonly discovery: { readonly adapters: boolean; readonly training: boolean;
41
+ readonly dsa: unknown; readonly embeddings: boolean };
42
+ embed?(inputs: string[], instruction?: string): ReturnType<typeof import("../embed").embedMany>;
43
+ }
@@ -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
+ }