mlx-bun 0.4.0 → 1.0.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 (601) hide show
  1. package/README.md +1453 -88
  2. package/THIRD_PARTY_NOTICES.md +882 -0
  3. package/bin/mlx-bun.convert.mjs +4 -0
  4. package/bin/mlx-bun.fuse.mjs +4 -0
  5. package/bin/mlx-bun.generate.mjs +4 -0
  6. package/bin/mlx-bun.lora.mjs +4 -0
  7. package/bin/mlx-bun.mjs +13 -21
  8. package/bin/mlx-bun.server.mjs +4 -0
  9. package/bin/mlx-bun.upload.mjs +4 -0
  10. package/dist/web/app.js +9584 -0
  11. package/package.json +50 -53
  12. package/src/cli/ane-install.ts +76 -0
  13. package/src/cli/args.ts +179 -0
  14. package/src/cli/engine-entry.ts +68 -0
  15. package/src/cli/inference.ts +214 -0
  16. package/src/cli/job-entry.ts +97 -0
  17. package/src/cli/library-host.ts +117 -0
  18. package/src/cli/main.ts +57 -0
  19. package/src/cli/memory-engine.ts +163 -0
  20. package/src/cli/memory.ts +36 -0
  21. package/src/cli/mlx-lm-aliases.ts +309 -0
  22. package/src/cli/model-choice.ts +33 -0
  23. package/src/cli/model-selection.ts +84 -0
  24. package/src/cli/module-host.ts +11 -0
  25. package/src/cli/module-verbs.ts +50 -0
  26. package/src/cli/numerical-policy.ts +12 -0
  27. package/src/cli/perplexity.ts +89 -0
  28. package/src/cli/serve-host.ts +423 -0
  29. package/src/cli/serve-isolated.ts +217 -0
  30. package/src/cli/serve-options.ts +106 -0
  31. package/src/cli/serve-state.ts +205 -0
  32. package/src/cli/serve.ts +500 -0
  33. package/src/cli/served-model-host.ts +102 -0
  34. package/src/cli/server-entry.ts +148 -0
  35. package/src/cli/serving-unit.ts +177 -0
  36. package/src/{tui.ts → cli/terminal.ts} +13 -8
  37. package/src/cli/worker-adapters.ts +34 -0
  38. package/src/cli/worker-entry.ts +272 -0
  39. package/src/cli/worker-unit.ts +179 -0
  40. package/src/engine/adapter-operation.ts +26 -0
  41. package/src/engine/cache-services.ts +114 -0
  42. package/src/engine/completion.ts +39 -0
  43. package/src/engine/generation-gateway.ts +358 -0
  44. package/src/engine/index.ts +59 -0
  45. package/src/engine/kv-budget.ts +120 -0
  46. package/src/engine/media-preparation.ts +232 -0
  47. package/src/engine/model-binding.ts +24 -0
  48. package/src/engine/model-host.ts +513 -0
  49. package/src/engine/model-serving.ts +89 -0
  50. package/src/{serve → engine}/preparation.ts +10 -8
  51. package/src/{serve → engine}/session-completion-engine.ts +6 -6
  52. package/src/engine/telemetry.ts +109 -0
  53. package/src/hub/downloads.ts +116 -0
  54. package/src/jobs/db.ts +16 -7
  55. package/src/jobs/events.ts +29 -0
  56. package/src/jobs/executable.ts +5 -0
  57. package/src/jobs/host.ts +51 -0
  58. package/src/jobs/in-process.ts +55 -0
  59. package/src/{contracts/jobs.ts → jobs/protocol.ts} +7 -9
  60. package/src/jobs/runner.ts +150 -231
  61. package/src/jobs/service.ts +75 -0
  62. package/src/jobs/sse.ts +59 -23
  63. package/src/jobs/worker-memory.ts +46 -0
  64. package/src/jobs/worker-process.ts +163 -0
  65. package/src/jobs/worker-supervisor.ts +258 -0
  66. package/src/modules.ts +58 -0
  67. package/src/publishing/catalog-hub.ts +18 -0
  68. package/src/publishing/credentials.ts +31 -0
  69. package/src/publishing/upload.ts +37 -0
  70. package/src/residency/leased-adapters.ts +21 -0
  71. package/src/residency/local-records.ts +16 -0
  72. package/src/residency/model-residency.ts +405 -0
  73. package/src/residency/record-index.ts +28 -0
  74. package/src/residency/resident-estimate.ts +50 -0
  75. package/src/{anthropic.ts → server/anthropic.ts} +3 -81
  76. package/src/server/cache-routes.ts +36 -0
  77. package/src/{serve → server}/chat-request.ts +12 -10
  78. package/src/{serve → server}/chat-stage.ts +27 -22
  79. package/src/{client.ts → server/client.ts} +28 -2
  80. package/src/{serve → server}/completion-executor.ts +42 -42
  81. package/src/server/decision-body.ts +55 -0
  82. package/src/server/decision-routes.ts +134 -0
  83. package/src/server/decision-wire.ts +228 -0
  84. package/src/{serve → server}/discovery-routes.ts +42 -83
  85. package/src/server/generated-token-history.ts +57 -0
  86. package/src/{serve → server}/http.ts +25 -13
  87. package/src/{serve → server}/inference-request.ts +5 -5
  88. package/src/server/job-routes.ts +20 -0
  89. package/src/server/media-prompt.ts +63 -0
  90. package/src/server/memory-completion-client.ts +46 -0
  91. package/src/server/model-routes.ts +192 -0
  92. package/src/{serve → server}/openai-wire.ts +3 -2
  93. package/src/{serve → server}/pipeline.ts +1 -1
  94. package/src/server/prompt-builder.ts +13 -0
  95. package/src/server/prompt-contracts.ts +17 -0
  96. package/src/server/proxy-routes.ts +187 -0
  97. package/src/server/publishing-routes.ts +41 -0
  98. package/src/{serve → server}/request-plan.ts +8 -8
  99. package/src/{serve → server}/request-prep.ts +82 -68
  100. package/src/{serve → server}/responses-client.ts +30 -13
  101. package/src/{responses.ts → server/responses.ts} +12 -93
  102. package/src/server/routes.ts +205 -0
  103. package/src/server/start.ts +72 -0
  104. package/src/server/status-routes.ts +108 -0
  105. package/src/{serve → server}/text-completion-stage.ts +25 -4
  106. package/src/server/text-prompt.ts +12 -0
  107. package/src/{serve → server}/token-streams.ts +36 -38
  108. package/src/server/worker-routes.ts +311 -0
  109. package/src/storage/paths.ts +61 -0
  110. package/src/web/assets.ts +37 -0
  111. package/src/web/{src → browser}/api.ts +5 -23
  112. package/src/web/browser/chat-host.ts +17 -0
  113. package/src/web/browser/installed-panels.ts +6 -0
  114. package/src/web/browser/main.ts +55 -0
  115. package/src/web/browser/markdown.ts +279 -0
  116. package/src/web/browser/memory-panel.ts +9 -0
  117. package/src/web/browser/palette.ts +64 -0
  118. package/src/web/browser/protocol.ts +13 -0
  119. package/src/web/browser/shell.ts +467 -0
  120. package/src/web/{src → browser}/status.ts +32 -36
  121. package/src/web/build.ts +51 -0
  122. package/src/web/public/app.html +1054 -0
  123. package/src/web/{sw.js → public/sw.js} +4 -3
  124. package/src/web/{vendor → public/vendor}/hljs-theme.css +2 -2
  125. package/src/web/{vendor → public/vendor}/hljs.js +2 -2
  126. package/THIRD_PARTY_LICENSES.md +0 -51
  127. package/docs/README.md +0 -94
  128. package/docs/archive/hlg-sampling.md +0 -350
  129. package/docs/archive/investigations/audio-input-plan.md +0 -356
  130. package/docs/archive/investigations/chunk-finetune-experiment.md +0 -84
  131. package/docs/archive/investigations/colibri-glm52-port.md +0 -1486
  132. package/docs/archive/investigations/colibri-oracle-pin.md +0 -1284
  133. package/docs/archive/investigations/curve-bisector-routing.md +0 -123
  134. package/docs/archive/investigations/decode-roofline-lookagain.md +0 -348
  135. package/docs/archive/investigations/diffusion-gemma-port.md +0 -602
  136. package/docs/archive/investigations/dspark-handoff.md +0 -224
  137. package/docs/archive/investigations/expert-offload-single-user-moe.md +0 -292
  138. package/docs/archive/investigations/faithful-l1-consolidation.md +0 -310
  139. package/docs/archive/investigations/hlg-sampling-investigation.md +0 -970
  140. package/docs/archive/investigations/indexshare-performance-spike.md +0 -357
  141. package/docs/archive/investigations/kernel-perf-review-2026-07.md +0 -171
  142. package/docs/archive/investigations/lab-build-journal.md +0 -157
  143. package/docs/archive/investigations/minicpm5-decode-megakernel.md +0 -489
  144. package/docs/archive/investigations/openjarvis-fit.md +0 -198
  145. package/docs/archive/investigations/openwiki-evaluation.md +0 -249
  146. package/docs/archive/investigations/optimization_plan.md +0 -346
  147. package/docs/archive/investigations/orpo-base-uf-experiment-and-directions.md +0 -120
  148. package/docs/archive/investigations/orpo-flash-cce-pin-leak.md +0 -167
  149. package/docs/archive/investigations/orpo-uf-testing-handoff.md +0 -126
  150. package/docs/archive/investigations/pareto-specialized-runtime-findings.md +0 -92
  151. package/docs/archive/investigations/pi-builtin-investigation.md +0 -308
  152. package/docs/archive/investigations/pre-colibri-stabilization.md +0 -329
  153. package/docs/archive/investigations/qwen38-27b-campaign-log.md +0 -1092
  154. package/docs/archive/investigations/segmented-backward-handoff.md +0 -148
  155. package/docs/archive/investigations/starter-model-port-handoff.md +0 -342
  156. package/docs/archive/investigations/steel-flash-cce-handoff.md +0 -489
  157. package/docs/archive/investigations/the-dreaming-handoff.md +0 -141
  158. package/docs/archive/investigations/trainer-validation-experiment.md +0 -173
  159. package/docs/archive/planning/chat-ui-vision-memory-first.md +0 -199
  160. package/docs/archive/planning/chat-ui-vision.md +0 -50
  161. package/docs/archive/planning/chunk-task-roadmap.md +0 -77
  162. package/docs/archive/planning/curve-sampler-research-plan.md +0 -331
  163. package/docs/archive/planning/journal.md +0 -316
  164. package/docs/archive/planning/memory-docs-and-dag-plan.md +0 -194
  165. package/docs/archive/planning/pi-integration-review.md +0 -178
  166. package/docs/archive/planning/release-notes-v0.0.10.md +0 -57
  167. package/docs/archive/planning/release-notes-v0.0.11.md +0 -239
  168. package/docs/archive/planning/release-notes-v0.0.12.md +0 -80
  169. package/docs/archive/planning/release-notes-v0.0.13.md +0 -77
  170. package/docs/archive/planning/release-notes-v0.0.9.md +0 -122
  171. package/docs/archive/planning/release-notes-v0.2.0.md +0 -49
  172. package/docs/archive/planning/release-notes-v0.3.0.md +0 -35
  173. package/docs/archive/planning/web-ui-pass-plan.md +0 -213
  174. package/docs/archive/planning/website-readme-pass-plan.md +0 -224
  175. package/docs/design/batching.md +0 -1841
  176. package/docs/design/decode-speed-program.md +0 -2349
  177. package/docs/design/dreaming-nightly-pipeline.md +0 -684
  178. package/docs/design/generic-model-support.md +0 -705
  179. package/docs/design/kv-cache.md +0 -824
  180. package/docs/design/orpo-training.md +0 -680
  181. package/docs/design/speculative-decoding.md +0 -1990
  182. package/docs/design/turboquant.md +0 -2212
  183. package/docs/design/unified-engine-frontier-plan.md +0 -1880
  184. package/docs/design/web-chat-redesign.md +0 -695
  185. package/docs/planning/PRODUCT_ROADMAP.md +0 -594
  186. package/docs/planning/ResearchTopics.md +0 -119
  187. package/docs/planning/release-notes-v0.4.0.md +0 -45
  188. package/docs/planning/video-series.md +0 -421
  189. package/docs/reference/benchmarks.md +0 -3613
  190. package/docs/reference/cli.md +0 -585
  191. package/docs/reference/distribution.md +0 -355
  192. package/docs/reference/environment.md +0 -398
  193. package/docs/reference/glossary.md +0 -39
  194. package/docs/reference/library-api.md +0 -674
  195. package/docs/reference/memory.md +0 -260
  196. package/docs/reference/models.md +0 -334
  197. package/docs/reference/server-api.md +0 -1775
  198. package/docs/reference/server-config.md +0 -846
  199. package/docs/reference/training.md +0 -462
  200. package/docs/reference/troubleshooting.md +0 -158
  201. package/src/admission-plan.ts +0 -18
  202. package/src/audio/conformer.ts +0 -647
  203. package/src/audio/decode.ts +0 -133
  204. package/src/audio/features.ts +0 -202
  205. package/src/audio/transcode.ts +0 -67
  206. package/src/backends/mlx/assistant-target.ts +0 -46
  207. package/src/backends/mlx/autoregressive-draft-rows.ts +0 -120
  208. package/src/backends/mlx/autoregressive.ts +0 -108
  209. package/src/backends/mlx/batch-group.ts +0 -1790
  210. package/src/backends/mlx/cache-attachment.ts +0 -67
  211. package/src/backends/mlx/cache-layout.ts +0 -31
  212. package/src/backends/mlx/checkpoint-state.ts +0 -53
  213. package/src/backends/mlx/continuation-persistence.ts +0 -106
  214. package/src/backends/mlx/continuation-request.ts +0 -43
  215. package/src/backends/mlx/continuation.ts +0 -77
  216. package/src/backends/mlx/diffusion.ts +0 -39
  217. package/src/backends/mlx/draft-target.ts +0 -32
  218. package/src/backends/mlx/evaluation.ts +0 -105
  219. package/src/backends/mlx/fill-append.ts +0 -45
  220. package/src/backends/mlx/full-kv-row-append.ts +0 -32
  221. package/src/backends/mlx/full-kv-row-donor.ts +0 -54
  222. package/src/backends/mlx/full-transitioning-kv-rows.ts +0 -65
  223. package/src/backends/mlx/gateway-binding.ts +0 -130
  224. package/src/backends/mlx/graph.ts +0 -38
  225. package/src/backends/mlx/kv-codec.ts +0 -9
  226. package/src/backends/mlx/kv-maintenance.ts +0 -133
  227. package/src/backends/mlx/kv-tensor-rows.ts +0 -212
  228. package/src/backends/mlx/memory-client.ts +0 -189
  229. package/src/backends/mlx/methods.ts +0 -90
  230. package/src/backends/mlx/model-prompt.ts +0 -164
  231. package/src/backends/mlx/model-serving.ts +0 -79
  232. package/src/backends/mlx/prefill-cohort.ts +0 -89
  233. package/src/backends/mlx/prefill-rows.ts +0 -200
  234. package/src/backends/mlx/prefill.ts +0 -33
  235. package/src/backends/mlx/projected-context-rows.ts +0 -72
  236. package/src/backends/mlx/request-policy.ts +0 -20
  237. package/src/backends/mlx/request-state-policy.ts +0 -41
  238. package/src/backends/mlx/rollback.ts +0 -89
  239. package/src/backends/mlx/row-sampling.ts +0 -49
  240. package/src/backends/mlx/serial-executor.ts +0 -242
  241. package/src/backends/mlx/speculative-group.ts +0 -359
  242. package/src/backends/mlx/speculative-round.ts +0 -161
  243. package/src/backends/mlx/speculative.ts +0 -114
  244. package/src/backends/mlx/state-rows.ts +0 -104
  245. package/src/backends/mlx/state-views.ts +0 -46
  246. package/src/backends/mlx/target-layout-capability.ts +0 -35
  247. package/src/backends/mlx/text-engine.ts +0 -73
  248. package/src/backends/mlx/transitioning-kv-rows.ts +0 -165
  249. package/src/chat-template.ts +0 -382
  250. package/src/cli.ts +0 -3168
  251. package/src/config.ts +0 -399
  252. package/src/contracts/completion.ts +0 -16
  253. package/src/contracts/execution.ts +0 -60
  254. package/src/contracts/generation.ts +0 -103
  255. package/src/contracts/host.ts +0 -7
  256. package/src/contracts/pi-provider.ts +0 -30
  257. package/src/contracts/pi.ts +0 -259
  258. package/src/contracts/prefix-cache.ts +0 -23
  259. package/src/contracts/resources.ts +0 -25
  260. package/src/contracts/sampling.ts +0 -23
  261. package/src/contracts/scheduling.ts +0 -45
  262. package/src/contracts/tsconfig.json +0 -14
  263. package/src/dataset/generators.ts +0 -1087
  264. package/src/dataset/index.ts +0 -12
  265. package/src/dataset/job.ts +0 -81
  266. package/src/dataset/llm.ts +0 -71
  267. package/src/dataset/registry.ts +0 -528
  268. package/src/diffusion/diffusion-generate.ts +0 -507
  269. package/src/download.ts +0 -505
  270. package/src/embed.ts +0 -77
  271. package/src/engine/admission.ts +0 -59
  272. package/src/engine/cancellation.ts +0 -38
  273. package/src/engine/engine.ts +0 -56
  274. package/src/engine/execution-coordinator.ts +0 -70
  275. package/src/engine/execution-plan.ts +0 -53
  276. package/src/engine/resources.ts +0 -53
  277. package/src/engine/scheduler.ts +0 -72
  278. package/src/engine/session.ts +0 -247
  279. package/src/eval/README.md +0 -130
  280. package/src/eval/ifeval.ts +0 -81
  281. package/src/eval/kl-prompts.ts +0 -29
  282. package/src/eval/kl.ts +0 -590
  283. package/src/eval/perplexity.ts +0 -164
  284. package/src/eval/quality-db.ts +0 -92
  285. package/src/eval/reference-logits.ts +0 -207
  286. package/src/eval/runner.ts +0 -124
  287. package/src/eval/score.ts +0 -49
  288. package/src/eval/tasks/bfcl.ts +0 -535
  289. package/src/eval/tasks/gsm8k.ts +0 -98
  290. package/src/eval/tasks/hashhop.ts +0 -139
  291. package/src/eval/tasks/humaneval.ts +0 -275
  292. package/src/eval/tasks/ifeval.ts +0 -525
  293. package/src/eval/tasks/mmlu.ts +0 -157
  294. package/src/eval/ultrafeedback.ts +0 -60
  295. package/src/evaldb.ts +0 -199
  296. package/src/expert-io.ts +0 -393
  297. package/src/expert-offload-build.ts +0 -77
  298. package/src/expert-offload.ts +0 -76
  299. package/src/expert-residency.ts +0 -1134
  300. package/src/expert-usage.ts +0 -415
  301. package/src/fill/echo-index.ts +0 -188
  302. package/src/fill/fill-session.ts +0 -452
  303. package/src/fill/proposal.ts +0 -68
  304. package/src/fill/schema-rows.ts +0 -506
  305. package/src/fill/tool-boundary.ts +0 -103
  306. package/src/fit.ts +0 -249
  307. package/src/generate.ts +0 -1346
  308. package/src/grammar.ts +0 -591
  309. package/src/harness-pi.ts +0 -184
  310. package/src/hf-push.ts +0 -628
  311. package/src/hub-rest.ts +0 -242
  312. package/src/index.ts +0 -63
  313. package/src/inference/denoising.ts +0 -17
  314. package/src/inference/draft-acceptance.ts +0 -41
  315. package/src/inference/draft-output.ts +0 -49
  316. package/src/inference/graph.ts +0 -33
  317. package/src/inference/prefill.ts +0 -39
  318. package/src/inference/rollback.ts +0 -7
  319. package/src/jobs/index.ts +0 -31
  320. package/src/jobs/job-entry.ts +0 -107
  321. package/src/jobs/task-client.ts +0 -19
  322. package/src/jobs/types.ts +0 -2
  323. package/src/kv-scheme.ts +0 -257
  324. package/src/kv-store.ts +0 -1099
  325. package/src/lab/README.md +0 -18
  326. package/src/lab/curve/curve-designer.html +0 -303
  327. package/src/lab/curve/curve-sampler.ts +0 -122
  328. package/src/lab/expert-trace/expert-trace.ts +0 -69
  329. package/src/lab/paged-kv/paged-kv-rows.ts +0 -83
  330. package/src/lab/paged-kv/paged-kv.ts +0 -270
  331. package/src/library.ts +0 -40
  332. package/src/lora.ts +0 -408
  333. package/src/md-modules.d.ts +0 -49
  334. package/src/media-fetch.ts +0 -442
  335. package/src/memory/article.ts +0 -558
  336. package/src/memory/chunk-validation.ts +0 -150
  337. package/src/memory/chunk.ts +0 -318
  338. package/src/memory/cluster.ts +0 -351
  339. package/src/memory/coverage.ts +0 -134
  340. package/src/memory/crosslink.ts +0 -0
  341. package/src/memory/db.ts +0 -253
  342. package/src/memory/entity.ts +0 -203
  343. package/src/memory/gate.ts +0 -187
  344. package/src/memory/history.ts +0 -152
  345. package/src/memory/ingest.ts +0 -335
  346. package/src/memory/model.ts +0 -183
  347. package/src/memory/normalize.ts +0 -671
  348. package/src/memory/parse.ts +0 -22
  349. package/src/memory/pipeline.ts +0 -275
  350. package/src/memory/prompts.ts +0 -65
  351. package/src/memory/query.ts +0 -334
  352. package/src/memory/reconcile.ts +0 -734
  353. package/src/memory/redirect.ts +0 -108
  354. package/src/memory/reindex.ts +0 -325
  355. package/src/memory/resolve.ts +0 -307
  356. package/src/memory/rest.ts +0 -245
  357. package/src/memory/route.ts +0 -272
  358. package/src/memory/schedule.ts +0 -165
  359. package/src/memory/stages.ts +0 -777
  360. package/src/memory/synthesize.ts +0 -1638
  361. package/src/memory/tools.ts +0 -749
  362. package/src/memory/vault.ts +0 -1194
  363. package/src/memory/wikify.ts +0 -1064
  364. package/src/mlx/array.ts +0 -388
  365. package/src/mlx/autograd.ts +0 -304
  366. package/src/mlx/checkpoint.ts +0 -149
  367. package/src/mlx/compile.ts +0 -168
  368. package/src/mlx/custom-vjp.ts +0 -188
  369. package/src/mlx/ffi.ts +0 -512
  370. package/src/mlx/materialize.ts +0 -23
  371. package/src/mlx/metal-kernel.ts +0 -159
  372. package/src/mlx/ops.ts +0 -1021
  373. package/src/mlx/quantized-rows.ts +0 -36
  374. package/src/mlx/token-bitmask.ts +0 -52
  375. package/src/mlx/turboquant-kv-decode.ts +0 -82
  376. package/src/mlx/turboquant-kv-inverse.ts +0 -122
  377. package/src/mlx/turboquant-ops.ts +0 -861
  378. package/src/mlx/turboquant-tables.ts +0 -237
  379. package/src/mmap.ts +0 -90
  380. package/src/model/artifact-identity.ts +0 -73
  381. package/src/model/batched-kv.ts +0 -235
  382. package/src/model/batched-mask.ts +0 -279
  383. package/src/model/batched-quant.ts +0 -212
  384. package/src/model/batched-quantized-kv.ts +0 -144
  385. package/src/model/batched-rotating-quant.ts +0 -353
  386. package/src/model/batched-rotating-state.ts +0 -149
  387. package/src/model/batched-rotating.ts +0 -338
  388. package/src/model/batched-row-storage.ts +0 -179
  389. package/src/model/batched-ssm.ts +0 -52
  390. package/src/model/batched-turboquant-kv.ts +0 -93
  391. package/src/model/compiled-decode.ts +0 -712
  392. package/src/model/decoded-kv-donor.ts +0 -12
  393. package/src/model/delayed-quantized-kv.ts +0 -72
  394. package/src/model/delayed-rotating-quantized-kv.ts +0 -93
  395. package/src/model/delayed-turboquant-kv.ts +0 -55
  396. package/src/model/diffusion-gemma.ts +0 -1026
  397. package/src/model/factory.ts +0 -189
  398. package/src/model/fingerprint.ts +0 -33
  399. package/src/model/flash-attention.ts +0 -694
  400. package/src/model/full-prefill-padding.ts +0 -56
  401. package/src/model/full-prefill-row.ts +0 -105
  402. package/src/model/gemma4-base.ts +0 -2351
  403. package/src/model/gemma4.ts +0 -1315
  404. package/src/model/generated/gemma4-12b.ts +0 -429
  405. package/src/model/generated/gemma4-26b.ts +0 -448
  406. package/src/model/generated/gemma4-e4b.ts +0 -717
  407. package/src/model/generated/index.ts +0 -18
  408. package/src/model/glm52-atlas.ts +0 -511
  409. package/src/model/glm52-cache.ts +0 -792
  410. package/src/model/glm52-config.ts +0 -262
  411. package/src/model/glm52-container.ts +0 -305
  412. package/src/model/glm52-coupling.ts +0 -388
  413. package/src/model/glm52-dsa.ts +0 -606
  414. package/src/model/glm52-expert-layout.ts +0 -253
  415. package/src/model/glm52-layout.ts +0 -152
  416. package/src/model/glm52-memory.ts +0 -500
  417. package/src/model/glm52-mla.ts +0 -792
  418. package/src/model/glm52-moe.ts +0 -223
  419. package/src/model/glm52-pilot.ts +0 -537
  420. package/src/model/glm52-reference.ts +0 -445
  421. package/src/model/glm52-residency.ts +0 -557
  422. package/src/model/glm52-resident-weights.ts +0 -135
  423. package/src/model/glm52-streamed-experts.ts +0 -453
  424. package/src/model/glm52-streamed-metal.ts +0 -610
  425. package/src/model/glm52-weights.ts +0 -503
  426. package/src/model/glm52.ts +0 -1132
  427. package/src/model/implementation.ts +0 -69
  428. package/src/model/kv-attention-view.ts +0 -67
  429. package/src/model/minicpm5.ts +0 -376
  430. package/src/model/profile.ts +0 -443
  431. package/src/model/qwen-append.ts +0 -12
  432. package/src/model/qwen-conv.ts +0 -52
  433. package/src/model/qwen3-delta-state.ts +0 -74
  434. package/src/model/qwen3-delta.ts +0 -451
  435. package/src/model/qwen3-moe.ts +0 -404
  436. package/src/model/qwen3-mrope.ts +0 -252
  437. package/src/model/qwen3.ts +0 -277
  438. package/src/model/qwen3_5-checkpoint.ts +0 -164
  439. package/src/model/qwen3_5.ts +0 -819
  440. package/src/model/rotating-kv-donor.ts +0 -35
  441. package/src/model/rotating-kv-layout.ts +0 -262
  442. package/src/model/rotating-row-transaction.ts +0 -35
  443. package/src/model/speculative-rotating-kv.ts +0 -101
  444. package/src/model/ssm-prefill-padding.ts +0 -39
  445. package/src/model/support.ts +0 -102
  446. package/src/model/trellis-balanced-scatter.ts +0 -51
  447. package/src/model/trellis-linear.ts +0 -672
  448. package/src/model/trellis-shared-m.ts +0 -151
  449. package/src/model/trellis-shared-scatter.ts +0 -144
  450. package/src/model/trellis-splitk-prefill.ts +0 -158
  451. package/src/model/trellis-tiled-prefill.ts +0 -136
  452. package/src/model/trellis-vector-expand.ts +0 -62
  453. package/src/model/trellis-wide-prefill.ts +0 -94
  454. package/src/model/turboquant-codec.ts +0 -83
  455. package/src/model/universal/archs.ts +0 -332
  456. package/src/model/universal/dense.ts +0 -612
  457. package/src/model/universal/modules.ts +0 -170
  458. package/src/model/universal/rope.ts +0 -381
  459. package/src/native/expert_io.c +0 -523
  460. package/src/native/frame_extract.swift +0 -140
  461. package/src/native-pack.ts +0 -162
  462. package/src/pi-provider.ts +0 -53
  463. package/src/pi-session.ts +0 -81
  464. package/src/pi-terminal.ts +0 -274
  465. package/src/pi-web.ts +0 -1932
  466. package/src/preflight.ts +0 -158
  467. package/src/prompt-cache.ts +0 -460
  468. package/src/quantize/allocator.ts +0 -627
  469. package/src/quantize/atomic-output.ts +0 -38
  470. package/src/quantize/calibration.ts +0 -181
  471. package/src/quantize/config-writer.ts +0 -145
  472. package/src/quantize/index.ts +0 -84
  473. package/src/quantize/job.ts +0 -162
  474. package/src/quantize/quantizer.ts +0 -666
  475. package/src/quantize/rotate.ts +0 -603
  476. package/src/quantize/safetensors-writer.ts +0 -249
  477. package/src/quantize/sensitivity.ts +0 -216
  478. package/src/quantize/trellis.ts +0 -586
  479. package/src/quantize/weight-transform.ts +0 -292
  480. package/src/registry.ts +0 -602
  481. package/src/runtime-config.ts +0 -81
  482. package/src/safetensors.ts +0 -158
  483. package/src/sampler.ts +0 -1011
  484. package/src/serve/admin-routes.ts +0 -184
  485. package/src/serve/assets/curve-terrain.html +0 -105
  486. package/src/serve/assets/training-inference-map.html +0 -575
  487. package/src/serve/aux-routes.ts +0 -132
  488. package/src/serve/batch-scheduler.ts +0 -8
  489. package/src/serve/checkpoint-identity.ts +0 -64
  490. package/src/serve/generation-gateway.ts +0 -496
  491. package/src/serve/isolate.ts +0 -609
  492. package/src/serve/kv-budget.ts +0 -14
  493. package/src/serve/lab-routes.ts +0 -341
  494. package/src/serve/lane-registry.ts +0 -45
  495. package/src/serve/model-admin-routes.ts +0 -155
  496. package/src/serve/model-binding.ts +0 -43
  497. package/src/serve/model-host.ts +0 -511
  498. package/src/serve/parent-application.ts +0 -56
  499. package/src/serve/prompt-response-trace.ts +0 -147
  500. package/src/serve/response-lease.ts +0 -24
  501. package/src/serve/session-search.ts +0 -326
  502. package/src/serve/static-routes.ts +0 -101
  503. package/src/server.ts +0 -1314
  504. package/src/spec/assistant-rows.ts +0 -92
  505. package/src/spec/assistant-source.ts +0 -126
  506. package/src/spec/cache-identity.ts +0 -22
  507. package/src/spec/deepspec-rows.ts +0 -29
  508. package/src/spec/deepspec-source.ts +0 -145
  509. package/src/spec/dflash-source.ts +0 -149
  510. package/src/spec/drafter.ts +0 -304
  511. package/src/spec/dspark/ab-stats.ts +0 -136
  512. package/src/spec/dspark/calibration.ts +0 -112
  513. package/src/spec/dspark/data-dflash.ts +0 -156
  514. package/src/spec/dspark/data.ts +0 -201
  515. package/src/spec/dspark/deepspec-module.ts +0 -776
  516. package/src/spec/dspark/generate-dflash.ts +0 -245
  517. package/src/spec/dspark/generate.ts +0 -290
  518. package/src/spec/dspark/loader.ts +0 -23
  519. package/src/spec/dspark/loss.ts +0 -213
  520. package/src/spec/dspark/module-dflash.ts +0 -560
  521. package/src/spec/dspark/module.ts +0 -540
  522. package/src/spec/dspark/quantize-drafter.ts +0 -91
  523. package/src/spec/dspark/sample.ts +0 -112
  524. package/src/spec/generate.ts +0 -276
  525. package/src/spec/glm52-mtp-graph.ts +0 -29
  526. package/src/spec/glm52-mtp-rows.ts +0 -132
  527. package/src/spec/glm52-mtp-source.ts +0 -317
  528. package/src/spec/glm52-mtp-state.ts +0 -33
  529. package/src/spec/ngram-source.ts +0 -204
  530. package/src/spec/projected-draft-rows.ts +0 -73
  531. package/src/spec/qwen-mtp-module.ts +0 -171
  532. package/src/spec/qwen-mtp-rows.ts +0 -219
  533. package/src/spec/qwen-mtp-source.ts +0 -383
  534. package/src/spec/qwen-mtp-state.ts +0 -30
  535. package/src/spec/serve-loop.ts +0 -585
  536. package/src/spec/source.ts +0 -215
  537. package/src/spec/two-model-rows.ts +0 -61
  538. package/src/spec/two-model.ts +0 -113
  539. package/src/ssd-cache.ts +0 -372
  540. package/src/ssd-durability.ts +0 -211
  541. package/src/tokenizer.ts +0 -335
  542. package/src/tool-approvals.ts +0 -131
  543. package/src/tool-call.ts +0 -695
  544. package/src/train/dataset.ts +0 -484
  545. package/src/train/diffusion-lora.ts +0 -216
  546. package/src/train/export.ts +0 -32
  547. package/src/train/flash-cce.ts +0 -1234
  548. package/src/train/forward.ts +0 -266
  549. package/src/train/fuse.ts +0 -243
  550. package/src/train/index.ts +0 -46
  551. package/src/train/job.ts +0 -205
  552. package/src/train/lora-params.ts +0 -254
  553. package/src/train/loss.ts +0 -1591
  554. package/src/train/merge.ts +0 -195
  555. package/src/train/optimizer.ts +0 -183
  556. package/src/train/prefix-shared.ts +0 -490
  557. package/src/train/rank.ts +0 -137
  558. package/src/train/segmented.ts +0 -1828
  559. package/src/train/steel-qmm-header.ts +0 -1461
  560. package/src/train/trainer.ts +0 -1221
  561. package/src/train/watch.ts +0 -542
  562. package/src/vision/diffusion-vision.ts +0 -620
  563. package/src/vision/embedder.ts +0 -168
  564. package/src/vision/preprocess.ts +0 -247
  565. package/src/vision/prompt.ts +0 -373
  566. package/src/vision/qwen3vl-preprocess.ts +0 -409
  567. package/src/vision/qwen3vl-prompt.ts +0 -196
  568. package/src/vision/qwen3vl-tower.ts +0 -555
  569. package/src/vision/siglip.ts +0 -599
  570. package/src/vision/video-frames.ts +0 -148
  571. package/src/web/app.html +0 -2143
  572. package/src/web/app.js +0 -5703
  573. package/src/web/skills/memory/SKILL.md +0 -120
  574. package/src/web/skills/web-research/SKILL.md +0 -46
  575. package/src/web/skills.ts +0 -97
  576. package/src/web/src/adapters-panel.ts +0 -288
  577. package/src/web/src/assistant.ts +0 -451
  578. package/src/web/src/chat.ts +0 -1057
  579. package/src/web/src/composer.ts +0 -959
  580. package/src/web/src/dataset.ts +0 -132
  581. package/src/web/src/finetune.ts +0 -267
  582. package/src/web/src/hub.ts +0 -428
  583. package/src/web/src/main.ts +0 -98
  584. package/src/web/src/markdown.ts +0 -0
  585. package/src/web/src/memory-panel.ts +0 -572
  586. package/src/web/src/model-picker.ts +0 -159
  587. package/src/web/src/palette.ts +0 -346
  588. package/src/web/src/protocol.ts +0 -26
  589. package/src/web/src/quantize.ts +0 -167
  590. package/src/web/src/rag.ts +0 -274
  591. package/src/web/src/sessions.ts +0 -469
  592. package/src/web/src/shell.ts +0 -804
  593. package/src/web/src/ui-catalog.ts +0 -78
  594. package/src/web/vendor/README.md +0 -61
  595. package/src/web-assets.ts +0 -47
  596. package/src/web-tools.ts +0 -478
  597. package/src/weights.ts +0 -255
  598. /package/src/{serve → server}/completion-sink.ts +0 -0
  599. /package/src/web/{icon.svg → public/icon.svg} +0 -0
  600. /package/src/web/{manifest.webmanifest → public/manifest.webmanifest} +0 -0
  601. /package/src/web/{vendor → public/vendor}/hljs-LICENSE +0 -0
