mlx-bun 0.0.13 → 0.3.0

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