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