@@ -1,1790 +0,0 @@
1
- import type { OrdinaryContinuation } from "./continuation";
2
- import type { MlxRequestStatePolicy } from "./request-state-policy";
3
- import { AdmissionRejected } from "../../engine/admission";
4
- import type { ExecutionContext, ExecutionGroup } from "../../contracts/scheduling";
5
- import { driveExecutionGroup } from "../../engine/scheduler";
6
- import { disposeResources, withResource } from "../../engine/resources";
7
- import type { DisposableResource } from "../../contracts/resources";
8
- import { MlxPrefillCohort, type PrefillState } from "./prefill-cohort";
9
- // Continuous-batching scheduler for `--batch N` serving (phase S2, the engine
10
- // loop). Owns ONE running batch and drives it forward one decode step at a
11
- // time, admitting waiting requests and evicting finished ones between steps —
12
- // iteration-level (continuous) scheduling, not static batching. See
13
- // docs/design/batching.md and docs/design/batching.md.
14
- //
15
- // The numerically-hard parts are verified primitives:
16
- // - the batched FORWARD (per-row RoPE/mask) is bit-parity with mlx-lm B=N
17
- // across all 4 models (tests/batched-decode-parity);
18
- // - the dynamic-B FULL-attention ops mergeKVRows / filterKVRows match mlx-lm
19
- // BatchKVCache (tests/batched-decode-parity), and the SLIDING-window
20
- // BatchedRotatingCache (merge/filter/decode/make_mask incl. ring-wrap)
21
- // matches mlx-lm BatchRotatingKVCache (tests/batched-rotating).
22
- // This module is the ORCHESTRATION on top: admission, the step loop, per-row
23
- // sampling + token accounting, eviction, and assembling each layer's batched
24
- // cache by type. Gate: tests/parity/batch-scheduler.test.ts (teacher-forced, KL).
25
- //
26
- // Per-layer cache types: a model interleaves full-attention layers (plain
27
- // KVCache, wrapped per step in a BatchedDecodeMaskCache) and sliding-window
28
- // layers (a persistent BatchedRotatingCache that is itself the batched cache +
29
- // mask). Full layers share one leftPad/offset (all rows advance together); the
30
- // rotating caches self-track per-row leftPad/offset as the ring wraps. The
31
- // per-row absolute position stays consistent across both (full: offset-leftPad;
32
- // rot: offsetArr) — see docs/design/batching.md. Hybrid gated-DeltaNet
33
- // models (Qwen3.5) add "ssm" layers: SSMCache state is plain [B,...] with no
34
- // temporal axis and no padding (rows solo-prefill unpadded, decode feeds one
35
- // real token per row), so merge/filter are B-axis concat/take and the cache
36
- // passes through the step unwrapped (no mask, no per-row RoPE — full layers
37
- // carry positions). Gate: GenerationGateway.place on cache capability.
38
- //
39
- // Engine mechanics (the serial decode loop's hygiene, transplanted —
40
- // batching-v2-plan step 3):
41
- // - PIPELINED decode: each step builds the NEXT step's graph from the
42
- // still-unread sampled-token array (asyncEval), then reads the PREVIOUS
43
- // step's tokens while the new step computes — mlx-lm GenerationBatch._step.
44
- // The pipeline is flushed (read + emit) before a join merges, so admission
45
- // never has to reconcile an in-flight token array with a new row.
46
- // - clearCache every 256 steps (serial's cadence; mlx-lm batched uses 512),
47
- // not every step — per-step clears trashed the buffer pool each token.
48
- // - CHUNKED, INTERLEAVED admission: a joiner prefills prefillChunkSize
49
- // tokens per loop iteration with one batch decode step run in between, so
50
- // running rows stall at most one chunk per joiner (mlx-lm interleaves the
51
- // same way), and the prefill transient stays bounded.
52
- // - Failure containment: one row's onToken throwing evicts THAT row (its
53
- // promise rejects); siblings keep decoding (mlx-lm `remove` semantics). A
54
- // forward/sampling error still drops the whole batch (can't be attributed
55
- // to a row).
56
- //
57
- // Bun-async, NO threads: a single detached driver loop owns the GPU for batched
58
- // mode (an ExclusiveLock keeps the serial fallback off the GPU concurrently).
59
- // When `admissionHeld` reports a waiting serial-lane request, the loop stops
60
- // admitting, finishes the running rows, and releases the lock so the serial
61
- // request runs (mlx-lm's drain_batch) — resumed via kick().
62
- // Joins re-merge the whole batch; the keep-the-running-batch `extend`
63
- // optimization is a later refinement (batching-v2-plan item a).
64
-
65
- import { MlxArray } from "../../mlx/array";
66
- import * as ops from "../../mlx/ops";
67
- import { activeMemory, cacheMemory, clearCache, Dtype, peakMemory } from "../../mlx/ffi";
68
- import { runtimeConfig, withRuntimeConfig, type RuntimeConfig } from "../../runtime-config";
69
- import { CompiledDecode } from "../../model/compiled-decode";
70
- import { legacyCompiledDecodeAvailable } from "./autoregressive";
71
- import type { Gemma4Model } from "../../model/gemma4";
72
- import {
73
- KVCache, QuantizedKVCache, RotatingKVCache, RotatingQuantizedKVCache,
74
- cacheSignature,
75
- isBatchableCache,
76
- isPlainKvCache,
77
- isQuantizedKvCache,
78
- isRotatingPlainCache,
79
- isRotatingQuantizedCache,
80
- isRowBatchCache,
81
- type BatchableCache,
82
- type Cache,
83
- } from "../../model/gemma4-base";
84
- import { BatchedDecodeMaskCache, mergeKVRows, extendKVRows, extractKVRow, filterKVRows } from "../../model/batched-mask";
85
- import {
86
- BatchedQuantDecodeMaskCache, extendQuantRows, extractQuantRow, filterQuantRows, mergeQuantRows,
87
- type QuantRow,
88
- } from "../../model/batched-quant";
89
- import { BatchedRotatingQuantCache } from "../../model/batched-rotating-quant";
90
- import { cloneSingleRowState, leaseCacheStates } from "./state-views";
91
- import { ownedCacheLayout } from "./cache-layout";
92
- import { createKvMaintenance, type KvMaintenance } from "./kv-maintenance";
93
- import type { KvScheme } from "../../kv-scheme";
94
- import { BatchedRotatingCache } from "../../model/batched-rotating";
95
- import { SSMCache } from "../../model/qwen3-delta";
96
- import type { RuntimeModel } from "../../model/factory";
97
- import type { GrammarController } from "../../grammar";
98
- import { independentGreedySampling } from "../../sampler";
99
- import { acquireModelWiredLimit } from "../../generate";
100
- import { batchRowKvBytes } from "../../serve/kv-budget";
101
- import type { PromptResponseTrace } from "../../serve/prompt-response-trace";
102
-
103
- /** Decode-pipeline kill switch (read once at load, like the serial loop's
104
- * MLX_BUN_COMPILED_DECODE): 1 ⇒ read each step's tokens synchronously. */
105
-
106
- /** Per-step phase timing (MLX_BUN_BATCH_STEP_TRACE=1, debug-only): where a
107
- * decode step's wall time goes — graph BUILD+dispatch (host), the pipelined
108
- * READ of the previous step's tokens (GPU wait), row EMIT (onToken/SSE), and
109
- * the GAP between consecutive steps (drive-loop + everything else). Sums
110
- * print via `stepTraceReport()` (the b1 profile experiment calls it). */
111
- const STEP_T = { t0: 0, lastEnd: 0, build: 0, read: 0, emit: 0, gap: 0, n: 0 };
112
- export function stepTraceReport(): string {
113
- const per = (x: number) => (STEP_T.n ? (x / STEP_T.n).toFixed(3) : "0");
114
- const s = `steps=${STEP_T.n} build=${per(STEP_T.build)}ms read=${per(STEP_T.read)}ms emit=${per(STEP_T.emit)}ms gap=${per(STEP_T.gap)}ms (per step)`;
115
- STEP_T.t0 = STEP_T.lastEnd = STEP_T.build = STEP_T.read = STEP_T.emit = STEP_T.gap = STEP_T.n = 0;
116
- return s;
117
- }
118
-
119
- // NOTE — oMLX-style "adaptive burst decode" (several steps per event-loop
120
- // yield, omlx/engine_core.py _step_burst) was ported here 2026-07-02 and
121
- // REFUTED by measurement: on this runtime it REGRESSED cpm5 B=4 aggregate
122
- // 345→289 tok/s, batch-lane B=1 149→121, and TTFT ~+100 ms (first-token SSE
123
- // flush waits out the burst budget). Their win exists because each Python
124
- // step hand-off ping-pongs the GIL with asyncio/uvicorn (~1 ms/token); Bun's
125
- // setImmediate hop costs microseconds, so bursting here only delays socket
126
- // flushes. Don't re-add without new evidence — the per-yield step below is
127
- // the measured optimum (docs/design/batching.md P4 notes).
128
-
129
- /** A token sampler for one row: (logits [1,V], step) → token array [1] on
130
- * device. Greedy is `(l) => ops.argmaxAxis(l, -1)`; richer closures fold in
131
- * temperature / top-p / logits processors + history (built per request from
132
- * its sampler options, exactly like generate()'s sampleStep). Called once per
133
- * step 0..maxTokens-1 for this row (never beyond maxTokens). */
134
- export type RowSampler = (logits1V: MlxArray, step: number) => MlxArray;
135
-
136
- /** A method prepares and advances rows; the shared executor owns queueing. */
137
- export interface MlxGroupPreparation {
138
- readonly rows: readonly Row[];
139
- readonly tokenWeight?: number;
140
- readonly canAdmit?: boolean;
141
- admit?(row: Row): void;
142
- advance(): Promise<boolean>;
143
- dispose(): void;
144
- }
145
- export interface MlxGroupMethodHost {
146
- readonly rows: readonly Row[];
147
- readonly runtime: RuntimeConfig;
148
- readonly prefillChunkSize: number;
149
- readonly promptCache: RowPromptCache | undefined;
150
- join(row: Row): void;
151
- filterRows(keep: number[]): void;
152
- publish(row: Row, token: number, logprobs?: import("../../generate").TokenLogprobs): Promise<void | boolean>;
153
- finish(row: Row, reason: "stop" | "length"): void;
154
- }
155
- export interface MlxGroupedMethod {
156
- prepare(row: Row): MlxGroupPreparation;
157
- advance(): Promise<void>;
158
- filterRows(keep: readonly number[], discard: boolean): void;
159
- dispose(): void;
160
- }
161
- export interface MlxGroupMethodRequest {
162
- /** Equal keys declare compatible method state, independent of queue size. */
163
- readonly key: string;
164
- readonly data: unknown;
165
- open(host: MlxGroupMethodHost): MlxGroupedMethod;
166
- }
167
-
168
- export type BatchRequest = BatchRequestFields & (
169
- | { method: MlxGroupMethodRequest; sample?: RowSampler }
170
- | { method?: undefined; sample: RowSampler }
171
- );
172
-
173
- interface BatchRequestFields {
174
- /** Optional ordinary continuation policy; owns persistence and sampler recovery. */
175
- continuation?: OrdinaryContinuation;
176
- statePolicy?: MlxRequestStatePolicy;
177
- context?: ExecutionContext;
178
- /** Resolve loaded-state identity under the execution lease, after any
179
- * queued adapter replacement has finished. */
180
- cacheNamespace?: string | (() => string);
181
- /** Resolved replay permission; standalone group callers retain auto mode. */
182
- compiledDecode?: boolean;
183
- promptIds: number[];
184
- /** Request policy overrides the execution group's captured prefill default. */
185
- prefillChunkSize?: number;
186
- maxTokens: number;
187
- eosTokenIds: number[];
188
- /** Called per emitted (non-EOS) token, in order. Returning `false` halts this
189
- * row (a decoded-text stop sequence fired) — matches generate()'s onToken
190
- * contract. EOS terminates the row WITHOUT an onToken call. Throwing evicts
191
- * THIS row only (its submit promise rejects; siblings continue). May be
192
- * async; keep it cheap — it runs inline in the step loop. */
193
- onToken: (token: number, logprobs?: import("../../generate").TokenLogprobs) => void | boolean | Promise<void | boolean>;
194
- /** Diagnostic-only request-local trace. */
195
- trace?: PromptResponseTrace;
196
- /** Closes the gateway's queue/admission span when this row leaves pending. */
197
- onAdmitted?: () => void;
198
- /** Client/request lifetime. An aborted pending row is removed before
199
- * admission; a row in prefill or decode is evicted at the next safe
200
- * scheduler boundary. */
201
- signal?: AbortSignal;
202
- /** The row's sampler is PLAIN GREEDY (temperature 0, no curve) with no
203
- * logits processors and no grammar — set by the gateway when true. Lets
204
- * the scheduler take the vectorized sampling fast path (ONE
205
- * log-softmax+argmax over [B,V] instead of B slice/sample/concat graphs)
206
- * when EVERY live row qualifies. Numerically identical per row
207
- * (row-independent ops, same per-row shapes); the per-row closure path
208
- * is the fallback and the MLX_BUN_BATCH_VEC_SAMPLE=0 kill switch. */
209
- plainGreedy?: boolean;
210
- /** Grammar controller for this row (B1: per-row matchers). When set, the
211
- * scheduler drives it: `accept()` after each emitted token (fires the async
212
- * bitmask fill), `await ready()` before the row's next sample (the sample
213
- * closure applies `applyMask`). Termination (grammar satisfied) is an
214
- * additional per-row stop source. The gateway OWNS disposal (finally around
215
- * submit()); the scheduler uses but never owns. Null on the degrade path. */
216
- grammar?: GrammarController;
217
- /** Stable cache boundary from the server's template probe (the serial
218
- * lane's options.snapshotAt): the prompt prefix the NEXT turn's render
219
- * preserves. The scheduler snapshots a trim-free prompt-cache entry at
220
- * min(this, promptIds.length-1) during the solo prefill — the oracle
221
- * invariant (mlx-lm insert_segments) that gives wrapped-ring models a
222
- * reuse path. Absent = still capped at promptIds.length-1. */
223
- snapshotAt?: number;
224
- }
225
-
226
- export interface BatchStats {
227
- spec?: import("../../generate").GenerateStats["spec"];
228
- promptTokens: number;
229
- generatedTokens: number;
230
- /** Prompt tokens served from the prompt cache (Phase 3.2): a joiner's solo
231
- * prefill starts from the longest usable cached prefix, exactly like the
232
- * serial lane's runGeneration take(). 0 on a cold prefill. */
233
- cachedTokens: number;
234
- finishReason: "stop" | "length";
235
- /** Wall-clock from admission (leaving the pending queue) to the first
236
- * emitted token — the row's prefill span on the batch lane. */
237
- prefillMs: number;
238
- /** Wall-clock from the first emitted token to finish. */
239
- decodeMs: number;
240
- }
241
-
242
- /** The slice of PromptCache the scheduler drives (structural — the server's
243
- * PromptCache satisfies it). take() on admission (any joiner: a restored
244
- * prefix + suffix prefill is byte-safe whether the row later merges or
245
- * not). put() paths: rows that finish NEVER-MERGED (adopted lone rows,
246
- * Phase 3.2) hand their pristine serial caches over zero-copy; rows that
247
- * finish INSIDE a multi-row batch get their KV EXTRACTED per row into
248
- * fresh serial caches first (mlx-lm server.py:872 extract_cache — the
249
- * cross-request reuse concurrent agents live on). */
250
- export type RowPromptCache = import("./checkpoint-state").MlxPrefixCache;
251
-
252
- export interface Row {
253
- spec?: import("../../generate").GenerateStats["spec"];
254
- req: BatchRequest;
255
- resolve: (s: BatchStats) => void;
256
- reject: (e: unknown) => void;
257
- current: number; // last emitted token, fed at the next step (pipeline cold)
258
- generated: number; // tokens emitted so far (incl. a terminating EOS)
259
- sampled: number; // sample() calls so far (leads `generated` by 1 in-pipeline)
260
- promptTokens: number;
261
- /** Prompt tokens restored from the prompt cache at admission (stats). */
262
- cachedTokens: number;
263
- /** performance.now() marks for BatchStats timing (0 = not reached). */
264
- admittedAt: number;
265
- firstTokenAt: number;
266
- closeTokenZero?: () => void;
267
- cacheNamespace?: string;
268
- /** Generated tokens whose KV actually entered the cache (fed as a step
269
- * input) — serial generate()'s `forwarded` list. promptIds+fed is the
270
- * exact token coverage of the row's caches, the put() entry key.
271
- * PER-ROW EXACT for every row: pushes are gated on the pending
272
- * register's per-slot real/placeholder flags (#pendingReal), so a
273
- * doomed slot's placeholder is never recorded — and if one ever DID
274
- * feed a forward, `fedTainted` flips instead (see #step's read). */
275
- fed: number[];
276
- /** A placeholder slot value fed this row's KV (junk token in the cache):
277
- * the coverage key is no longer derivable — extraction refuses.
278
- * Structurally unreachable today (a doomed row always evicts at the
279
- * emit that follows its placeholder, filtering the slot before the
280
- * next forward; cold steps never contain doomed rows because a flush
281
- * emits every in-flight token) — this flag makes `fed` provably exact
282
- * instead of resting on that timing chain. */
283
- fedTainted: boolean;
284
- /** Ever merged into a multi-row batch (or poisoned by a reject): its KV
285
- * is interleaved in batched buffers — a finish put() must EXTRACT the
286
- * row (#extractRowCaches) rather than adopt the inners. */
287
- merged: boolean;
288
- }
289
-
290
- /** Held while the batch is active; the serial fallback acquires the same lock. */
291
- export interface ExclusiveLock {
292
- acquire(): Promise<() => void>;
293
- }
294
-
295
- export interface MlxBatchExecutionGroupOptions {
296
- /** Scheduling work budget for extending an existing preparation cohort. */
297
- prefillBatchTokenLimit?: number;
298
- runtime?: RuntimeConfig;
299
- maxQueued?: number;
300
- stateCodecs?: import("../../kv-store").CacheCodecProvider;
301
- /** Max rows in the running batch (mlx-lm `--decode-concurrency`). */
302
- maxBatch: number;
303
- lock?: ExclusiveLock;
304
- /** Drain signal: while true, no NEW rows are admitted (running rows finish,
305
- * the lock is released) so a waiting serial-lane request can run — mlx-lm's
306
- * drain_batch. Pair with kick() when it flips back to false. */
307
- admissionHeld?: () => boolean;
308
- /** Joiner prefill chunk length (default 2048, the serial loop's constant). */
309
- prefillChunkSize?: number;
310
- /** Aggregate KV-byte budget across all running rows (batching-perf-path
311
- * P3 admission, via `--kv-budget`). A joiner whose PROJECTED KV
312
- * (kvBytesAt(config, prompt + maxTokens), sliding window already capped)
313
- * would push the batch's projected total over this ceiling WAITS in the
314
- * queue (FIFO, head-of-line — no starvation, no reorder) until rows
315
- * evict. A request that can NEVER fit (over budget alone, empty batch)
316
- * is rejected instead of deadlocking. Unset = unlimited (v1 behavior). */
317
- kvBudgetBytes?: number;
318
- /** Authoritative server-wide scheme. Each joiner's solo prefill converts at
319
- * the same chunk boundaries as the serial path, so a row's quantized bytes
320
- * preserve the L2 composition. Unsupported schemes fail at construction. */
321
- kvScheme?: KvScheme;
322
- /** Model binding owns support for precision transitions. */
323
- kvBatchCapabilities?: { delayedAffine?: boolean };
324
- /** Prompt-cache hook (Phase 3.2): admission take()s the longest usable
325
- * prefix into the joiner's solo caches (suffix-only prefill — the
326
- * multi-turn chat TTFT path); rows that finish never-merged put() their
327
- * caches back. Adapter requests never reach the batch lane, so the
328
- * namespace is always "" here. Runs under the gateway mutex domain, so
329
- * take/put never race the serial lane's use of the same cache. */
330
- promptCache?: RowPromptCache;
331
- }
332
-
333
- type LayerInner =
334
- | KVCache
335
- | QuantizedKVCache
336
- | BatchedRotatingCache
337
- | BatchedRotatingQuantCache // rot layer under a kv_config scheme (milestone 2)
338
- | RotatingKVCache // adopted lone-row state only (see #mergeJoiner adopt)
339
- | RotatingQuantizedKVCache // adopted lone-row state, quantized rot layer
340
- | SSMCache
341
- | BatchableCache;
342
- type Row1 = { keys: MlxArray; values: MlxArray };
343
-
344
- export class MlxBatchExecutionGroup {
345
- readonly #runtime: RuntimeConfig;
346
- readonly #noPipeline: boolean;
347
- readonly #stepTrace: boolean;
348
- readonly #stateCodecs: import("../../kv-store").CacheCodecProvider | undefined;
349
- readonly #maxQueued: number;
350
- #running: Row[] = [];
351
- #inners: LayerInner[] | null = null; // per-layer batched KV; null when empty
352
- #fullLeftPad: number[] = []; // per-row padding for FULL layers (rot self-tracks)
353
- #pending: Row[] = [];
354
- #prefill: MlxGroupPreparation | null = null; // the (single) joiner mid-prefill
355
- #preparationPublishedOutput = false;
356
- /** Sampled-but-unread token array [B], aligned with #running — the decode
357
- * pipeline register. Filtered/disposed alongside the batched KV. */
358
- #pendingToks: MlxArray | null = null;
359
- /** Per-slot flags for #pendingToks: true = a REAL sampled token of that
360
- * row's stream; false = a doomed/terminated row's placeholder (fed-token
361
- * accounting must skip it — see Row.fed/fedTainted). Filtered/cleared in
362
- * lockstep with the register. */
363
- #pendingReal: boolean[] | null = null;
364
- #method: MlxGroupedMethod | undefined;
365
- #methodKey: string | undefined;
366
- #steps = 0; // decode-step counter (clearCache cadence)
367
- #looping = false;
368
- #closed = false;
369
- #driver: Promise<void> | null = null;
370
- #wake: (() => void) | null = null;
371
- readonly #maxBatch: number;
372
- readonly #lock: ExclusiveLock | undefined;
373
- readonly #admissionHeld: (() => boolean) | undefined;
374
- readonly #prefillChunkSize: number;
375
- readonly #prefillBatchTokenLimit: number;
376
- readonly #prefillTailSplit: boolean;
377
- readonly #kvBudgetBytes: number | undefined;
378
- readonly #defaultPromptCache: RowPromptCache | undefined;
379
- #statePolicy?: MlxRequestStatePolicy;
380
- get #promptCache(): RowPromptCache | undefined {
381
- return this.#statePolicy ? this.#statePolicy.promptCache : this.#defaultPromptCache;
382
- }
383
- /** Retain hook of the currently-ADOPTED row's cache entry (at most one:
384
- * only a lone adopted row holds un-copied entry caches). Runs after the
385
- * adopted caches are disposed, or transfers back on put(). */
386
- #adoptedRetain: (() => void) | null = null;
387
- #contextKey: string | undefined;
388
- #releaseContext: (() => void) | undefined;
389
- readonly #kinds: ("full" | "rot" | "ssm" | "owned-batch")[];
390
- readonly #rotMaxSize: number[]; // per-layer sliding window (rot layers only)
391
- readonly #compressedProjectors: Array<(tokens: number) => number> | null;
392
- readonly #batchCacheMaxTokens: number | null;
393
- readonly #kvScheme: KvScheme | undefined;
394
- readonly #maintainKv: KvMaintenance | null;
395
- /** Compiled decode runner for the B=1 serial-class case (Phase 3.2) —
396
- * same eligibility gate as generate.ts (gemma dense, kill switch
397
- * MLX_BUN_COMPILED_DECODE); adapter requests disable replay in their plan. Set
398
- * to null permanently on a failed step (serial disables per
399
- * generation; the scheduler is one long-lived "generation"). */
400
- #compiled: CompiledDecode | null;
401
-
402
- constructor(private readonly model: RuntimeModel, opts: MlxBatchExecutionGroupOptions) {
403
- this.#runtime = opts.runtime ?? runtimeConfig();
404
- this.#noPipeline = this.#runtime.value("MLX_BUN_BATCH_NO_PIPELINE") === "1";
405
- this.#stepTrace = this.#runtime.value("MLX_BUN_BATCH_STEP_TRACE") === "1";
406
- this.#maxQueued = opts.maxQueued ?? 64;
407
- if (!Number.isSafeInteger(this.#maxQueued) || this.#maxQueued < 1) throw new Error("invalid batch queue limit");
408
- this.#stateCodecs = opts.stateCodecs;
409
- this.#maxBatch = Math.max(1, Math.floor(opts.maxBatch));
410
- this.#lock = opts.lock;
411
- this.#admissionHeld = opts.admissionHeld;
412
- this.#prefillChunkSize = Math.max(1, Math.floor(opts.prefillChunkSize ??
413
- this.#runtime.number("MLX_BUN_RD_PREFILL_CHUNK", 2048)));
414
- this.#prefillBatchTokenLimit = opts.prefillBatchTokenLimit ?? 2048;
415
- this.#prefillTailSplit = this.#runtime.flag("MLX_BUN_PREFILL_TAIL_SPLIT", true);
416
- this.#kvBudgetBytes = opts.kvBudgetBytes;
417
- this.#defaultPromptCache = opts.promptCache;
418
- this.#kvScheme = opts.kvScheme;
419
- const proto = withRuntimeConfig(this.#runtime, () => model.makeCache()); // fresh caches hold no buffers
420
- if (this.#kvScheme && !this.#kvScheme.batchable(
421
- model.config,
422
- (layerIdx) =>
423
- isPlainKvCache(proto[layerIdx]) || isRotatingPlainCache(proto[layerIdx]),
424
- proto.length, opts.kvBatchCapabilities,
425
- )) {
426
- for (const cache of proto) cache.dispose();
427
- throw new Error(`unsupported KV scheme for batch scheduler: ${this.#kvScheme.kind}`);
428
- }
429
- this.#kinds = proto.map((c) =>
430
- isBatchableCache(c)
431
- ? "owned-batch"
432
- : isRotatingPlainCache(c)
433
- ? "rot"
434
- : cacheSignature(c) === "ssm"
435
- ? "ssm"
436
- : "full",
437
- );
438
- this.#compressedProjectors = proto.every(isBatchableCache)
439
- ? proto.map((cache) => (tokens: number) => cache.projectedBytes(tokens))
440
- : null;
441
- this.#batchCacheMaxTokens = proto.every(isBatchableCache)
442
- ? Math.min(...proto.map((cache) => cache.maxTokens ?? Infinity))
443
- : null;
444
- this.#maintainKv = this.#kvScheme?.quantized
445
- ? createKvMaintenance(this.#kvScheme.options)
446
- : null;
447
- this.#rotMaxSize = proto.map((c) => (isRotatingPlainCache(c) ? c.maxSize : 0));
448
- for (const c of proto) c.dispose();
449
- this.#compiled =
450
- this.#runtime.flag("MLX_BUN_COMPILED_DECODE", true) &&
451
- legacyCompiledDecodeAvailable(model)
452
- ? withRuntimeConfig(this.#runtime, () => CompiledDecode.for(model as Gemma4Model))
453
- : null;
454
- }
455
-
456
- get activeRows(): number {
457
- return this.#running.length;
458
- }
459
-
460
- get pendingRows(): number {
461
- return this.#pending.length + (this.#prefill?.rows.length ?? 0);
462
- }
463
-
464
- /** Projected KV bytes of one row at its worst case (full prompt + full
465
- * completion; the sliding-window term is window-capped by kvBytesAt). */
466
- #rowKvBytes(row: Row): number {
467
- return this.#compressedProjectors
468
- ? this.#compressedProjectors.reduce(
469
- (sum, project) => sum + project(row.promptTokens + row.req.maxTokens),
470
- 0,
471
- )
472
- : batchRowKvBytes(
473
- this.model.config,
474
- row.promptTokens,
475
- row.req.maxTokens,
476
- this.#kvScheme,
477
- );
478
- }
479
-
480
- async #forwardHidden(ids: MlxArray, cache: Cache[]): Promise<MlxArray> {
481
- const asyncModel = this.model as RuntimeModel & {
482
- forwardHiddenAsync?: (ids: MlxArray, cache: Cache[]) => Promise<MlxArray>;
483
- };
484
- return typeof asyncModel.forwardHiddenAsync === "function"
485
- ? await asyncModel.forwardHiddenAsync(ids, cache)
486
- : this.model.forwardHidden(ids, cache);
487
- }
488
-
489
- /** Projected aggregate KV of everything admitted (running + mid-prefill). */
490
- get projectedKvBytes(): number {
491
- let total = this.#running.reduce((a, r) => a + this.#rowKvBytes(r), 0);
492
- if (this.#prefill) for (const row of this.#prefill.rows) total += this.#rowKvBytes(row);
493
- return total;
494
- }
495
-
496
- get kvBudgetBytes(): number | undefined {
497
- return this.#kvBudgetBytes;
498
- }
499
-
500
- /** KV-budget admission for the queue head. True = admit now. A candidate
501
- * that cannot fit even alone is rejected here (never deadlocks the
502
- * queue); one that fits alone but not alongside the current batch waits. */
503
- #kvAdmits(candidate: Row): boolean {
504
- const requestedTokens = candidate.promptTokens + candidate.req.maxTokens;
505
- if (
506
- this.#batchCacheMaxTokens !== null &&
507
- requestedTokens > this.#batchCacheMaxTokens
508
- ) {
509
- this.#pending.shift();
510
- candidate.reject(new RangeError(
511
- `context limit: prompt ${candidate.promptTokens} + max_tokens ` +
512
- `${candidate.req.maxTokens} exceeds ${this.#batchCacheMaxTokens}`,
513
- ));
514
- return false;
515
- }
516
- if (this.#kvBudgetBytes === undefined) return true;
517
- const need = this.#rowKvBytes(candidate);
518
- if (need > this.#kvBudgetBytes && this.#running.length === 0 && !this.#prefill) {
519
- this.#pending.shift();
520
- candidate.reject(
521
- new Error(
522
- `kv budget: request needs ~${(need / 1e9).toFixed(2)} GB KV ` +
523
- `(prompt ${candidate.promptTokens} + max_tokens ${candidate.req.maxTokens}), ` +
524
- `over --kv-budget ${(this.#kvBudgetBytes / 1e9).toFixed(2)} GB — ` +
525
- `lower max_tokens or raise the budget`,
526
- ),
527
- );
528
- return false;
529
- }
530
- return this.projectedKvBytes + need <= this.#kvBudgetBytes;
531
- }
532
-
533
- /** Submit a request; resolves when its row finishes (EOS, stop, or length). */
534
- submit(req: BatchRequest): Promise<BatchStats> {
535
- if (this.#closed) return Promise.reject(new Error("scheduler closed"));
536
- if (req.signal?.aborted) return Promise.reject(req.signal.reason);
537
- if (this.#pending.length >= this.#maxQueued) return Promise.reject(new AdmissionRejected());
538
- return new Promise<BatchStats>((resolve, reject) => {
539
- let abortListener: (() => void) | null = null;
540
- const cleanup = () => {
541
- if (abortListener) req.signal?.removeEventListener("abort", abortListener);
542
- abortListener = null;
543
- };
544
- this.#pending.push({
545
- req,
546
- resolve: (stats) => { cleanup(); resolve(stats); },
547
- reject: (error) => { cleanup(); reject(error); },
548
- current: 0, generated: 0, sampled: 0, promptTokens: req.promptIds.length,
549
- admittedAt: 0, firstTokenAt: 0,
550
- cachedTokens: 0, fed: [], fedTainted: false, merged: false,
551
- });
552
- if (req.signal) {
553
- abortListener = () => this.kick();
554
- req.signal.addEventListener("abort", abortListener, { once: true });
555
- }
556
- this.#ensureLoop();
557
- });
558
- }
559
-
560
- /** Wake the driver loop (e.g. after admissionHeld flips back to false). */
561
- kick(): void {
562
- this.#ensureLoop();
563
- }
564
-
565
- #ensureLoop(): void {
566
- if (this.#wake) { this.#wake(); return; }
567
- if (this.#looping || this.#closed) return;
568
- this.#looping = true;
569
- this.#driver = withRuntimeConfig(this.#runtime, () => this.#drive());
570
- void this.#driver.catch((error) => console.error(`batch scheduler cleanup failed: ${error}`));
571
- }
572
-
573
- /** Stop at the next safe work boundary and release all queued/active runs. */
574
- async close(): Promise<void> {
575
- this.#closed = true;
576
- this.#wake?.();
577
- await this.#driver;
578
- }
579
-
580
- async #drive(): Promise<void> {
581
- const scheduler = this;
582
- const group: ExecutionGroup = {
583
- get active() { return scheduler.#running.length; },
584
- get queued() { return scheduler.#pending.length; },
585
- get preparing() { return scheduler.#prefill !== null; },
586
- get preparingRows() { return scheduler.#prefill?.rows.length ?? 0; },
587
- get canPrepareMore() { return scheduler.#prefill?.canAdmit === true; },
588
- get preparingTokens() { return scheduler.#prefill?.tokenWeight ?? 0; },
589
- // Cache restoration belongs to preparation. A queued request's prompt
590
- // length is an upper bound until its cache owner resolves the prefix.
591
- get nextPreparationTokens() { return scheduler.#pending[0]?.promptTokens ?? 0; },
592
- get maxPreparationTokens() { return scheduler.#prefillBatchTokenLimit; },
593
- get preparationPublishedOutput() { return scheduler.#preparationPublishedOutput; },
594
- get maxActive() { return scheduler.#maxBatch; },
595
- get admissionHeld() { return scheduler.#admissionHeld?.() === true; },
596
- get closed() { return scheduler.#closed; },
597
- pruneCancelled() {
598
- for (let i = scheduler.#pending.length - 1; i >= 0; i--) {
599
- const row = scheduler.#pending[i]!;
600
- if (!row.req.signal?.aborted) continue;
601
- scheduler.#pending.splice(i, 1);
602
- row.reject(row.req.signal.reason);
603
- }
604
- },
605
- admitNext: () => this.#admitNext(),
606
- canBurst: () => this.#contextCompatible(this.#pending[0]!) &&
607
- (this.#kvBudgetBytes === undefined ||
608
- this.projectedKvBytes + this.#rowKvBytes(this.#pending[0]!) <= this.#kvBudgetBytes),
609
- advancePreparation: () => this.#advancePreparation(),
610
- advance: () => this.#method ? this.#method.advance() : this.#step(),
611
- failActive: (error) => {
612
- for (const row of this.#running) row.reject(error);
613
- this.#applyFilter([], true); // failed state never enters the prefix store
614
- },
615
- failAll: (error) => this.#failAll(error),
616
- reserveResidency: () => {
617
- const release = acquireModelWiredLimit(this.model);
618
- return () => disposeResources([
619
- { dispose: () => this.#leaveContext() }, { dispose: release },
620
- ]);
621
- },
622
- ...(this.#lock ? { acquireExecution: () => this.#lock!.acquire() } : {}),
623
- waitForWork: async () => {
624
- await new Promise<void>((resolve) => { this.#wake = resolve; });
625
- this.#wake = null;
626
- },
627
- };
628
- try {
629
- await driveExecutionGroup(group, {
630
- now: () => performance.now(),
631
- yield: () => new Promise<void>((resolve) => setImmediate(resolve)),
632
- }, this.#runtime.value("MLX_BUN_EARLY_FIRST_TOKEN") === "1");
633
- } finally { this.#looping = false; }
634
- }
635
-
636
- #contextCompatible(row: Row): boolean {
637
- return (!this.#running.length && !this.#prefill) || ((row.req.context?.key ?? "") === this.#contextKey && row.req.method?.key === this.#methodKey && row.req.statePolicy?.key === this.#statePolicy?.key);
638
- }
639
-
640
- #leaveContext(): void {
641
- const release = this.#releaseContext;
642
- this.#releaseContext = undefined;
643
- this.#contextKey = undefined;
644
- release?.();
645
- }
646
-
647
- #admitNext(): boolean {
648
- if (!this.#contextCompatible(this.#pending[0]!) || !this.#kvAdmits(this.#pending[0]!)) return false;
649
- const row = this.#pending.shift()!;
650
- try {
651
- this.#statePolicy = row.req.statePolicy;
652
- row.cacheNamespace = typeof row.req.cacheNamespace === "function"
653
- ? row.req.cacheNamespace() : row.req.cacheNamespace;
654
- const key = row.req.context?.key ?? "";
655
- if (key !== this.#contextKey) {
656
- this.#leaveContext();
657
- this.#releaseContext = row.req.context?.enter();
658
- this.#contextKey = key;
659
- }
660
- row.req.onAdmitted?.();
661
- row.admittedAt = performance.now();
662
- if (row.req.method?.key !== this.#methodKey) {
663
- this.#method?.dispose(); this.#method = undefined; this.#methodKey = undefined;
664
- if (row.req.method) {
665
- const executor = this;
666
- this.#method = row.req.method.open({
667
- get rows() { return executor.#running; }, runtime: this.#runtime,
668
- prefillChunkSize: this.#prefillChunkSize, promptCache: this.#promptCache,
669
- join: row => { this.#running.push(row); },
670
- filterRows: keep => this.#applyFilter(keep),
671
- publish: async (row, token, logprobs) => {
672
- row.req.signal?.throwIfAborted();
673
- this.#firstOutput(row);
674
- return row.req.onToken(token, logprobs);
675
- },
676
- finish: (row, reason) => this.#finish(row, reason),
677
- });
678
- this.#methodKey = row.req.method.key;
679
- }
680
- }
681
- if (this.#prefill) {
682
- this.#prefill.admit!(row);
683
- } else if (this.#method) {
684
- this.#prefill = this.#method.prepare(row);
685
- } else {
686
- const preparation = new MlxPrefillCohort({
687
- model: this.model, chunkSize: this.#prefillChunkSize, tailSplit: this.#prefillTailSplit,
688
- promptCache: this.#promptCache, stateCodecs: this.#stateCodecs, maintain: this.#maintainKv ?? undefined,
689
- forward: (ids, caches) => this.#forwardHidden(ids, caches),
690
- project: (hidden, caches, completed) => this.#projectPrefill(hidden, caches, completed),
691
- complete: (state, logits) => this.#completePrefill(state, logits),
692
- resume: state => this.#completePrefill(state, null),
693
- reject: (failed, error) => this.#rejectPreparingRows([failed], error),
694
- });
695
- preparation.admit(row); this.#prefill = preparation;
696
- }
697
- } catch (error) { row.reject(error); }
698
- return true;
699
- }
700
-
701
- #rejectPreparingRows(rows: readonly Row[], error: unknown): void {
702
- const retiring = new Set(rows);
703
- const keep = this.#running.flatMap((row, index) => retiring.has(row) ? [] : [index]);
704
- if (keep.length !== this.#running.length) this.#applyFilter(keep, true);
705
- for (const row of rows) row.reject(error);
706
- }
707
-
708
- async #advancePreparation(): Promise<void> {
709
- const p = this.#prefill!, rows = p.rows;
710
- this.#preparationPublishedOutput = false;
711
- try {
712
- if (await p.advance()) this.#prefill = null;
713
- } catch (error) {
714
- this.#prefill = null;
715
- let failure = error;
716
- try { p.dispose(); }
717
- catch (cleanupError) { failure = new AggregateError([error, cleanupError], "batch prefill and cleanup failed"); }
718
- try { this.#rejectPreparingRows(rows, failure); }
719
- catch (cleanupError) {
720
- failure = new AggregateError([failure, cleanupError], "batch admission retirement failed");
721
- for (const row of rows) row.reject(failure);
722
- this.#failAll(failure);
723
- }
724
- }
725
- }
726
-
727
- #failAll(error: unknown): void {
728
- const p = this.#prefill;
729
- const rows = new Set([...this.#running, ...this.#pending, ...(p?.rows ?? [])]);
730
- const retain = this.#adoptedRetain;
731
- const resources = [p, this.#method, ...(this.#inners ?? []), this.#pendingToks,
732
- { dispose: () => retain?.() }]
733
- .filter((resource): resource is DisposableResource => resource != null);
734
- this.#pending = []; this.#running = []; this.#prefill = null;
735
- this.#method = undefined; this.#methodKey = undefined;
736
- this.#inners = null; this.#pendingToks = null; this.#pendingReal = null;
737
- this.#fullLeftPad = []; this.#adoptedRetain = null;
738
- for (const row of rows) row.reject(error);
739
- disposeResources(resources);
740
- }
741
-
742
- /** Per-layer mixed-precision conversion of a joiner's SOLO caches — the
743
- * scheduler-side mirror of the serial maybeQuantizeKv (generate.ts): same
744
- * per-layer map, same skip rules (empty cache, already quantized), same
745
- * streaming discipline (evalAll the converted layer's state so the bf16
746
- * source frees before the next layer converts). Called at every prefill
747
- * chunk boundary AND once before merge, exactly where the serial loop
748
- * calls maybeQuantizeKv — that placement is what makes a row's quantized
749
- * bytes bit-exact vs serial `--kv-quant config`. Gateway placement and the
750
- * constructor both guarantee every named cache can convert. */
751
- #quantizeSolo(solo: Cache[], trace?: PromptResponseTrace): void {
752
- if (!this.#maintainKv) return;
753
- const close = trace?.begin("prefill.kv_maintenance", {
754
- mechanism: "continuous",
755
- });
756
- try {
757
- this.#maintainKv(solo);
758
- } finally {
759
- close?.();
760
- }
761
- }
762
-
763
- /** The target owns projection geometry; samplers receive individual rows. */
764
- #projectPrefill(hidden: MlxArray, caches: Cache[], completed: readonly PrefillState[]): MlxArray {
765
- for (const p of completed) {
766
- p.closePrefill?.(); p.closePrefill = undefined;
767
- p.row.closeTokenZero = p.row.req.trace?.begin("token_zero.total", { mechanism: "continuous" });
768
- }
769
- const attributed = this.#runtime.value("MLX_BUN_P2R_SYNC") === "1"
770
- ? completed.flatMap(p => p.row.req.trace ? [p.row.req.trace] : []) : [];
771
- const begin = (phase: "token_zero.forward" | "token_zero.head") => attributed.map(trace => trace.begin(phase, {
772
- mechanism: "continuous", activeBytes: activeMemory(), cacheBytes: cacheMemory(), peakBytes: peakMemory(),
773
- }));
774
- if (attributed.length) {
775
- const closes = begin("token_zero.forward");
776
- try { withResource(leaseCacheStates(caches), state => ops.evalAll([hidden, ...state])); }
777
- finally { for (const close of closes) close(); }
778
- }
779
- // Project before selecting rows: M4 quantized projection can use different
780
- // arithmetic at M=1. Tail-split preparation reaches this with N=1.
781
- const logits = this.model.logitsFromHidden(hidden);
782
- try {
783
- if (attributed.length) {
784
- const closes = begin("token_zero.head");
785
- try { ops.evalAll([logits]); } finally { for (const close of closes) close(); }
786
- }
787
- return logits;
788
- } catch (error) { logits.dispose(); throw error; }
789
- }
790
-
791
- /** Sample borrowed logits from the shared target projection. */
792
- async #completePrefill(p: PrefillState, logits: MlxArray | null): Promise<void> {
793
- if (p.continuation) {
794
- const saved = p.continuation, row = p.row;
795
- row.req.continuation!.resumeSampling(saved);
796
- const interval = row.req.continuation!.interval;
797
- this.#checkpointAt.set(row, (Math.floor(saved.generatedTokens / interval) + 1) * interval);
798
- row.firstTokenAt = performance.now();
799
- row.closeTokenZero?.(); row.closeTokenZero = undefined;
800
- this.#preparationPublishedOutput = true;
801
- for (const token of saved.cacheTokens.slice(row.req.promptIds.length)) {
802
- row.req.signal?.throwIfAborted();
803
- if (await row.req.onToken(token) === false)
804
- throw new Error("saved generation prefix triggered a terminal stop while replaying");
805
- }
806
- row.fed = saved.cacheTokens.slice(row.req.promptIds.length);
807
- row.generated = saved.generatedTokens + 1;
808
- row.sampled = saved.generatedTokens + 1;
809
- row.cachedTokens = Math.min(saved.cacheTokens.length, row.promptTokens);
810
- const stop = await this.#emit(row, saved.pendingToken);
811
- if (stop !== "continue") {
812
- this.#putOrDispose(p.solo, saved.cacheTokens, p.retain, row.cacheNamespace);
813
- p.solo = [];
814
- this.#finish(row, stop);
815
- return;
816
- }
817
- await this.#mergeJoiner(p);
818
- return;
819
- }
820
- if (!logits) throw new Error("ordinary prefill completed without logits");
821
- const forceAttribution = !!p.row.req.trace && this.#runtime.value("MLX_BUN_P2R_SYNC") === "1";
822
- const V = logits.shape[2]!;
823
- const last2 = ops.reshape(logits, [1, V]);
824
- const closeSample = forceAttribution
825
- ? p.row.req.trace!.begin("token_zero.sample", { mechanism: "continuous" })
826
- : undefined;
827
- let sampled: MlxArray;
828
- try { sampled = p.row.req.sample!(last2, 0); } finally { last2.dispose(); }
829
- // The first admission can seed the existing device-token register. Its
830
- // first decode forward then overlaps token-zero readback, just like every
831
- // later pipeline step. Grammar and explicit eager-output modes retain
832
- // their read-before-advance order.
833
- if (!this.#inners && !p.row.req.grammar && !this.#noPipeline &&
834
- this.#runtime.value("MLX_BUN_EARLY_FIRST_TOKEN") !== "1" && !forceAttribution) {
835
- let owned: MlxArray | null = sampled;
836
- try {
837
- ops.asyncEvalAll([sampled]);
838
- p.row.sampled = 1;
839
- this.#quantizeSolo(p.solo, p.row.req.trace);
840
- await this.#mergeJoiner(p);
841
- this.#pendingToks = sampled;
842
- this.#pendingReal = [true];
843
- owned = null;
844
- return;
845
- } finally { owned?.dispose(); }
846
- }
847
- const tok = this.#readToken(sampled);
848
- closeSample?.();
849
- p.row.sampled = 1;
850
- p.row.generated = 1;
851
-
852
- // Grammar (B1): the mask0 was applied inside the sample closure (the
853
- // controller is primed at compile). After reading token 0, advance the
854
- // matcher — fires the async fill for the NEXT step, overlapping the merge
855
- // below. If the grammar is already satisfied at token 0 (a 1-token grammar,
856
- // e.g. guided_choice landing on a single-token option), emit + finish("stop")
857
- // WITHOUT merging into the batch — the row never joins #running.
858
- if (p.row.req.grammar) {
859
- p.row.req.grammar.accept(tok);
860
- if (p.row.req.grammar.isTerminated) {
861
- const stop = await this.#emit(p.row, tok);
862
- // Token 0 was sampled but never fed — the caches cover exactly the
863
- // prompt, a clean prompt-only entry (put-or-dispose).
864
- this.#putOrDispose(p.solo, p.row.req.promptIds, p.retain, p.row.cacheNamespace);
865
- this.#finish(p.row, stop === "continue" ? "stop" : stop);
866
- return;
867
- }
868
- }
869
-
870
- const stop = await this.#emit(p.row, tok);
871
- if (stop !== "continue") {
872
- this.#putOrDispose(p.solo, p.row.req.promptIds, p.retain, p.row.cacheNamespace);
873
- this.#finish(p.row, stop);
874
- return;
875
- }
876
- // Default tail-split path: the caches were already converted at the head
877
- // boundary above (oracle composition: prefill ids[:-1] → convert → L=1
878
- // step-0), so this call is an idempotent no-op (converted caches match
879
- // neither serial class). It is LOAD-BEARING only under
880
- // MLX_BUN_PREFILL_TAIL_SPLIT=0 — the old serial order: token 0 sampled
881
- // from the unconverted final-chunk logits, THEN the caches convert
882
- // (before decode step 1 == before the merge).
883
- this.#quantizeSolo(p.solo, p.row.req.trace);
884
- await this.#mergeJoiner(p);
885
- return;
886
- }
887
-
888
- /** Merge a fully-prefilled joiner with the running batch, layer by layer
889
- * (re-merge; `extend` is the later refinement). Flushes the decode pipeline
890
- * first so the row set is settled and the next step starts cold. */
891
- async #mergeJoiner(p: PrefillState): Promise<void> {
892
- await this.#flushPipeline();
893
- this.#maintainKv?.prepareBatch?.(p.solo);
894
-
895
- // ADOPT, don't copy (unified-engine plan Phase 3.2): a row joining an
896
- // EMPTY batch keeps its solo caches as the batch inners — a pointer
897
- // handoff, zero bytes moved (the old path ran the full merge machinery
898
- // to produce a byte-identical [1,...] copy). The copy now happens only
899
- // when a SECOND row joins and a genuinely new layout must exist. The
900
- // prize beyond the saved copy: the lone row's caches stay SERIAL-CLASS
901
- // (KVCache / RotatingKVCache / QuantizedKVCache), so the B=1 step is
902
- // literally the serial graph, and compiled decode + prompt-cache
903
- // take/put become possible for it. The rot branch below knows how to
904
- // treat an adopted RotatingKVCache as the merge's first row.
905
- if (!this.#inners) {
906
- this.#inners = p.solo as LayerInner[]; p.solo = [];
907
- this.#fullLeftPad = [0];
908
- this.#adoptedRetain = p.retain ?? null; p.retain = undefined;
909
- this.#running.push(p.row);
910
- return;
911
- }
912
-
913
- const prev = this.#inners;
914
- const prevPad = this.#fullLeftPad;
915
- const B = this.#running.length;
916
- const newInners: LayerInner[] = [];
917
- let newFullPad = this.#fullLeftPad;
918
- for (let layer = 0; layer < this.#kinds.length; layer++) {
919
- const solo = p.solo[layer]!;
920
- const merged = ownedCacheLayout(solo);
921
- if (merged) {
922
- const previous = prev?.[layer];
923
- merged.mergeRows(previous ? [previous, solo] : [solo]);
924
- newFullPad = [...merged.leftPad];
925
- newInners.push(merged);
926
- continue;
927
- }
928
- if (this.#kinds[layer] === "owned-batch")
929
- throw new Error(`batch-capable layer ${layer} lost its cache capability`);
930
- if (this.#kinds[layer] === "ssm") {
931
- // No temporal axis, no left-pad: B-axis concat of the state slots.
932
- // mergeRows steals the solo arrays when the batch starts cold, so the
933
- // unconditional p.solo dispose below stays safe either way.
934
- newInners.push(SSMCache.mergeRows(
935
- (prev?.[layer] as SSMCache | undefined) ?? null,
936
- p.solo[layer] as SSMCache,
937
- ));
938
- continue;
939
- }
940
- if (isQuantizedKvCache(p.solo[layer])) {
941
- // Phase 3.1 — quantized full layer: same merge/extend shapes as the
942
- // bf16 branch below, over (packed, scales, biases) triples. The solo
943
- // row was converted by #quantizeSolo with the serial ops, so its
944
- // bytes already bit-match serial `--kv-quant config`; this branch
945
- // only re-arranges rows along the batch axis.
946
- const qSolo = p.solo[layer] as QuantizedKVCache;
947
- const [qk, qv] = qSolo.temporalView();
948
- const qRow = { keys: qk, values: qv };
949
- const dispose3 = (t: { packed: MlxArray; scales: MlxArray; biases: MlxArray }) => {
950
- t.packed.dispose(); t.scales.dispose(); t.biases.dispose();
951
- };
952
- const prevQ = prev?.[layer] as QuantizedKVCache | undefined;
953
- if (prevQ && this.#runtime.value("MLX_BUN_BATCH_EXTEND") !== "0") {
954
- const [k0, v0] = prevQ.temporalView();
955
- const ext = extendQuantRows(k0, v0, prevPad, qRow);
956
- dispose3(k0); dispose3(v0);
957
- newFullPad = ext.leftPad;
958
- const c = new QuantizedKVCache(qSolo.groupSize, qSolo.bits);
959
- c.restoreState(ext.keys, ext.values, ext.width);
960
- newInners.push(c);
961
- } else {
962
- const rows: { keys: typeof qk; values: typeof qv }[] = [];
963
- if (prevQ) {
964
- const [k0, v0] = prevQ.temporalView(); // [B,H,off,*]
965
- const S = k0.packed.shape[2]!;
966
- for (let b = 0; b < B; b++) {
967
- const pad = prevPad[b]!;
968
- const cutRow = (t: typeof k0): typeof k0 => ({
969
- packed: t.packed.slice([b, 0, pad, 0], [b + 1, t.packed.shape[1]!, S, t.packed.shape[3]!]),
970
- scales: t.scales.slice([b, 0, pad, 0], [b + 1, t.scales.shape[1]!, S, t.scales.shape[3]!]),
971
- biases: t.biases.slice([b, 0, pad, 0], [b + 1, t.biases.shape[1]!, S, t.biases.shape[3]!]),
972
- });
973
- rows.push({ keys: cutRow(k0), values: cutRow(v0) });
974
- }
975
- dispose3(k0); dispose3(v0);
976
- }
977
- rows.push(qRow);
978
- const merged = mergeQuantRows(rows);
979
- newFullPad = merged.leftPad;
980
- const c = new QuantizedKVCache(qSolo.groupSize, qSolo.bits);
981
- c.restoreState(merged.keys, merged.values, merged.width);
982
- newInners.push(c);
983
- for (const r of rows) { dispose3(r.keys); dispose3(r.values); }
984
- }
985
- // qRow views are disposed via the rows loop above or here for extend
986
- if (prevQ && this.#runtime.value("MLX_BUN_BATCH_EXTEND") !== "0") { dispose3(qRow.keys); dispose3(qRow.values); }
987
- else if (!prevQ) { /* disposed in the rows loop */ }
988
- continue;
989
- }
990
- // NOTE: the quantized-rotating branch below never uses this layer's
991
- // bf16 temporalView — calling it before the branch leaked the pair
992
- // (six arrays per second-row join on quantized rotating layers,
993
- // introduced in 859572d; 2026-07-07 review fix). The view is taken
994
- // AFTER the branch, on the paths that actually consume it.
995
- const soloC = p.solo[layer] as KVCache | RotatingKVCache;
996
- if (this.#kinds[layer] === "rot" && isRotatingQuantizedCache(p.solo[layer])) {
997
- // Milestone 2 — QUANTIZED rotating layer: the solo row converted at
998
- // the serial boundaries (#quantizeSolo), so its ring bytes are the
999
- // serial oracle's; this branch re-arranges temporal triples across
1000
- // the batch axis (the bf16 rot merge over triples).
1001
- const qSolo = p.solo[layer] as RotatingQuantizedKVCache;
1002
- const [qk, qv] = qSolo.temporalView();
1003
- const rows: QuantRow[] = [];
1004
- const offsets: number[] = [];
1005
- const dispose3 = (t: QuantRow) => {
1006
- t.keys.packed.dispose(); t.keys.scales.dispose(); t.keys.biases.dispose();
1007
- t.values.packed.dispose(); t.values.scales.dispose(); t.values.biases.dispose();
1008
- };
1009
- const prevC = prev?.[layer];
1010
- if (prevC && isRowBatchCache(prevC) && isRotatingQuantizedCache(prevC)) {
1011
- const batched = prevC as BatchedRotatingQuantCache;
1012
- const [k0, v0] = batched.temporalView(); // [B,H,valid,*] triples, temporal
1013
- const valid = k0.packed.shape[2]!;
1014
- for (let b = 0; b < B; b++) {
1015
- const pad = Math.max(0, batched.leftPad[b]!);
1016
- const cutRow = (t: typeof k0): typeof k0 => ({
1017
- packed: t.packed.slice([b, 0, pad, 0], [b + 1, t.packed.shape[1]!, valid, t.packed.shape[3]!]),
1018
- scales: t.scales.slice([b, 0, pad, 0], [b + 1, t.scales.shape[1]!, valid, t.scales.shape[3]!]),
1019
- biases: t.biases.slice([b, 0, pad, 0], [b + 1, t.biases.shape[1]!, valid, t.biases.shape[3]!]),
1020
- });
1021
- rows.push({ keys: cutRow(k0), values: cutRow(v0) });
1022
- offsets.push(batched.offsetArr[b]!);
1023
- }
1024
- for (const t of [k0, v0]) { t.packed.dispose(); t.scales.dispose(); t.biases.dispose(); }
1025
- } else if (isRotatingQuantizedCache(prevC)) {
1026
- // Adopted lone row (Phase 3.2 adopt): its chronological triples
1027
- // are the merge's first row, pad 0 by definition.
1028
- const [k0, v0] = prevC.temporalView();
1029
- rows.push({ keys: k0, values: v0 });
1030
- offsets.push(prevC.offset);
1031
- }
1032
- rows.push({ keys: qk, values: qv });
1033
- offsets.push(qSolo.offset);
1034
- newInners.push(BatchedRotatingQuantCache.merge(
1035
- rows, offsets, this.#rotMaxSize[layer]!, qSolo.groupSize, qSolo.bits,
1036
- ));
1037
- for (const r of rows) dispose3(r);
1038
- continue;
1039
- }
1040
- const [sk, sv] = soloC.temporalView();
1041
- const newRow: Row1 = { keys: sk, values: sv };
1042
- if (this.#kinds[layer] === "rot") {
1043
- const rows: Row1[] = [];
1044
- const offsets: number[] = [];
1045
- const prevC = prev?.[layer];
1046
- if (isRotatingPlainCache(prevC) && !isRowBatchCache(prevC)) {
1047
- // Adopted lone row (Phase 3.2): a plain serial rotating cache —
1048
- // its chronological view is the merge's first row, same as a
1049
- // fresh solo (pad 0 by definition).
1050
- const [k0, v0] = prevC.temporalView();
1051
- rows.push({ keys: k0, values: v0 });
1052
- offsets.push(prevC.offset);
1053
- }
1054
- // Route by CAPABILITY (isRowBatchCache), never by signature string,
1055
- // inside the rot branch: the running batch's ring is a row-batch
1056
- // cache whatever its storage kind. The 2026-08-22 agg×4 regression
1057
- // (443f333) came from a signature-based conjunct here silently
1058
- // dropping the running rows; since then Cache.signature() is
1059
- // REQUIRED (BatchedRotatingCache reports "kv:rotating-plain") and
1060
- // the quant family is dispatched by its own branch above.
1061
- const prevRot = prevC && isRowBatchCache(prevC)
1062
- ? prevC as unknown as BatchedRotatingCache
1063
- : undefined;
1064
- if (prevRot) {
1065
- const [k0, v0] = prevRot.temporalView(); // [B,H,valid,D]
1066
- const [, H, valid, D] = k0.shape as [number, number, number, number];
1067
- const vD = v0.shape[3]!;
1068
- for (let b = 0; b < B; b++) {
1069
- const pad = Math.max(0, prevRot.leftPad[b]!);
1070
- rows.push({
1071
- keys: k0.slice([b, 0, pad, 0], [b + 1, H, valid, D]),
1072
- values: v0.slice([b, 0, pad, 0], [b + 1, H, valid, vD]),
1073
- });
1074
- offsets.push(prevRot.offsetArr[b]!);
1075
- }
1076
- k0.dispose(); v0.dispose();
1077
- }
1078
- rows.push(newRow);
1079
- offsets.push(soloC.offset);
1080
- newInners.push(BatchedRotatingCache.merge(rows, offsets, this.#rotMaxSize[layer]!));
1081
- for (const r of rows) { r.keys.dispose(); r.values.dispose(); }
1082
- } else {
1083
- const prevFull = prev?.[layer] as KVCache | undefined;
1084
- if (prevFull && this.#runtime.value("MLX_BUN_BATCH_EXTEND") !== "0") {
1085
- // extend-join (mlx-lm BatchKVCache.extend semantics, P0): append
1086
- // the new right-justified row to the running buffer in ONE pad +
1087
- // ONE concat — no per-row extraction. Existing pads grow, never
1088
- // shrink (the re-merge below re-normalizes them instead; both are
1089
- // masked, both token-exact vs their mlx-lm protocol twin).
1090
- // MLX_BUN_BATCH_EXTEND=0 = the O(B·S) re-merge, kill switch/A-B.
1091
- const [k0, v0] = prevFull.temporalView(); // [B,H,off,D]
1092
- const ext = extendKVRows(k0, v0, prevPad, newRow);
1093
- k0.dispose(); v0.dispose();
1094
- newFullPad = ext.leftPad;
1095
- const c = new KVCache();
1096
- c.restoreState(ext.keys, ext.values, ext.width);
1097
- newInners.push(c);
1098
- newRow.keys.dispose(); newRow.values.dispose();
1099
- } else {
1100
- const rows: Row1[] = [];
1101
- if (prevFull) {
1102
- const [k0, v0] = prevFull.temporalView(); // [B,H,off,D]
1103
- const [, H, off, D] = k0.shape as [number, number, number, number];
1104
- const vD = v0.shape[3]!;
1105
- for (let b = 0; b < B; b++) {
1106
- const pad = prevPad[b]!;
1107
- rows.push({
1108
- keys: k0.slice([b, 0, pad, 0], [b + 1, H, off, D]),
1109
- values: v0.slice([b, 0, pad, 0], [b + 1, H, off, vD]),
1110
- });
1111
- }
1112
- k0.dispose(); v0.dispose();
1113
- }
1114
- rows.push(newRow);
1115
- const merged = mergeKVRows(rows);
1116
- newFullPad = merged.leftPad;
1117
- const c = new KVCache();
1118
- c.restoreState(merged.keys, merged.values, merged.width);
1119
- newInners.push(c);
1120
- for (const r of rows) { r.keys.dispose(); r.values.dispose(); }
1121
- }
1122
- }
1123
- }
1124
- if (prev) for (const c of prev) c.dispose();
1125
- // An adopted row's entry-backed arrays are gone after the prev dispose;
1126
- // run its retain now. The joiner's likewise after its solo dispose.
1127
- this.#adoptedRetain?.();
1128
- this.#adoptedRetain = null;
1129
- const completed = p.solo; p.solo = [];
1130
- const release = p.retain; p.retain = undefined;
1131
- disposeResources([...completed, { dispose: () => release?.() }]);
1132
- // Every row in a REAL merge has its KV interleaved in batched buffers —
1133
- // no longer prompt-cache put() candidates.
1134
- for (const r of this.#running) r.merged = true;
1135
- p.row.merged = true;
1136
- this.#inners = newInners;
1137
- this.#fullLeftPad = newFullPad;
1138
- this.#running.push(p.row);
1139
- }
1140
-
1141
- /** One PIPELINED batched decode step (mlx-lm GenerationBatch._step):
1142
- * 1. forward all rows from the UNREAD pending token array (or, pipeline
1143
- * cold, from the rows' last emitted tokens), sample each live row's next
1144
- * token on its [1,V] slice, asyncEval the new [B] token array;
1145
- * 2. THEN sync-read the previous step's tokens (overlapping the readback
1146
- * with this step's compute), emit them, and evict finished rows.
1147
- * Rows that finish get one extra harmless KV write from the already-built
1148
- * step; filter drops the row (mlx-lm behaves identically). Length-finished
1149
- * rows are known in advance and are NOT sampled (placeholder slot). */
1150
- async #step(): Promise<void> {
1151
- if (this.#stepTrace) {
1152
- const now = performance.now();
1153
- if (STEP_T.lastEnd) STEP_T.gap += now - STEP_T.lastEnd;
1154
- STEP_T.t0 = now;
1155
- }
1156
- const rows = this.#running;
1157
- const B = rows.length;
1158
- const inners = this.#inners!;
1159
-
1160
- // A row is live if it still needs tokens sampled; a row whose pending
1161
- // unread token is its last (sampled == maxTokens) only awaits emission.
1162
- const anyLive = rows.some((r) => r.sampled < r.req.maxTokens);
1163
- // Grammar (B1): if any row has a LIVE grammar controller (not terminated,
1164
- // still sampling), take the read-before-build shape — the matcher's
1165
- // acceptToken needs the token id as a JS number, so the previous step's
1166
- // [B] token array is read back NOW (before building the next graph),
1167
- // accept()ed per row (firing async fills that overlap the forward), then
1168
- // ready() is awaited before this step's sample. This is the serial loop's
1169
- // grammar resolution transplanted to the batch. Batches with NO live
1170
- // grammar row keep the pipelined path byte-identical (zero cost when
1171
- // unused). The trade: while a grammar row is live the batch runs
1172
- // effectively NO_PIPELINE (readback no longer overlaps GPU compute) —
1173
- // bounded by the readback (~0.1 ms) + fills (0.004–0.19 ms/row, overlapped
1174
- // with the graph build). Serial grammar pays the identical trade today.
1175
- const hasLiveGrammar = anyLive && rows.some(
1176
- (r) => r.req.grammar && !r.req.grammar.isTerminated,
1177
- );
1178
- if (hasLiveGrammar) return this.#stepGrammar();
1179
-
1180
- let nextToks: MlxArray | null = null;
1181
- let nextReal: boolean[] | null = null;
1182
- if (anyLive) {
1183
- // Fed-token accounting (prompt-cache put): a COLD step feeds each
1184
- // row's `current` (values known now, always a real emitted token); a
1185
- // pipelined step feeds the pending array, whose values are pushed at
1186
- // the read below gated on the per-slot real flags.
1187
- if (!this.#pendingToks) for (const r of rows) r.fed.push(r.current);
1188
- // Per-layer forward cache: rot layers use the persistent
1189
- // BatchedRotatingCache directly; ssm layers are already [B,...] state
1190
- // with no padding (no mask, no per-row RoPE — pass through); full
1191
- // layers get a fresh BatchedDecodeMaskCache wrapper — UNLESS no row
1192
- // has left padding. UNPADDED FAST PATH (unified-engine plan Phase 2,
1193
- // the B=1 case above all): with every leftPad 0 the wrapper's two
1194
- // jobs vanish — the padding mask (KVCache.makeMask(1) is the empty
1195
- // mask, exactly the serial loop's) and the per-row rope positions
1196
- // (every row sits at the shared scalar offset). The bare cache then
1197
- // dispatches the SAME per-step graph serial builds; the wrapper
1198
- // otherwise costs a host mask build + ~8 device nodes PER FULL LAYER
1199
- // PER TOKEN (the Phase-0 constant ~4–6 ms/step host tax at B=1).
1200
- const unpadded = this.#fullLeftPad.every((p) => p === 0);
1201
- // Compiled decode at B=1 (Phase 3.2): after adopt-don't-copy, a lone
1202
- // row's caches are SERIAL-CLASS, so the serial engine's compiled step
1203
- // replays the same C++ graph here — closing the batch lane's last
1204
- // B=1 host-tax gap (e4b's ~7%). Guards: gemma dense (constructor),
1205
- // serial-class caches (supports — a merged batch's BatchedRotating
1206
- // layers fail it), unpadded, and a uint32 pipeline register (the
1207
- // trace signature; per-row int32 samplers take the graph path).
1208
- // Grammar batches use #stepGrammar and stay on the graph path.
1209
- let lg: MlxArray | null = null;
1210
- let evalWith: MlxArray[] = [];
1211
- if (
1212
- this.#compiled && B === 1 && unpadded && this.#running[0]!.req.compiledDecode !== false &&
1213
- (!this.#pendingToks || this.#pendingToks.dtype === Dtype.uint32) &&
1214
- // A filtered-to-one BATCHED rot-quant cache subclasses the serial
1215
- // class (so supports() passes) but carries batched ring state —
1216
- // exclude it; only truly-adopted serial caches replay compiled.
1217
- !inners.some((c) => isRowBatchCache(c) && isRotatingQuantizedCache(c)) &&
1218
- CompiledDecode.supports(inners as Cache[])
1219
- ) {
1220
- let cur = this.#pendingToks;
1221
- let owned = false;
1222
- if (!cur) {
1223
- const i = ops.fromInt32([rows[0]!.current], [1]);
1224
- cur = i.astype(Dtype.uint32);
1225
- i.dispose();
1226
- owned = true;
1227
- }
1228
- try {
1229
- const r = this.#compiled.step(cur, inners as Cache[]);
1230
- lg = r.logits; // [1,1,V]
1231
- evalWith = r.evalWith;
1232
- } catch (e) {
1233
- // A failed step is transactional (see generate.ts) — safe to
1234
- // re-forward the same token on the graph path below.
1235
- this.#compiled = null;
1236
- console.warn(`batch lane: compiled decode disabled: ${e}`);
1237
- } finally {
1238
- if (owned) cur.dispose();
1239
- }
1240
- }
1241
- let fwd: Cache[] | null = null;
1242
- try {
1243
- if (!lg) {
1244
- fwd = inners.map((c) =>
1245
- isRowBatchCache(c) || isBatchableCache(c) || unpadded
1246
- ? c
1247
- : isQuantizedKvCache(c)
1248
- ? new BatchedQuantDecodeMaskCache(c, B, this.#fullLeftPad)
1249
- : new BatchedDecodeMaskCache(c, B, this.#fullLeftPad, null),
1250
- );
1251
- const ids = this.#pendingToks
1252
- ? ops.reshape(this.#pendingToks, [B, 1]) // feed the unread tokens
1253
- : ops.fromInt32(rows.map((r) => r.current), [B, 1]); // pipeline cold
1254
- const h = await this.#forwardHidden(ids, fwd);
1255
- ids.dispose();
1256
- lg = this.model.logitsFromHidden(h); // [B,1,V]
1257
- h.dispose();
1258
- }
1259
- const V = lg.shape[2]!;
1260
- // Vectorized homogeneous sampling (batching-perf-path P0): when every
1261
- // LIVE row is plain greedy, one log-softmax+argmax over [B,V] replaces
1262
- // B slice/sample/concat graphs. Per-row identical math (row-independent
1263
- // ops, same per-row shapes — argmax over log-softmax mirrors the
1264
- // closure's toLogprobs→argmax exactly, tie behavior included). Doomed
1265
- // rows get a real argmax instead of the placeholder 0 — equally
1266
- // harmless (the slot is filtered before it is ever emitted; its only
1267
- // use is one KV write on the row's own, about-to-evict row).
1268
- const vecOk =
1269
- this.#runtime.value("MLX_BUN_BATCH_VEC_SAMPLE") !== "0" &&
1270
- rows.every((r) => r.sampled >= r.req.maxTokens || r.req.plainGreedy);
1271
- // Doomed slots hold placeholders (vec path: a real argmax value,
1272
- // equally not part of the row's stream) — flag them so the fed
1273
- // accounting at the read stays per-row exact.
1274
- nextReal = rows.map((r) => r.sampled < r.req.maxTokens);
1275
- if (vecOk) {
1276
- const flat = ops.reshape(lg, [B, V]);
1277
- lg.dispose();
1278
- try { nextToks = independentGreedySampling.sample(flat); }
1279
- finally { flat.dispose(); }
1280
- for (const row of rows) if (row.sampled < row.req.maxTokens) row.sampled++;
1281
- } else {
1282
- const sampled: MlxArray[] = [];
1283
- for (let b = 0; b < B; b++) {
1284
- const row = rows[b]!;
1285
- if (row.sampled >= row.req.maxTokens) {
1286
- // Length-doomed row: evicted right after the emission below ever
1287
- // uses this slot as input — placeholder keeps the [B] alignment.
1288
- sampled.push(ops.fromInt32([0], [1]));
1289
- continue;
1290
- }
1291
- const rl = lg.slice([b, 0, 0], [b + 1, 1, V]);
1292
- const rl2 = ops.reshape(rl, [1, V]);
1293
- rl.dispose();
1294
- sampled.push(row.req.sample!(rl2, row.sampled));
1295
- row.sampled++;
1296
- rl2.dispose();
1297
- }
1298
- lg.dispose();
1299
- nextToks = ops.concatAxis(sampled, 0); // [B]
1300
- for (const t of sampled) t.dispose();
1301
- }
1302
- // dispatch; read NEXT iteration. evalWith: the compiled step's
1303
- // cache-update nodes must ride the same async_eval (generate.ts).
1304
- ops.asyncEvalAll([nextToks, ...evalWith]);
1305
- } finally {
1306
- // Free the step's RoPE arrays; do NOT dispose (full wrappers would free
1307
- // their persistent inner; rot caches persist across steps).
1308
- if (fwd) for (const c of fwd) (c as { releaseRopeArr?: () => void }).releaseRopeArr?.();
1309
- }
1310
- }
1311
- this.#steps++;
1312
- if (this.#steps % 256 === 0) clearCache(); // serial's cadence, not per-step
1313
- if (this.#stepTrace) STEP_T.build += performance.now() - STEP_T.t0;
1314
-
1315
- // Read + emit the PREVIOUS step's tokens while the new step computes.
1316
- const prev = this.#pendingToks;
1317
- const prevReal = this.#pendingReal;
1318
- this.#pendingToks = nextToks;
1319
- this.#pendingReal = nextReal;
1320
- // Kill switch / A-B lever (house style, cf. MLX_BUN_COMPILED_DECODE=0):
1321
- // MLX_BUN_BATCH_NO_PIPELINE=1 reads THIS step's tokens synchronously —
1322
- // set from process start `prev` is always null, so the flush below IS the
1323
- // whole phase 2. Same math either way (pipelining is scheduling).
1324
- if (this.#noPipeline) {
1325
- if (this.#running.some(row => row.req.continuation)) this.#captureContinuations();
1326
- await this.#flushPipeline();
1327
- return;
1328
- }
1329
- if (prev) {
1330
- const tRead = this.#stepTrace ? performance.now() : 0;
1331
- const toks = prev.toIntTokens();
1332
- prev.dispose();
1333
- // These values were the step's forward input (fed) iff a forward ran.
1334
- // Placeholder slots are excluded from `fed` — and taint their row if
1335
- // they ever fed (see Row.fedTainted; structurally unreachable today).
1336
- if (anyLive)
1337
- for (let b = 0; b < B; b++) {
1338
- if (!prevReal || prevReal[b]) rows[b]!.fed.push(toks[b]!);
1339
- else rows[b]!.fedTainted = true;
1340
- }
1341
- if (this.#stepTrace) STEP_T.read += performance.now() - tRead;
1342
- const tEmit = this.#stepTrace ? performance.now() : 0;
1343
- await this.#emitRows(toks); // also filters #pendingToks on eviction
1344
- if (this.#stepTrace) { STEP_T.emit += performance.now() - tEmit; STEP_T.n++; }
1345
- }
1346
- if (this.#running.some(row => row.req.continuation)) this.#captureContinuations();
1347
- if (this.#stepTrace) STEP_T.lastEnd = performance.now();
1348
- }
1349
-
1350
- readonly #checkpointAt = new WeakMap<Row, number>();
1351
- /** Cache extraction belongs to this existing ordinary numerical driver;
1352
- * the optional request port owns checkpoint eligibility and persistence. */
1353
- #captureContinuations(): void {
1354
- if (!this.#pendingToks || !this.#running.some(row => row.req.continuation)) return;
1355
- let pending: number[] | undefined;
1356
- const failed = new Set<number>();
1357
- for (let index = 0; index < this.#running.length; index++) {
1358
- const row = this.#running[index]!, policy = row.req.continuation;
1359
- if (!policy || row.fedTainted || row.fed.length !== row.generated ||
1360
- row.generated < (this.#checkpointAt.get(row) ?? policy.interval) ||
1361
- this.#pendingReal?.[index] === false) continue;
1362
- pending ??= this.#pendingToks.toIntTokens();
1363
- const tokens = [...row.req.promptIds, ...row.fed];
1364
- const caches = this.#running.length === 1 && !row.merged
1365
- ? cloneSingleRowState(this.#inners! as Cache[], this.#stateCodecs)
1366
- : this.#extractRowCaches(index, tokens.length);
1367
- if (!caches) continue;
1368
- try {
1369
- policy.captureOwned({ caches, cacheTokens: tokens, generatedTokens: row.generated,
1370
- pendingToken: pending[index]! });
1371
- this.#checkpointAt.set(row, (Math.floor(row.generated / policy.interval) + 1) * policy.interval);
1372
- } catch (error) { row.reject(error); failed.add(index); }
1373
- }
1374
- if (failed.size) this.#applyFilter(this.#running.flatMap((_, index) => failed.has(index) ? [] : [index]), true);
1375
- }
1376
-
1377
- /** Read out the pipeline register (if any): emit its tokens and evict
1378
- * finished rows, leaving the pipeline cold. Called before a join merges. */
1379
- async #flushPipeline(): Promise<void> {
1380
- const prev = this.#pendingToks;
1381
- if (!prev) return;
1382
- this.#pendingToks = null;
1383
- this.#pendingReal = null; // flushed values never fed — nothing to account
1384
- const toks = prev.toIntTokens();
1385
- prev.dispose();
1386
- // Grammar rows: the flushed tokens are EMITTED below, so their matchers
1387
- // must advance here — #stepGrammar's accept only covers tokens it reads
1388
- // from a live pending array, and after this flush it cold-starts (no
1389
- // accept). Skipping this left the matcher one token behind its stream on
1390
- // every mid-decode join → one-step-stale masks → invalid output (found
1391
- // by the feature-matrix conformance gate, 2026-07-03; the fill fired
1392
- // here is awaited by the next #stepGrammar's ready()).
1393
- for (let b = 0; b < this.#running.length && b < toks.length; b++) {
1394
- const g = this.#running[b]!.req.grammar;
1395
- if (g && !g.isTerminated) g.accept(toks[b]!);
1396
- }
1397
- await this.#emitRows(toks);
1398
- }
1399
-
1400
- /** The read-before-build decode step for batches with ≥1 live grammar row
1401
- * (B1). Mirrors the serial loop's grammar resolution: read the previous
1402
- * step's [B] tokens NOW (acceptToken needs JS numbers), accept() per row
1403
- * (fires async fills), build the forward graph (fills overlap), await
1404
- * ready(), sample per live row (the closure applies applyMask), then emit
1405
- * the values read in step 1 — no second readback. Terminated grammar rows
1406
- * keep their [B] slot through the forward (placeholder, not sampled) and
1407
- * finish("stop") in #emitRows. On a cold start (first step after prefill)
1408
- * there is no pending array to read; the prefill already accepted token 0
1409
- * and fired the fill, so we just await ready() + sample. */
1410
- async #stepGrammar(): Promise<void> {
1411
- const rows = this.#running;
1412
- const B = rows.length;
1413
- const inners = this.#inners!;
1414
-
1415
- // (1) Read the pending [B] token array (host copy for accept). The device
1416
- // array is kept for the forward input below; disposed after sampling.
1417
- // Cold start: pendingToks null → prevVals empty (prefill handled tok0).
1418
- const prev = this.#pendingToks;
1419
- const prevVals: number[] =
1420
- prev ? prev.toIntTokens() : [];
1421
- if (this.#runtime.value("MLX_BUN_GRAMMAR_DEBUG") === "1")
1422
- console.log(`[sg] B=${B} prevVals=${JSON.stringify(prevVals)} current=${JSON.stringify(rows.map((r) => r.current))} sampled=${JSON.stringify(rows.map((r) => r.sampled))}`);
1423
-
1424
- // (2) accept() per live grammar row — fires that row's async bitmask fill.
1425
- for (let b = 0; b < B && prevVals.length; b++) {
1426
- const g = rows[b]!.req.grammar;
1427
- if (g && !g.isTerminated) g.accept(prevVals[b]!);
1428
- }
1429
-
1430
- let nextToks: MlxArray | null = null;
1431
- let nextReal: boolean[] | null = null;
1432
- const anyLive = rows.some((r) => r.sampled < r.req.maxTokens);
1433
- if (anyLive) {
1434
- // Fed-token accounting (prompt-cache put) — mirror of #step's read:
1435
- // real slots push, a placeholder that fed taints its row.
1436
- const prevReal = this.#pendingReal;
1437
- if (prev)
1438
- for (let b = 0; b < B; b++) {
1439
- if (!prevReal || prevReal[b]) rows[b]!.fed.push(prevVals[b]!);
1440
- else rows[b]!.fedTainted = true;
1441
- }
1442
- else for (const r of rows) r.fed.push(r.current);
1443
- // Unpadded fast path — same rule as #step (bare caches == serial graph).
1444
- const unpadded = this.#fullLeftPad.every((p) => p === 0);
1445
- const fwd: Cache[] = inners.map((c) =>
1446
- isRowBatchCache(c) || isBatchableCache(c) || unpadded
1447
- ? c
1448
- : isQuantizedKvCache(c)
1449
- ? new BatchedQuantDecodeMaskCache(c, B, this.#fullLeftPad)
1450
- : new BatchedDecodeMaskCache(c, B, this.#fullLeftPad, null),
1451
- );
1452
- try {
1453
- // (3) Build the forward graph (host-side; the fills overlap it).
1454
- const ids = prev
1455
- ? ops.reshape(prev, [B, 1]) // feed the unread tokens (device array)
1456
- : ops.fromInt32(rows.map((r) => r.current), [B, 1]); // pipeline cold
1457
- const h = await this.#forwardHidden(ids, fwd);
1458
- ids.dispose();
1459
- const lg = this.model.logitsFromHidden(h); // [B,1,V]
1460
- h.dispose();
1461
- const V = lg.shape[2]!;
1462
-
1463
- // (4) await ready() on every live grammar row — the fills fired in (2)
1464
- // overlapped the graph build above. Usually already resolved.
1465
- const liveGrammar = rows.filter(
1466
- (r) => r.req.grammar && !r.req.grammar.isTerminated,
1467
- );
1468
- if (liveGrammar.length)
1469
- await Promise.all(liveGrammar.map((r) => r.req.grammar!.ready()));
1470
-
1471
- // (5) Sample per live row (the closure applies applyMask after the
1472
- // logits processors). Terminated grammar rows + length-doomed rows
1473
- // take a placeholder (one harmless KV write, then evicted).
1474
- const sampled: MlxArray[] = [];
1475
- nextReal = rows.map(
1476
- (r) => r.sampled < r.req.maxTokens && !r.req.grammar?.isTerminated,
1477
- );
1478
- for (let b = 0; b < B; b++) {
1479
- const row = rows[b]!;
1480
- if (
1481
- row.sampled >= row.req.maxTokens ||
1482
- row.req.grammar?.isTerminated
1483
- ) {
1484
- sampled.push(ops.fromInt32([0], [1]));
1485
- continue;
1486
- }
1487
- const rl = lg.slice([b, 0, 0], [b + 1, 1, V]);
1488
- const rl2 = ops.reshape(rl, [1, V]);
1489
- rl.dispose();
1490
- sampled.push(row.req.sample!(rl2, row.sampled));
1491
- row.sampled++;
1492
- rl2.dispose();
1493
- }
1494
- lg.dispose();
1495
- nextToks = ops.concatAxis(sampled, 0); // [B]
1496
- for (const t of sampled) t.dispose();
1497
- ops.asyncEvalAll([nextToks]);
1498
- } finally {
1499
- for (const c of fwd)
1500
- (c as { releaseRopeArr?: () => void }).releaseRopeArr?.();
1501
- }
1502
- }
1503
- this.#steps++;
1504
- if (this.#steps % 256 === 0) clearCache();
1505
-
1506
- // The device array `prev` has now fed the forward + been read for accept;
1507
- // dispose it and install the new pending array. On cold start prev is null.
1508
- prev?.dispose();
1509
- this.#pendingToks = nextToks;
1510
- this.#pendingReal = nextReal;
1511
-
1512
- // (6) Emit the values read in (1) — no second readback. Terminated grammar
1513
- // rows finish("stop") via #emit's isTerminated check; the filter evicts.
1514
- // Cold start: prevVals empty (prefill emitted tok0) → nothing to emit.
1515
- if (prevVals.length) await this.#emitRows(prevVals);
1516
- if (this.#running.some(row => row.req.continuation)) this.#captureContinuations();
1517
- }
1518
-
1519
- /** Emit one read-back token per running row; evict finished rows. A row's
1520
- * onToken throwing rejects THAT row and evicts it — siblings continue. */
1521
- async #emitRows(toks: number[]): Promise<void> {
1522
- const rows = this.#running;
1523
- const B = rows.length;
1524
- const keep: number[] = [];
1525
- const done: { b: number; row: Row }[] = []; // clean finishes (stop/length)
1526
- for (let b = 0; b < B; b++) {
1527
- const row = rows[b]!;
1528
- row.generated++;
1529
- let disp: "continue" | "stop" | "length";
1530
- try {
1531
- disp = await this.#emit(row, toks[b]!);
1532
- } catch (e) {
1533
- row.reject(e); // containment: this row only (mlx-lm `remove`)
1534
- row.merged = true; // poison: a rejected row is never put() back
1535
- row.fedTainted = true;
1536
- continue; // not kept → evicted by the filter below
1537
- }
1538
- if (disp === "continue") keep.push(b);
1539
- else {
1540
- done.push({ b, row });
1541
- this.#finish(row, disp);
1542
- }
1543
- }
1544
- if (keep.length < B) {
1545
- // Per-row prompt-cache extraction (mlx-lm server.py:864-880 →
1546
- // BatchGenerator.extract_cache): a MERGED row's KV lives interleaved
1547
- // in the batched inners, so it is pulled out into fresh serial caches
1548
- // BEFORE filter() mutates them. Never-merged lone rows skip this —
1549
- // #applyFilter's keep=[] path put()s their adopted caches zero-copy.
1550
- // Rejected rows aren't in `done`; the whole-batch error path calls
1551
- // #applyFilter(dropOnly) directly and never reaches here.
1552
- for (const { b, row } of done) this.#extractAndPut(b, row);
1553
- this.#applyFilter(keep);
1554
- }
1555
- }
1556
-
1557
- /** Account one sampled token for a row. Mirrors generate(): EOS terminates
1558
- * WITHOUT an onToken call; otherwise onToken(token) runs and `false` halts;
1559
- * reaching maxTokens ends with "length". Advances row.current on continue. */
1560
- async #emit(row: Row, token: number, logprobs?: import("../../generate").TokenLogprobs): Promise<"continue" | "stop" | "length"> {
1561
- row.req.signal?.throwIfAborted();
1562
- this.#firstOutput(row);
1563
- if (row.generated === 1) clearCache();
1564
- if (row.req.eosTokenIds.includes(token)) return "stop";
1565
- const cont = await row.req.onToken(token, logprobs);
1566
- if (cont === false) return "stop";
1567
- // Grammar termination: the matcher is satisfied (e.g. closing `}` accepted).
1568
- // The final token has been delivered via onToken above; halt with "stop" so
1569
- // the row finishes + evicts rather than sampling into an all--inf mask.
1570
- if (row.req.grammar?.isTerminated) return "stop";
1571
- if (row.generated >= row.req.maxTokens) return "length";
1572
- row.current = token;
1573
- return "continue";
1574
- }
1575
-
1576
- #firstOutput(row: Row): void {
1577
- if (row.generated === 1) {
1578
- if (this.#prefill?.rows.includes(row)) this.#preparationPublishedOutput = true;
1579
- row.firstTokenAt = performance.now();
1580
- row.closeTokenZero?.();
1581
- row.closeTokenZero = undefined;
1582
- }
1583
- }
1584
-
1585
- #finish(row: Row, reason: "stop" | "length"): void {
1586
- row.req.continuation?.complete();
1587
- const now = performance.now();
1588
- const first = row.firstTokenAt || now;
1589
- row.resolve({
1590
- ...(row.spec ? { spec: row.spec } : {}),
1591
- promptTokens: row.promptTokens,
1592
- generatedTokens: row.generated,
1593
- cachedTokens: row.cachedTokens,
1594
- finishReason: reason,
1595
- prefillMs: row.admittedAt ? first - row.admittedAt : 0,
1596
- decodeMs: row.firstTokenAt ? now - row.firstTokenAt : 0,
1597
- });
1598
- }
1599
-
1600
- /** Finish-time disposition of serial-class caches covering exactly
1601
- * `tokens`: put() into the prompt cache when the hook is present and the
1602
- * offset lines up (defensive — a mismatch means the accounting is wrong
1603
- * and the entry would corrupt future hits), else dispose. `retain` rides
1604
- * along per the PromptCacheEntry contract (runs after dispose). */
1605
- #putOrDispose(caches: Cache[], tokens: number[], retain?: () => void, namespace = ""): void {
1606
- if (this.#promptCache) {
1607
- // A never-merged row can still own a row layout. Persistence receives
1608
- // its existing serial representation, just like merged-row retirement.
1609
- const extracted: Cache[] = [], replaced: Cache[] = [];
1610
- let persistent: Cache[];
1611
- try {
1612
- persistent = caches.map(cache => {
1613
- if (!isBatchableCache(cache) || cache.batchSize !== 1) return cache;
1614
- const row = cache.extractRow(0);
1615
- extracted.push(row); replaced.push(cache);
1616
- return row;
1617
- });
1618
- } catch (error) { disposeResources(extracted); throw error; }
1619
- try { disposeResources(replaced); }
1620
- catch (error) { disposeResources(extracted); throw error; }
1621
- caches = persistent;
1622
- const withOff = caches.find(
1623
- (c) => typeof (c as { offset?: unknown }).offset === "number",
1624
- ) as { offset: number } | undefined;
1625
- if (withOff && withOff.offset === tokens.length) {
1626
- this.#promptCache.put(tokens, caches, namespace, retain);
1627
- return;
1628
- }
1629
- }
1630
- for (const c of caches) c.dispose();
1631
- retain?.();
1632
- }
1633
-
1634
- /** Extract a finishing MERGED row's KV into fresh serial caches and put()
1635
- * them keyed by [promptIds + fed] — the batch-lane mirror of mlx-lm
1636
- * server.py:872 (extract_cache → prompt_cache.insert_cache). Gates:
1637
- * promptTokens >= 256 (the boundary-snapshot substantiality gate,
1638
- * server.ts) and an exact coverage key (!fedTainted). Refusal
1639
- * (#extractRowCaches null) just disposes-by-omission — the row's KV dies
1640
- * with the filter, exactly the pre-extraction behavior. */
1641
- #extractAndPut(b: number, row: Row): void {
1642
- if (!this.#promptCache || !row.merged || row.fedTainted) return;
1643
- if (row.promptTokens < 256) return;
1644
- const tokens = [...row.req.promptIds, ...row.fed];
1645
- const caches = this.#extractRowCaches(b, tokens.length);
1646
- if (!caches) return;
1647
- // Materialize the owned copies without stalling the in-flight step (the
1648
- // slices depend on this step's KV writes): async — the batched source
1649
- // buffers free once the copies land, instead of being pinned by a lazy
1650
- // graph inside an idle cache entry.
1651
- withResource(leaseCacheStates(caches), state => ops.asyncEvalAll([...state]));
1652
- this.#putOrDispose(caches, tokens, undefined, row.cacheNamespace);
1653
- }
1654
-
1655
- /** Row `b` of every layer as OWNED serial-class caches, or null when a
1656
- * layer kind can't be extracted (then the caller drops the row's KV as
1657
- * before). Bit-exactness: merge/extend/filter/decode are byte-preserving
1658
- * per row (tests/batched-decode-parity, tests/batched-rotating,
1659
- * tests/batched-rotating-quant) and each extract is a pure slice+copy of
1660
- * those bytes (tests/batched-extract), so an extracted row's bytes ==
1661
- * the solo run's. */
1662
- #extractRowCaches(b: number, expectTokens: number): Cache[] | null {
1663
- const out: Cache[] = [];
1664
- for (const inner of this.#inners!) {
1665
- let c: Cache | null;
1666
- if (isBatchableCache(inner)) c = inner.extractRow(b);
1667
- else if (isRowBatchCache(inner) && cacheSignature(inner) === "ssm")
1668
- // Coverage gate: recurrent state is UNTRIMMABLE, so an entry is only
1669
- // valid when the row's own advance count equals the [promptIds+fed]
1670
- // key EXACTLY (a mismatched entry would silently corrupt every future
1671
- // exact-hit). Defensive — a miss here means the fed accounting broke.
1672
- c = (inner as SSMCache).conv && (inner as SSMCache).rowOffset(b) === expectTokens
1673
- ? inner.extractRow(b)
1674
- : null;
1675
- else if (isRowBatchCache(inner)) c = inner.extractRow(b);
1676
- else if (
1677
- isRotatingQuantizedCache(inner) || // adopted serial state never
1678
- isRotatingPlainCache(inner) // coexists with a merged row (defensive)
1679
- )
1680
- c = null;
1681
- else if (isQuantizedKvCache(inner))
1682
- c = inner.keys ? extractQuantRow(inner, this.#fullLeftPad[b]!, b) : null;
1683
- else if (isPlainKvCache(inner))
1684
- c = inner.keys ? extractKVRow(inner, this.#fullLeftPad[b]!, b) : null;
1685
- else c = null;
1686
- if (!c) {
1687
- for (const d of out) d.dispose();
1688
- return null;
1689
- }
1690
- out.push(c);
1691
- }
1692
- return out;
1693
- }
1694
-
1695
- /** Evict rows not in `keep` (sorted ascending) from the batched KV and the
1696
- * pipeline register. */
1697
- #applyFilter(keep: number[], dropOnly = false): void {
1698
- if (this.#method) {
1699
- this.#method.filterRows(keep, dropOnly);
1700
- this.#running = keep.map(row => this.#running[row]!);
1701
- return;
1702
- }
1703
- const inners = this.#inners!;
1704
- if (keep.length === 0) {
1705
- // Prompt-cache put (Phase 3.2): a lone NEVER-MERGED row's inners are
1706
- // its adopted serial-class caches, covering exactly prompt+fed — hand
1707
- // them back to the cache instead of disposing. dropOnly (the batch-
1708
- // drop error path) and poisoned rows dispose as before; MERGED rows'
1709
- // KV was already extracted per row in #emitRows (owned copies), so
1710
- // disposing the batched inners here is safe either way.
1711
- const solo =
1712
- !dropOnly && this.#running.length === 1 && !this.#running[0]!.merged
1713
- ? this.#running[0]!
1714
- : null;
1715
- if (solo) {
1716
- this.#putOrDispose(
1717
- inners as Cache[],
1718
- [...solo.req.promptIds, ...solo.fed],
1719
- this.#adoptedRetain ?? undefined,
1720
- solo.cacheNamespace,
1721
- );
1722
- } else {
1723
- for (const c of inners) c.dispose();
1724
- this.#adoptedRetain?.();
1725
- }
1726
- this.#adoptedRetain = null;
1727
- this.#inners = null;
1728
- this.#fullLeftPad = [];
1729
- this.#running = [];
1730
- this.#pendingToks?.dispose();
1731
- this.#pendingToks = null;
1732
- this.#pendingReal = null;
1733
- return;
1734
- }
1735
- const keptFullPad = keep.map((i) => this.#fullLeftPad[i]!);
1736
- // mlx-lm BatchKVCache.filter removes padding shared by all survivors.
1737
- // Full-attention width and padding move together; each row's absolute
1738
- // RoPE position stays unchanged. Rotating caches keep their own layout.
1739
- const trimFull = this.#kinds.includes("full") ? Math.min(...keptFullPad) : 0;
1740
- const out: LayerInner[] = [];
1741
- for (const inner of inners) {
1742
- if (isBatchableCache(inner)) {
1743
- inner.filterRows(keep);
1744
- out.push(inner);
1745
- } else if (isRowBatchCache(inner)) {
1746
- inner.filterRows(keep);
1747
- out.push(inner);
1748
- } else if (isRotatingQuantizedCache(inner) || isRotatingPlainCache(inner)) {
1749
- // Adopted lone-row state exists only at B=1, where the only filter
1750
- // is the keep=[] dispose-all handled above — unreachable.
1751
- throw new Error("applyFilter: adopted serial rotating cache cannot be row-filtered");
1752
- } else if (isQuantizedKvCache(inner)) {
1753
- const [k0, v0] = inner.temporalView();
1754
- const f = filterQuantRows(k0, v0, keep, trimFull);
1755
- for (const t of [k0, v0]) { t.packed.dispose(); t.scales.dispose(); t.biases.dispose(); }
1756
- const c = new QuantizedKVCache(inner.groupSize, inner.bits);
1757
- c.restoreState(f.keys, f.values, inner.offset - trimFull);
1758
- out.push(c);
1759
- inner.dispose();
1760
- } else if (isPlainKvCache(inner)) {
1761
- const [k0, v0] = inner.temporalView();
1762
- const f = filterKVRows(k0, v0, keep, trimFull);
1763
- k0.dispose(); v0.dispose();
1764
- const c = new KVCache();
1765
- c.restoreState(f.keys, f.values, inner.offset - trimFull);
1766
- out.push(c);
1767
- inner.dispose();
1768
- } else {
1769
- throw new Error(`applyFilter: unsupported cache signature ${cacheSignature(inner)}`);
1770
- }
1771
- }
1772
- this.#inners = out;
1773
- this.#fullLeftPad = keptFullPad.map((padding) => padding - trimFull);
1774
- this.#running = keep.map((i) => this.#running[i]!);
1775
- if (this.#pendingToks) {
1776
- const idx = ops.fromInt32(keep, [keep.length]);
1777
- const next = ops.takeAxis(this.#pendingToks, idx, 0);
1778
- idx.dispose();
1779
- this.#pendingToks.dispose();
1780
- this.#pendingToks = next;
1781
- }
1782
- if (this.#pendingReal) this.#pendingReal = keep.map((i) => this.#pendingReal![i]!);
1783
- }
1784
-
1785
- #readToken(t: MlxArray): number {
1786
- const v = t.toIntTokens()[0]!;
1787
- t.dispose();
1788
- return v;
1789
- }
1790
- }