mlx-bun 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (640) hide show
  1. package/README.md +1449 -109
  2. package/THIRD_PARTY_NOTICES.md +882 -0
  3. package/bin/mlx-bun.convert.mjs +4 -0
  4. package/bin/mlx-bun.fuse.mjs +4 -0
  5. package/bin/mlx-bun.generate.mjs +4 -0
  6. package/bin/mlx-bun.lora.mjs +4 -0
  7. package/bin/mlx-bun.mjs +13 -21
  8. package/bin/mlx-bun.server.mjs +4 -0
  9. package/bin/mlx-bun.upload.mjs +4 -0
  10. package/dist/web/app.js +9584 -0
  11. package/package.json +50 -53
  12. package/src/cli/ane-install.ts +76 -0
  13. package/src/cli/args.ts +179 -0
  14. package/src/cli/engine-entry.ts +68 -0
  15. package/src/cli/inference.ts +214 -0
  16. package/src/cli/job-entry.ts +97 -0
  17. package/src/cli/library-host.ts +117 -0
  18. package/src/cli/main.ts +57 -0
  19. package/src/cli/memory-engine.ts +163 -0
  20. package/src/cli/memory.ts +36 -0
  21. package/src/cli/mlx-lm-aliases.ts +309 -0
  22. package/src/cli/model-choice.ts +33 -0
  23. package/src/cli/model-selection.ts +84 -0
  24. package/src/cli/module-host.ts +11 -0
  25. package/src/cli/module-verbs.ts +50 -0
  26. package/src/cli/numerical-policy.ts +12 -0
  27. package/src/cli/perplexity.ts +89 -0
  28. package/src/cli/serve-host.ts +423 -0
  29. package/src/cli/serve-isolated.ts +217 -0
  30. package/src/cli/serve-options.ts +106 -0
  31. package/src/cli/serve-state.ts +205 -0
  32. package/src/cli/serve.ts +500 -0
  33. package/src/cli/served-model-host.ts +102 -0
  34. package/src/cli/server-entry.ts +148 -0
  35. package/src/cli/serving-unit.ts +177 -0
  36. package/src/{tui.ts → cli/terminal.ts} +13 -8
  37. package/src/cli/worker-adapters.ts +34 -0
  38. package/src/cli/worker-entry.ts +272 -0
  39. package/src/cli/worker-unit.ts +179 -0
  40. package/src/engine/adapter-operation.ts +26 -0
  41. package/src/engine/cache-services.ts +114 -0
  42. package/src/engine/completion.ts +39 -0
  43. package/src/engine/generation-gateway.ts +358 -0
  44. package/src/engine/index.ts +59 -0
  45. package/src/engine/kv-budget.ts +120 -0
  46. package/src/engine/media-preparation.ts +232 -0
  47. package/src/engine/model-binding.ts +24 -0
  48. package/src/engine/model-host.ts +513 -0
  49. package/src/engine/model-serving.ts +89 -0
  50. package/src/{serve → engine}/preparation.ts +7 -5
  51. package/src/{serve → engine}/session-completion-engine.ts +6 -6
  52. package/src/engine/telemetry.ts +109 -0
  53. package/src/hub/downloads.ts +116 -0
  54. package/src/jobs/db.ts +16 -7
  55. package/src/jobs/events.ts +29 -0
  56. package/src/jobs/executable.ts +5 -0
  57. package/src/jobs/host.ts +51 -0
  58. package/src/jobs/in-process.ts +55 -0
  59. package/src/{contracts/jobs.ts → jobs/protocol.ts} +7 -9
  60. package/src/jobs/runner.ts +150 -231
  61. package/src/jobs/service.ts +75 -0
  62. package/src/jobs/sse.ts +59 -23
  63. package/src/jobs/worker-memory.ts +46 -0
  64. package/src/jobs/worker-process.ts +163 -0
  65. package/src/jobs/worker-supervisor.ts +258 -0
  66. package/src/modules.ts +58 -0
  67. package/src/publishing/catalog-hub.ts +18 -0
  68. package/src/publishing/credentials.ts +31 -0
  69. package/src/publishing/upload.ts +37 -0
  70. package/src/residency/leased-adapters.ts +21 -0
  71. package/src/residency/local-records.ts +16 -0
  72. package/src/residency/model-residency.ts +405 -0
  73. package/src/residency/record-index.ts +28 -0
  74. package/src/residency/resident-estimate.ts +50 -0
  75. package/src/{anthropic.ts → server/anthropic.ts} +3 -81
  76. package/src/server/cache-routes.ts +36 -0
  77. package/src/{serve → server}/chat-request.ts +10 -10
  78. package/src/{serve → server}/chat-stage.ts +14 -14
  79. package/src/{client.ts → server/client.ts} +28 -2
  80. package/src/{serve → server}/completion-executor.ts +33 -41
  81. package/src/server/decision-body.ts +55 -0
  82. package/src/server/decision-routes.ts +134 -0
  83. package/src/server/decision-wire.ts +228 -0
  84. package/src/{serve → server}/discovery-routes.ts +25 -82
  85. package/src/{serve → server}/http.ts +25 -13
  86. package/src/{serve → server}/inference-request.ts +5 -5
  87. package/src/server/job-routes.ts +20 -0
  88. package/src/server/media-prompt.ts +63 -0
  89. package/src/server/memory-completion-client.ts +46 -0
  90. package/src/server/model-routes.ts +192 -0
  91. package/src/{serve → server}/openai-wire.ts +3 -2
  92. package/src/{serve → server}/pipeline.ts +1 -1
  93. package/src/server/prompt-builder.ts +13 -0
  94. package/src/server/prompt-contracts.ts +17 -0
  95. package/src/server/proxy-routes.ts +187 -0
  96. package/src/server/publishing-routes.ts +41 -0
  97. package/src/{serve → server}/request-plan.ts +6 -8
  98. package/src/{serve → server}/request-prep.ts +47 -50
  99. package/src/{serve → server}/responses-client.ts +30 -13
  100. package/src/{responses.ts → server/responses.ts} +12 -93
  101. package/src/server/routes.ts +205 -0
  102. package/src/server/start.ts +72 -0
  103. package/src/server/status-routes.ts +108 -0
  104. package/src/{serve → server}/text-completion-stage.ts +25 -4
  105. package/src/server/text-prompt.ts +12 -0
  106. package/src/{serve → server}/token-streams.ts +36 -38
  107. package/src/server/worker-routes.ts +311 -0
  108. package/src/storage/paths.ts +61 -0
  109. package/src/web/assets.ts +37 -0
  110. package/src/web/{src → browser}/api.ts +5 -23
  111. package/src/web/browser/chat-host.ts +17 -0
  112. package/src/web/browser/installed-panels.ts +6 -0
  113. package/src/web/browser/main.ts +55 -0
  114. package/src/web/browser/markdown.ts +279 -0
  115. package/src/web/browser/memory-panel.ts +9 -0
  116. package/src/web/browser/palette.ts +64 -0
  117. package/src/web/browser/protocol.ts +13 -0
  118. package/src/web/browser/shell.ts +467 -0
  119. package/src/web/{src → browser}/status.ts +32 -36
  120. package/src/web/build.ts +51 -0
  121. package/src/web/public/app.html +1054 -0
  122. package/src/web/{sw.js → public/sw.js} +4 -3
  123. package/src/web/{vendor → public/vendor}/hljs-theme.css +2 -2
  124. package/src/web/{vendor → public/vendor}/hljs.js +2 -2
  125. package/THIRD_PARTY_LICENSES.md +0 -51
  126. package/docs/README.md +0 -107
  127. package/docs/archive/hlg-sampling.md +0 -350
  128. package/docs/archive/investigations/audio-input-plan.md +0 -356
  129. package/docs/archive/investigations/benchmark-ledger-through-v0.4.0.md +0 -3617
  130. package/docs/archive/investigations/chunk-finetune-experiment.md +0 -84
  131. package/docs/archive/investigations/colibri-glm52-port.md +0 -1486
  132. package/docs/archive/investigations/colibri-oracle-pin.md +0 -1284
  133. package/docs/archive/investigations/curve-bisector-routing.md +0 -123
  134. package/docs/archive/investigations/decode-roofline-lookagain.md +0 -348
  135. package/docs/archive/investigations/diffusion-gemma-port.md +0 -602
  136. package/docs/archive/investigations/dspark-handoff.md +0 -224
  137. package/docs/archive/investigations/expert-offload-single-user-moe.md +0 -292
  138. package/docs/archive/investigations/faithful-l1-consolidation.md +0 -310
  139. package/docs/archive/investigations/hlg-sampling-investigation.md +0 -970
  140. package/docs/archive/investigations/indexshare-performance-spike.md +0 -357
  141. package/docs/archive/investigations/kernel-perf-review-2026-07.md +0 -171
  142. package/docs/archive/investigations/lab-build-journal.md +0 -157
  143. package/docs/archive/investigations/minicpm5-decode-megakernel.md +0 -489
  144. package/docs/archive/investigations/openjarvis-fit.md +0 -198
  145. package/docs/archive/investigations/openwiki-evaluation.md +0 -249
  146. package/docs/archive/investigations/optimization_plan.md +0 -346
  147. package/docs/archive/investigations/orpo-base-uf-experiment-and-directions.md +0 -120
  148. package/docs/archive/investigations/orpo-flash-cce-pin-leak.md +0 -167
  149. package/docs/archive/investigations/orpo-uf-testing-handoff.md +0 -126
  150. package/docs/archive/investigations/pareto-specialized-runtime-findings.md +0 -92
  151. package/docs/archive/investigations/pi-builtin-investigation.md +0 -308
  152. package/docs/archive/investigations/pre-colibri-stabilization.md +0 -329
  153. package/docs/archive/investigations/qwen38-27b-campaign-log.md +0 -1092
  154. package/docs/archive/investigations/segmented-backward-handoff.md +0 -148
  155. package/docs/archive/investigations/starter-model-port-handoff.md +0 -342
  156. package/docs/archive/investigations/steel-flash-cce-handoff.md +0 -489
  157. package/docs/archive/investigations/the-dreaming-handoff.md +0 -141
  158. package/docs/archive/investigations/trainer-validation-experiment.md +0 -173
  159. package/docs/archive/planning/chat-ui-vision-memory-first.md +0 -199
  160. package/docs/archive/planning/chat-ui-vision.md +0 -50
  161. package/docs/archive/planning/chunk-task-roadmap.md +0 -77
  162. package/docs/archive/planning/curve-sampler-research-plan.md +0 -331
  163. package/docs/archive/planning/journal.md +0 -316
  164. package/docs/archive/planning/memory-docs-and-dag-plan.md +0 -194
  165. package/docs/archive/planning/pi-integration-review.md +0 -178
  166. package/docs/archive/planning/release-notes-v0.0.10.md +0 -57
  167. package/docs/archive/planning/release-notes-v0.0.11.md +0 -239
  168. package/docs/archive/planning/release-notes-v0.0.12.md +0 -80
  169. package/docs/archive/planning/release-notes-v0.0.13.md +0 -77
  170. package/docs/archive/planning/release-notes-v0.0.9.md +0 -122
  171. package/docs/archive/planning/release-notes-v0.2.0.md +0 -49
  172. package/docs/archive/planning/release-notes-v0.3.0.md +0 -35
  173. package/docs/archive/planning/release-notes-v0.4.0.md +0 -45
  174. package/docs/archive/planning/release-notes-v0.5.0.md +0 -37
  175. package/docs/archive/planning/web-ui-pass-plan.md +0 -213
  176. package/docs/archive/planning/website-readme-pass-plan.md +0 -224
  177. package/docs/design/batching.md +0 -2054
  178. package/docs/design/decode-speed-program.md +0 -2404
  179. package/docs/design/dreaming-nightly-pipeline.md +0 -684
  180. package/docs/design/generic-model-support.md +0 -821
  181. package/docs/design/kv-cache.md +0 -993
  182. package/docs/design/orpo-training.md +0 -680
  183. package/docs/design/speculative-decoding.md +0 -2129
  184. package/docs/design/turboquant.md +0 -2225
  185. package/docs/design/unified-engine-frontier-plan.md +0 -1987
  186. package/docs/design/web-chat-redesign.md +0 -695
  187. package/docs/planning/PRODUCT_ROADMAP.md +0 -593
  188. package/docs/planning/ResearchTopics.md +0 -119
  189. package/docs/planning/public-readiness-handoff.md +0 -244
  190. package/docs/planning/public-readiness.md +0 -149
  191. package/docs/planning/video-series.md +0 -421
  192. package/docs/reference/benchmarks.md +0 -3587
  193. package/docs/reference/cli.md +0 -646
  194. package/docs/reference/distribution.md +0 -380
  195. package/docs/reference/environment.md +0 -494
  196. package/docs/reference/glossary.md +0 -39
  197. package/docs/reference/library-api.md +0 -688
  198. package/docs/reference/memory.md +0 -260
  199. package/docs/reference/models.md +0 -346
  200. package/docs/reference/server-api.md +0 -1945
  201. package/docs/reference/server-config.md +0 -973
  202. package/docs/reference/training.md +0 -462
  203. package/docs/reference/troubleshooting.md +0 -158
  204. package/src/admission-plan.ts +0 -18
  205. package/src/audio/audiotoolbox.ts +0 -112
  206. package/src/audio/conformer.ts +0 -655
  207. package/src/audio/decode.ts +0 -133
  208. package/src/audio/features.ts +0 -202
  209. package/src/audio/mic-capture.ts +0 -98
  210. package/src/audio/silero-vad.ts +0 -379
  211. package/src/audio/transcode.ts +0 -67
  212. package/src/audio/whisper-decode.ts +0 -774
  213. package/src/audio/whisper-fast.ts +0 -732
  214. package/src/audio/whisper-format.ts +0 -73
  215. package/src/audio/whisper-mel.ts +0 -185
  216. package/src/audio/whisper-timing.ts +0 -274
  217. package/src/audio/whisper-tokenizer.ts +0 -239
  218. package/src/audio/whisper-transcribe.ts +0 -410
  219. package/src/backends/mlx/assistant-target.ts +0 -46
  220. package/src/backends/mlx/autoregressive-draft-rows.ts +0 -120
  221. package/src/backends/mlx/autoregressive.ts +0 -129
  222. package/src/backends/mlx/batch-group.ts +0 -1874
  223. package/src/backends/mlx/cache-attachment.ts +0 -67
  224. package/src/backends/mlx/cache-layout.ts +0 -31
  225. package/src/backends/mlx/checkpoint-state.ts +0 -53
  226. package/src/backends/mlx/continuation-persistence.ts +0 -107
  227. package/src/backends/mlx/continuation-request.ts +0 -43
  228. package/src/backends/mlx/continuation.ts +0 -77
  229. package/src/backends/mlx/diffusion.ts +0 -39
  230. package/src/backends/mlx/draft-target.ts +0 -32
  231. package/src/backends/mlx/encoder-cache.ts +0 -25
  232. package/src/backends/mlx/evaluation.ts +0 -105
  233. package/src/backends/mlx/fill-append.ts +0 -58
  234. package/src/backends/mlx/fill-group.ts +0 -497
  235. package/src/backends/mlx/full-kv-row-append.ts +0 -32
  236. package/src/backends/mlx/full-kv-row-donor.ts +0 -54
  237. package/src/backends/mlx/full-transitioning-kv-rows.ts +0 -65
  238. package/src/backends/mlx/gateway-binding.ts +0 -174
  239. package/src/backends/mlx/graph.ts +0 -38
  240. package/src/backends/mlx/kv-codec.ts +0 -9
  241. package/src/backends/mlx/kv-maintenance.ts +0 -161
  242. package/src/backends/mlx/kv-tensor-rows.ts +0 -212
  243. package/src/backends/mlx/memory-client.ts +0 -189
  244. package/src/backends/mlx/methods.ts +0 -90
  245. package/src/backends/mlx/mixed-iteration.ts +0 -62
  246. package/src/backends/mlx/model-prompt.ts +0 -178
  247. package/src/backends/mlx/model-serving.ts +0 -80
  248. package/src/backends/mlx/paged-cache-codec.ts +0 -27
  249. package/src/backends/mlx/prefill-cohort.ts +0 -100
  250. package/src/backends/mlx/prefill-policy.ts +0 -26
  251. package/src/backends/mlx/prefill-rows.ts +0 -244
  252. package/src/backends/mlx/prefill.ts +0 -33
  253. package/src/backends/mlx/projected-context-rows.ts +0 -72
  254. package/src/backends/mlx/prompt-input.ts +0 -29
  255. package/src/backends/mlx/qwen-prompt-input.ts +0 -40
  256. package/src/backends/mlx/request-policy.ts +0 -20
  257. package/src/backends/mlx/request-state-policy.ts +0 -54
  258. package/src/backends/mlx/rollback.ts +0 -92
  259. package/src/backends/mlx/row-sampling.ts +0 -49
  260. package/src/backends/mlx/serial-executor.ts +0 -251
  261. package/src/backends/mlx/speculative-group.ts +0 -438
  262. package/src/backends/mlx/speculative-round.ts +0 -161
  263. package/src/backends/mlx/speculative.ts +0 -131
  264. package/src/backends/mlx/state-rows.ts +0 -104
  265. package/src/backends/mlx/state-views.ts +0 -46
  266. package/src/backends/mlx/target-layout-capability.ts +0 -35
  267. package/src/backends/mlx/text-engine.ts +0 -73
  268. package/src/backends/mlx/transitioning-kv-rows.ts +0 -173
  269. package/src/chat-template.ts +0 -382
  270. package/src/cli.ts +0 -3490
  271. package/src/config.ts +0 -399
  272. package/src/contracts/completion.ts +0 -16
  273. package/src/contracts/execution.ts +0 -70
  274. package/src/contracts/generation.ts +0 -103
  275. package/src/contracts/host.ts +0 -7
  276. package/src/contracts/object-cache.ts +0 -8
  277. package/src/contracts/pi-provider.ts +0 -30
  278. package/src/contracts/pi.ts +0 -261
  279. package/src/contracts/prefix-cache.ts +0 -33
  280. package/src/contracts/resources.ts +0 -25
  281. package/src/contracts/sampling.ts +0 -23
  282. package/src/contracts/scheduling.ts +0 -54
  283. package/src/contracts/tsconfig.json +0 -14
  284. package/src/dataset/generators.ts +0 -1087
  285. package/src/dataset/index.ts +0 -12
  286. package/src/dataset/job.ts +0 -81
  287. package/src/dataset/llm.ts +0 -71
  288. package/src/dataset/registry.ts +0 -528
  289. package/src/diffusion/diffusion-generate.ts +0 -507
  290. package/src/download.ts +0 -505
  291. package/src/embed.ts +0 -77
  292. package/src/engine/admission.ts +0 -59
  293. package/src/engine/cancellation.ts +0 -38
  294. package/src/engine/engine.ts +0 -56
  295. package/src/engine/execution-coordinator.ts +0 -70
  296. package/src/engine/execution-plan.ts +0 -64
  297. package/src/engine/execution-tasks.ts +0 -44
  298. package/src/engine/namespaced-cache.ts +0 -13
  299. package/src/engine/resources.ts +0 -53
  300. package/src/engine/scheduler.ts +0 -92
  301. package/src/engine/session.ts +0 -247
  302. package/src/eval/README.md +0 -130
  303. package/src/eval/ifeval.ts +0 -81
  304. package/src/eval/kl-prompts.ts +0 -29
  305. package/src/eval/kl.ts +0 -590
  306. package/src/eval/perplexity.ts +0 -164
  307. package/src/eval/quality-db.ts +0 -92
  308. package/src/eval/reference-logits.ts +0 -207
  309. package/src/eval/runner.ts +0 -124
  310. package/src/eval/score.ts +0 -49
  311. package/src/eval/tasks/bfcl.ts +0 -535
  312. package/src/eval/tasks/gsm8k.ts +0 -98
  313. package/src/eval/tasks/hashhop.ts +0 -139
  314. package/src/eval/tasks/humaneval.ts +0 -275
  315. package/src/eval/tasks/ifeval.ts +0 -525
  316. package/src/eval/tasks/mmlu.ts +0 -157
  317. package/src/eval/ultrafeedback.ts +0 -60
  318. package/src/evaldb.ts +0 -199
  319. package/src/expert-io.ts +0 -393
  320. package/src/expert-offload-build.ts +0 -77
  321. package/src/expert-offload.ts +0 -76
  322. package/src/expert-residency.ts +0 -1134
  323. package/src/expert-usage.ts +0 -415
  324. package/src/fill/echo-index.ts +0 -188
  325. package/src/fill/fill-session.ts +0 -463
  326. package/src/fill/proposal.ts +0 -68
  327. package/src/fill/schema-rows.ts +0 -506
  328. package/src/fill/tool-boundary.ts +0 -103
  329. package/src/fit.ts +0 -249
  330. package/src/generate.ts +0 -1352
  331. package/src/grammar.ts +0 -604
  332. package/src/harness-pi.ts +0 -184
  333. package/src/hf-push.ts +0 -628
  334. package/src/hub-rest.ts +0 -242
  335. package/src/index.ts +0 -63
  336. package/src/inference/denoising.ts +0 -17
  337. package/src/inference/draft-acceptance.ts +0 -41
  338. package/src/inference/draft-output.ts +0 -49
  339. package/src/inference/graph.ts +0 -33
  340. package/src/inference/prefill.ts +0 -45
  341. package/src/inference/rollback.ts +0 -7
  342. package/src/jobs/index.ts +0 -31
  343. package/src/jobs/job-entry.ts +0 -107
  344. package/src/jobs/task-client.ts +0 -19
  345. package/src/jobs/types.ts +0 -2
  346. package/src/kv-scheme.ts +0 -279
  347. package/src/kv-store.ts +0 -1135
  348. package/src/lab/README.md +0 -22
  349. package/src/lab/curve/curve-designer.html +0 -303
  350. package/src/lab/curve/curve-sampler.ts +0 -122
  351. package/src/lab/expert-trace/expert-trace.ts +0 -69
  352. package/src/lab/paged-kv/paged-attention.ts +0 -117
  353. package/src/lab/paged-kv/paged-kv-rows.ts +0 -111
  354. package/src/lab/paged-kv/paged-kv.ts +0 -336
  355. package/src/library.ts +0 -40
  356. package/src/lora.ts +0 -408
  357. package/src/md-modules.d.ts +0 -54
  358. package/src/media-fetch.ts +0 -442
  359. package/src/memory/article.ts +0 -558
  360. package/src/memory/chunk-validation.ts +0 -150
  361. package/src/memory/chunk.ts +0 -318
  362. package/src/memory/cluster.ts +0 -351
  363. package/src/memory/coverage.ts +0 -134
  364. package/src/memory/crosslink.ts +0 -0
  365. package/src/memory/db.ts +0 -253
  366. package/src/memory/entity.ts +0 -203
  367. package/src/memory/gate.ts +0 -187
  368. package/src/memory/history.ts +0 -152
  369. package/src/memory/ingest.ts +0 -335
  370. package/src/memory/model.ts +0 -183
  371. package/src/memory/normalize.ts +0 -671
  372. package/src/memory/parse.ts +0 -22
  373. package/src/memory/pipeline.ts +0 -275
  374. package/src/memory/prompts.ts +0 -65
  375. package/src/memory/query.ts +0 -334
  376. package/src/memory/reconcile.ts +0 -734
  377. package/src/memory/redirect.ts +0 -108
  378. package/src/memory/reindex.ts +0 -325
  379. package/src/memory/resolve.ts +0 -307
  380. package/src/memory/rest.ts +0 -245
  381. package/src/memory/route.ts +0 -272
  382. package/src/memory/schedule.ts +0 -165
  383. package/src/memory/stages.ts +0 -777
  384. package/src/memory/synthesize.ts +0 -1638
  385. package/src/memory/tools.ts +0 -749
  386. package/src/memory/vault.ts +0 -1194
  387. package/src/memory/wikify.ts +0 -1064
  388. package/src/mlx/array.ts +0 -425
  389. package/src/mlx/autograd.ts +0 -304
  390. package/src/mlx/checkpoint.ts +0 -149
  391. package/src/mlx/compile.ts +0 -168
  392. package/src/mlx/custom-vjp.ts +0 -188
  393. package/src/mlx/ffi.ts +0 -531
  394. package/src/mlx/materialize.ts +0 -23
  395. package/src/mlx/metal-kernel.ts +0 -159
  396. package/src/mlx/normalized-argmax.ts +0 -116
  397. package/src/mlx/ops.ts +0 -1108
  398. package/src/mlx/quantized-rows.ts +0 -36
  399. package/src/mlx/token-bitmask.ts +0 -52
  400. package/src/mlx/turboquant-kv-decode.ts +0 -82
  401. package/src/mlx/turboquant-kv-inverse.ts +0 -122
  402. package/src/mlx/turboquant-ops.ts +0 -861
  403. package/src/mlx/turboquant-tables.ts +0 -237
  404. package/src/mmap.ts +0 -90
  405. package/src/model/artifact-identity.ts +0 -73
  406. package/src/model/batched-kv.ts +0 -235
  407. package/src/model/batched-mask.ts +0 -279
  408. package/src/model/batched-quant.ts +0 -212
  409. package/src/model/batched-quantized-kv.ts +0 -144
  410. package/src/model/batched-rotating-quant.ts +0 -353
  411. package/src/model/batched-rotating-state.ts +0 -149
  412. package/src/model/batched-rotating.ts +0 -338
  413. package/src/model/batched-row-storage.ts +0 -179
  414. package/src/model/batched-ssm.ts +0 -52
  415. package/src/model/batched-turboquant-kv.ts +0 -94
  416. package/src/model/compiled-decode.ts +0 -712
  417. package/src/model/decoded-kv-donor.ts +0 -12
  418. package/src/model/delayed-quantized-kv.ts +0 -72
  419. package/src/model/delayed-rotating-quantized-kv.ts +0 -93
  420. package/src/model/delayed-turboquant-kv.ts +0 -57
  421. package/src/model/diffusion-gemma.ts +0 -1026
  422. package/src/model/factory.ts +0 -215
  423. package/src/model/fingerprint.ts +0 -45
  424. package/src/model/flash-attention.ts +0 -694
  425. package/src/model/full-prefill-padding.ts +0 -56
  426. package/src/model/full-prefill-row.ts +0 -105
  427. package/src/model/gemma4-base.ts +0 -2370
  428. package/src/model/gemma4.ts +0 -1395
  429. package/src/model/generated/gemma4-12b.ts +0 -429
  430. package/src/model/generated/gemma4-26b.ts +0 -448
  431. package/src/model/generated/gemma4-e4b.ts +0 -717
  432. package/src/model/generated/index.ts +0 -18
  433. package/src/model/glm52-atlas.ts +0 -511
  434. package/src/model/glm52-cache.ts +0 -792
  435. package/src/model/glm52-config.ts +0 -262
  436. package/src/model/glm52-container.ts +0 -305
  437. package/src/model/glm52-coupling.ts +0 -388
  438. package/src/model/glm52-dsa.ts +0 -606
  439. package/src/model/glm52-expert-layout.ts +0 -253
  440. package/src/model/glm52-layout.ts +0 -152
  441. package/src/model/glm52-memory.ts +0 -500
  442. package/src/model/glm52-mla.ts +0 -792
  443. package/src/model/glm52-moe.ts +0 -223
  444. package/src/model/glm52-pilot.ts +0 -537
  445. package/src/model/glm52-reference.ts +0 -445
  446. package/src/model/glm52-residency.ts +0 -557
  447. package/src/model/glm52-resident-weights.ts +0 -135
  448. package/src/model/glm52-streamed-experts.ts +0 -453
  449. package/src/model/glm52-streamed-metal.ts +0 -610
  450. package/src/model/glm52-weights.ts +0 -503
  451. package/src/model/glm52.ts +0 -1132
  452. package/src/model/implementation.ts +0 -69
  453. package/src/model/kv-attention-view.ts +0 -70
  454. package/src/model/minicpm5.ts +0 -376
  455. package/src/model/profile.ts +0 -468
  456. package/src/model/quantized-append-attention.ts +0 -31
  457. package/src/model/qwen-append.ts +0 -12
  458. package/src/model/qwen-conv.ts +0 -52
  459. package/src/model/qwen3-delta-state.ts +0 -74
  460. package/src/model/qwen3-delta.ts +0 -451
  461. package/src/model/qwen3-moe.ts +0 -404
  462. package/src/model/qwen3-mrope.ts +0 -250
  463. package/src/model/qwen3.ts +0 -277
  464. package/src/model/qwen3_5-checkpoint.ts +0 -164
  465. package/src/model/qwen3_5.ts +0 -881
  466. package/src/model/rotating-kv-donor.ts +0 -35
  467. package/src/model/rotating-kv-layout.ts +0 -262
  468. package/src/model/rotating-row-transaction.ts +0 -35
  469. package/src/model/speculative-rotating-kv.ts +0 -101
  470. package/src/model/ssm-prefill-padding.ts +0 -39
  471. package/src/model/support.ts +0 -110
  472. package/src/model/token-groups.ts +0 -66
  473. package/src/model/trellis-balanced-scatter.ts +0 -51
  474. package/src/model/trellis-linear.ts +0 -672
  475. package/src/model/trellis-shared-m.ts +0 -151
  476. package/src/model/trellis-shared-scatter.ts +0 -144
  477. package/src/model/trellis-splitk-prefill.ts +0 -158
  478. package/src/model/trellis-tiled-prefill.ts +0 -136
  479. package/src/model/trellis-vector-expand.ts +0 -62
  480. package/src/model/trellis-wide-prefill.ts +0 -94
  481. package/src/model/turboquant-codec.ts +0 -89
  482. package/src/model/universal/archs.ts +0 -332
  483. package/src/model/universal/dense.ts +0 -612
  484. package/src/model/universal/modules.ts +0 -170
  485. package/src/model/universal/rope.ts +0 -381
  486. package/src/model/whisper.ts +0 -435
  487. package/src/native/expert_io.c +0 -523
  488. package/src/native/frame_extract.swift +0 -140
  489. package/src/native/mic_capture.swift +0 -92
  490. package/src/native-pack.ts +0 -163
  491. package/src/pi-provider.ts +0 -53
  492. package/src/pi-session.ts +0 -81
  493. package/src/pi-terminal.ts +0 -274
  494. package/src/pi-web.ts +0 -1940
  495. package/src/preflight.ts +0 -158
  496. package/src/prompt-cache.ts +0 -682
  497. package/src/quantize/allocator.ts +0 -627
  498. package/src/quantize/atomic-output.ts +0 -38
  499. package/src/quantize/calibration.ts +0 -181
  500. package/src/quantize/config-writer.ts +0 -145
  501. package/src/quantize/index.ts +0 -84
  502. package/src/quantize/job.ts +0 -162
  503. package/src/quantize/quantizer.ts +0 -666
  504. package/src/quantize/rotate.ts +0 -603
  505. package/src/quantize/safetensors-writer.ts +0 -249
  506. package/src/quantize/sensitivity.ts +0 -216
  507. package/src/quantize/trellis.ts +0 -586
  508. package/src/quantize/weight-transform.ts +0 -292
  509. package/src/registry.ts +0 -602
  510. package/src/runtime-config.ts +0 -77
  511. package/src/safetensors.ts +0 -165
  512. package/src/sampler.ts +0 -1012
  513. package/src/serve/admin-routes.ts +0 -184
  514. package/src/serve/assets/curve-terrain.html +0 -105
  515. package/src/serve/assets/training-inference-map.html +0 -575
  516. package/src/serve/audio-routes.ts +0 -323
  517. package/src/serve/aux-routes.ts +0 -132
  518. package/src/serve/batch-scheduler.ts +0 -8
  519. package/src/serve/checkpoint-identity.ts +0 -64
  520. package/src/serve/generation-gateway.ts +0 -537
  521. package/src/serve/isolate.ts +0 -609
  522. package/src/serve/kv-budget.ts +0 -14
  523. package/src/serve/lab-routes.ts +0 -341
  524. package/src/serve/lane-registry.ts +0 -45
  525. package/src/serve/model-admin-routes.ts +0 -155
  526. package/src/serve/model-binding.ts +0 -49
  527. package/src/serve/model-host.ts +0 -511
  528. package/src/serve/parent-application.ts +0 -56
  529. package/src/serve/prompt-response-trace.ts +0 -161
  530. package/src/serve/response-lease.ts +0 -24
  531. package/src/serve/session-search.ts +0 -326
  532. package/src/serve/static-routes.ts +0 -101
  533. package/src/serve/transcription-server.ts +0 -64
  534. package/src/serve/transcription-service.ts +0 -502
  535. package/src/server.ts +0 -1282
  536. package/src/spec/assistant-rows.ts +0 -93
  537. package/src/spec/assistant-source.ts +0 -126
  538. package/src/spec/cache-identity.ts +0 -22
  539. package/src/spec/deepspec-rows.ts +0 -29
  540. package/src/spec/deepspec-source.ts +0 -145
  541. package/src/spec/dflash-source.ts +0 -149
  542. package/src/spec/drafter.ts +0 -304
  543. package/src/spec/dspark/ab-stats.ts +0 -136
  544. package/src/spec/dspark/calibration.ts +0 -112
  545. package/src/spec/dspark/data-dflash.ts +0 -156
  546. package/src/spec/dspark/data.ts +0 -201
  547. package/src/spec/dspark/deepspec-module.ts +0 -776
  548. package/src/spec/dspark/generate-dflash.ts +0 -245
  549. package/src/spec/dspark/generate.ts +0 -290
  550. package/src/spec/dspark/loader.ts +0 -23
  551. package/src/spec/dspark/loss.ts +0 -213
  552. package/src/spec/dspark/module-dflash.ts +0 -560
  553. package/src/spec/dspark/module.ts +0 -540
  554. package/src/spec/dspark/quantize-drafter.ts +0 -91
  555. package/src/spec/dspark/sample.ts +0 -112
  556. package/src/spec/generate.ts +0 -276
  557. package/src/spec/glm52-mtp-graph.ts +0 -29
  558. package/src/spec/glm52-mtp-rows.ts +0 -132
  559. package/src/spec/glm52-mtp-source.ts +0 -318
  560. package/src/spec/glm52-mtp-state.ts +0 -33
  561. package/src/spec/ngram-source.ts +0 -226
  562. package/src/spec/projected-draft-rows.ts +0 -73
  563. package/src/spec/qwen-mtp-module.ts +0 -171
  564. package/src/spec/qwen-mtp-rows.ts +0 -230
  565. package/src/spec/qwen-mtp-source.ts +0 -386
  566. package/src/spec/qwen-mtp-state.ts +0 -30
  567. package/src/spec/serve-loop.ts +0 -587
  568. package/src/spec/source.ts +0 -228
  569. package/src/spec/two-model-rows.ts +0 -62
  570. package/src/spec/two-model.ts +0 -113
  571. package/src/ssd-cache.ts +0 -431
  572. package/src/ssd-durability.ts +0 -209
  573. package/src/storage/host-buffer.ts +0 -24
  574. package/src/storage/kv-writer.ts +0 -83
  575. package/src/storage/kv-writer.worker.js +0 -264
  576. package/src/storage/retention-policy.ts +0 -37
  577. package/src/tiered-prompt-cache.ts +0 -45
  578. package/src/tokenizer.ts +0 -335
  579. package/src/tool-approvals.ts +0 -131
  580. package/src/tool-call.ts +0 -695
  581. package/src/train/dataset.ts +0 -484
  582. package/src/train/diffusion-lora.ts +0 -216
  583. package/src/train/export.ts +0 -32
  584. package/src/train/flash-cce.ts +0 -1234
  585. package/src/train/forward.ts +0 -266
  586. package/src/train/fuse.ts +0 -243
  587. package/src/train/index.ts +0 -46
  588. package/src/train/job.ts +0 -205
  589. package/src/train/lora-params.ts +0 -254
  590. package/src/train/loss.ts +0 -1591
  591. package/src/train/merge.ts +0 -195
  592. package/src/train/optimizer.ts +0 -183
  593. package/src/train/prefix-shared.ts +0 -490
  594. package/src/train/rank.ts +0 -137
  595. package/src/train/segmented.ts +0 -1828
  596. package/src/train/steel-qmm-header.ts +0 -1461
  597. package/src/train/trainer.ts +0 -1221
  598. package/src/train/watch.ts +0 -542
  599. package/src/vision/diffusion-vision.ts +0 -620
  600. package/src/vision/embedder.ts +0 -176
  601. package/src/vision/preprocess.ts +0 -247
  602. package/src/vision/prompt.ts +0 -409
  603. package/src/vision/qwen3vl-preprocess.ts +0 -409
  604. package/src/vision/qwen3vl-prompt.ts +0 -233
  605. package/src/vision/qwen3vl-tower.ts +0 -566
  606. package/src/vision/siglip.ts +0 -607
  607. package/src/vision/video-frames.ts +0 -148
  608. package/src/web/app.html +0 -2155
  609. package/src/web/app.js +0 -5863
  610. package/src/web/skills/memory/SKILL.md +0 -120
  611. package/src/web/skills/web-research/SKILL.md +0 -46
  612. package/src/web/skills.ts +0 -97
  613. package/src/web/src/adapters-panel.ts +0 -288
  614. package/src/web/src/assistant.ts +0 -451
  615. package/src/web/src/chat.ts +0 -1060
  616. package/src/web/src/composer.ts +0 -962
  617. package/src/web/src/dataset.ts +0 -132
  618. package/src/web/src/finetune.ts +0 -267
  619. package/src/web/src/hub.ts +0 -428
  620. package/src/web/src/main.ts +0 -98
  621. package/src/web/src/markdown.ts +0 -0
  622. package/src/web/src/memory-panel.ts +0 -572
  623. package/src/web/src/model-picker.ts +0 -159
  624. package/src/web/src/palette.ts +0 -346
  625. package/src/web/src/protocol.ts +0 -26
  626. package/src/web/src/quantize.ts +0 -167
  627. package/src/web/src/rag.ts +0 -274
  628. package/src/web/src/sessions.ts +0 -469
  629. package/src/web/src/shell.ts +0 -804
  630. package/src/web/src/ui-catalog.ts +0 -78
  631. package/src/web/src/voice.ts +0 -141
  632. package/src/web/vendor/README.md +0 -61
  633. package/src/web-assets.ts +0 -47
  634. package/src/web-tools.ts +0 -478
  635. package/src/weights.ts +0 -255
  636. /package/src/{serve → server}/completion-sink.ts +0 -0
  637. /package/src/{serve → server}/generated-token-history.ts +0 -0
  638. /package/src/web/{icon.svg → public/icon.svg} +0 -0
  639. /package/src/web/{manifest.webmanifest → public/manifest.webmanifest} +0 -0
  640. /package/src/web/{vendor → public/vendor}/hljs-LICENSE +0 -0
@@ -1,2404 +0,0 @@
1
- ---
2
- status: active
3
- axis: ON
4
- canonical-for: decode-speed-levers
5
- plan-anchor: "Phase 6 — Speed: change what gets computed `[~]`"
6
- last-verified: 2026-09-08
7
- ---
8
-
9
- # Inference performance program
10
-
11
- This is the canonical performance research plan. The current priority is the
12
- Qwen3.8-27B program in section 7, covering quants, the complete execution graph,
13
- custom kernels, deterministic token replay, prefill, decode, and serving.
14
- Sections 1–6 retain the earlier cross-model research and the
15
- **port ledger vs oMLX** (§6, folded in from `docs/design/omlx-adoption-map.md`
16
- in `2b571ff`, 2026-08-24). Open status lives in PLAN.md (Phase 6); the
17
- campaign run log is
18
- [qwen38-27b-campaign-log.md](../archive/investigations/qwen38-27b-campaign-log.md)
19
- and its outcome ledger is §7.13; the architecture the levers plug into is
20
- `unified-engine-frontier-plan.md`; curated numbers are
21
- `docs/reference/benchmarks.md`. Every lever here has evidence, an expected
22
- win, and a trigger; pick them up in order. No number below is new — each
23
- cites where it was measured.
24
-
25
- ## 1. The physics and the baseline
26
-
27
- For an efficient bandwidth-bound implementation,
28
- decode tok/s ≈ bandwidth ÷ bytes-touched-per-token. The earlier mode-matrix benchmark
29
- (`scripts/bench-matrix.ts modes`) confirmed what the roofline work predicted:
30
- the then-tested L1 decode paths approached the memory-bandwidth wall
31
- at short context, so tier levers cannot buy single-stream decode speed
32
- (naked default = `--l1`, decided 2026-07-05, `git show 3199c75:PLAN-archive.md`:
33
- decode parity with mlx-lm on every model; no output-changing lever beat it). Faster therefore means one of five
34
- physical moves:
35
-
36
- 1. read the weight bytes ONCE for several tokens — speculation, batching;
37
- 2. read FEWER bytes — quantization quality-per-bit;
38
- 3. SKIP reads — caching (prefill/TTFT side, already leadership territory);
39
- 4. shave the non-GPU residue — host overhead, dispatch count, residency.
40
- 5. execute the math more efficiently when arithmetic, access patterns or
41
- occupancy keep the implementation below its bandwidth limit.
42
-
43
- One correction the bandwidth framing missed (2026-07-04, CPM5): small
44
- ELEMENTWISE ops are dispatch-bound, not bandwidth-bound. An unfused swiglu
45
- (`sigmoid` + `mul` + `mul`, 3 kernels/layer × 24) cost ~5% of decode; porting
46
- mlx-lm's `@mx.compile` swiglu (`compiledSwiglu`, now the default in
47
- `src/model/minicpm5.ts`, `qwen3.ts`, `qwen3_5.ts`, `qwen3-moe.ts`,
48
- `universal/dense.ts`; `MLX_BUN_COMPILED_SWIGLU=0` kills it) moved CPM5 to
49
- parity with mlx-lm, bit-identical tokens. The win was per-dispatch host +
50
- encode tax, which is why CompiledDecode was 0% there (it replays the same
51
- unfused graph). Packed trellis is a further exception: unpack arithmetic,
52
- memory access patterns, and occupancy can dominate its matrix products.
53
- Section 7 measures these limits for each shape and chip instead of assuming
54
- fewer bits are faster.
55
-
56
- ## 2. The levers, ranked
57
-
58
- ### Lever 1 — speculative decoding, subject to a wall-clock win
59
-
60
- One target forward verifies γ drafts + a bonus token: the weight read
61
- amortizes over up to γ+1 tokens. The serve loop is the ONE verify/accept
62
- executor (`src/spec/serve-loop.ts`, faithful to mlx-lm's
63
- `speculative_generate_step`; grammar composes on the verify walk), reached
64
- through `serve --draft-model` / `--draft-kind`, with `usage.speculation`
65
- telemetry. Drafters, as wired in `src/spec/` and `src/cli.ts` on 2026-08-23:
66
-
67
- | kind | source | status | evidence |
68
- |---|---|---|---|
69
- | `two-model` | `two-model.ts` — a full same-tokenizer draft model (mlx_lm.server parity) | landed | 48/48 token-for-token vs mlx-lm's spec path (`docs/design/batching.md` Phase B) |
70
- | `assistant` | `assistant-source.ts` — optiq's KV-borrowing Gemma "-assistant" drafter | landed (was "build next" in the 2026-07-04 draft of this doc) | bit-exact vs optiq's `spec_generate`; 12B γ=1 ≈ 1.09× (`docs/design/speculative-decoding.md`); e4b a net loss at every γ (PLAN.md Phase 6) |
71
- | `dspark` / `deepspec` | `dflash-source.ts`, `deepspec-source.ts` — DFlash KV-injection (ours / DeepSeek's released drafters) | landed, wall-clock NEGATIVE so far | 12B + block-7 drafter: τ ≈ 2.8 committed tokens per target forward but ~3.4× slower wall-clock (spec 14.6 vs serial 49.8 agg tok/s, loaded box) — the drafter's own weight reads and host syncs are the tax (`docs/design/speculative-decoding.md`) |
72
- | `mtp` | `qwen-mtp-source.ts`, `glm52-mtp-source.ts` | Qwen3.8 implemented, opt-in; measured negative on the 27B | `speculative-decoding.md` section 4.4 records the off/on wall-clock comparison; acceptance alone is not a speed result |
73
- | `ngram` | `ngram-source.ts` — model-free prompt lookup, lossless | landed | no drafter weights; drafts copied from the request's own context (`--ngram-max/--ngram-min`) |
74
-
75
- What remains is drafters worth running, in this order:
76
-
77
- - **1a. Reopen native MTP only with a changed cost model.** The native head
78
- still reads head weights, projects vocabulary logits, and samples drafts.
79
- The recorded Qwen off/on comparison lost. Test head quantization and small-M
80
- verify kernels against the same artifact with MTP off; retain off as control.
81
- - **1b. Cheaper drafter head** — the 262k tied-embedding argmax every draft
82
- step dominates γ≥2 cost on the Gemma assistant drafter; capping or
83
- approximating it extends the win past γ=1 (`docs/design/speculative-decoding.md`
84
- "remaining levers").
85
- - **1c. DSpark wall-clock flip** — `docs/design/speculative-decoding.md` Phases 0–4
86
- (drafter weight diet, host-sync reduction in `draftBlock`, tapped verifies
87
- on the optimized graph). Goal there: spec ≥ 1.3× serial on 12B at the best
88
- config, clean machine. No-oracle / KL-gated (Lab).
89
- - **1d. Grammar-aware speculation** — the grammar mask collapses the
90
- drafting problem on structured output. State in `src/` today:
91
- (i) **jump-forward** exists as `MLX_BUN_GRAMMAR_JUMP=1`, opt-in, in the
92
- serial NON-spec loop only (`generate.ts` `shouldUseGrammarJump`; the batch
93
- lane's `#stepGrammar` doesn't jump; excluded when logprobs are requested).
94
- It is not yet folded into a spec verify window as a pre-accepted draft.
95
- (ii) **constrained drafting** is NOT implemented — the drafter runs free and
96
- the mask rides the verify walk (`serve-loop.ts` header); the
97
- `MLX_BUN_SPEC_GRAMMAR_DRAFT` lever an older draft of this doc named does not
98
- exist in `src/`. The measured motivation stands: acceptance dropped 51%→29%
99
- under grammar with a blind drafter (our own matrix). (iii) grammar-pruned
100
- draft TREES (XGrammar-2's `traverse_draft_tree`) — idea only.
101
- - **Drafting under batching** — grouped provider execution is implemented at
102
- B1/B>1, with method-owned candidate generation, verification and companion
103
- state. Remaining compositions and evidence live in [batching](batching.md#consolidation-matrix).
104
-
105
- ### Lever 2 — native MLX updates against the pinned control
106
-
107
- The runtime and oracle now use MLX 0.32.2 / native pack 0.4.0; see §7.12 and
108
- [environment](../reference/environment.md). The historical July audit below
109
- identified upstream changes absent from its then-current MLX 0.31.2 pin. Recheck current releases and the native libraries actually loaded before
110
- an upgrade experiment. A new mlx/mlx-c build also needs matching oracles;
111
- retain the pinned installation and test the new stack in isolation.
112
- Upstream refs are full URLs on purpose (a bare `#NNNN` here resolves to our
113
- own tracker).
114
-
115
- What `main` has (confirmed against the PR pages, 2026-07-04):
116
- - [ml-explore/mlx#3485](https://github.com/ml-explore/mlx/pull/3485)
117
- `GatherQMM::output_shapes` (merged 2026-05-29, zero numeric change) — THE
118
- prize: `src/model/compiled-decode.ts` still keeps MoE models uncompiled
119
- because GatherQMM lacks `output_shapes` in the pinned mlx (verified
120
- 2026-08-23); this unblocks CompiledDecode over the MoE and attacks the
121
- 26B/30B-A3B host term.
122
- - [ml-explore/mlx#3764](https://github.com/ml-explore/mlx/pull/3764)
123
- `qmv_wide` (merged 2026-06-26) — small-M (≈2–8) quant matvec: helps the
124
- spec-decode VERIFY forward and small batches, NOT single-stream M=1 and NOT
125
- the gather/MoE path. Becomes the default at M≈2–8 → re-baseline batched
126
- goldens.
127
-
128
- The older description of
129
- [ml-explore/mlx#3553](https://github.com/ml-explore/mlx/issues/3553) was wrong:
130
- it describes a dense small-M QMV discontinuity, not the MoE gather path, and
131
- is closed as of 2026-09-04. Issue status does not establish which fix is in
132
- our binary. Inspect the selected dispatch and measure Qwen's actual shapes.
133
- [ml-explore/mlx#3120](https://github.com/ml-explore/mlx/pull/3120) (split-K
134
- small-M quant matmul) predates the 0.31.2 tag — probably already ours;
135
- confirm before counting it.
136
-
137
- For the dense 27B, prioritize small-M reuse for fill spans and prefill before
138
- reopening MTP. MoE-specific changes belong to the other models' experiments.
139
-
140
- ### Lever 3 — quantization quality, bytes and measured latency
141
-
142
- On bandwidth-bound paths, reducing weight bytes can improve decode. Packed
143
- formats also change unpack cost and access patterns, so test the latency of
144
- each recipe. Existing quality-per-bit work includes the sensitivity-driven
145
- knapsack (`convert --target-bpw`, `src/quantize/sensitivity.ts`, a port of
146
- optiq's `analyze_sensitivity_exact`), rotation-folded quantization
147
- (`--rotate-weights`, `docs/design/turboquant.md`), and TurboQuant KV
148
- (`docs/design/turboquant.md`). The 27B program's measured verdict (STATUS.md /
149
- PLAN.md "TurboQuant weights"): quality saturates at ≥4.5 bpw on ppl and
150
- MMLU/GSM8K; recipes matter below 4 bpw, where rotation wins (the 3.86 bpw /
151
- 13.9 GB Qwen3.8-27B-TQ artifact is the M4 Pro 24 GB fit lever). Decode tok/s
152
- for those artifacts on a quiet box is still owed (PLAN W7) — do not quote a
153
- speed number for them until it exists. Gate for any new recipe: perplexity +
154
- the frozen 6-task eval at equal bpw, eval-DB rows.
155
-
156
- ### Lever 4 — host-side residuals [expected 2–8% on affected models]
157
-
158
- - **Compiled elementwise activations — LANDED** (§1). Same standalone
159
- `sigmoid/silu + mul` pattern audited into every dedicated file; gemma geglu
160
- is `MLX_BUN_COMPILED_GEGLU` (default on).
161
- - **Weight residency (wiring) — LANDED 2026-08-23** (PLAN.md "Prefill vs
162
- mlx-lm — paired re-measurement" and the follow-up; STATUS.md): the
163
- large-model wiring policy was stale against macOS's reported working set,
164
- so Qwen3.8-27B ran unwired. Both the serial generator and the continuous
165
- scheduler now hold the same re-entrant wired scope (`acquireModelWiredLimit`
166
- in `src/generate.ts`) while they own the GPU; the controlled replay moved
167
- the final Qwen L=1 forward from about 1.48 s to 55 ms. Numerics unchanged.
168
- Rule: a decode-class regression on a large model is a residency question
169
- before it is a kernel question.
170
- - **e4b ~5% per-step host overhead** (PLAN.md Phase 7 residual; dispatch
171
- count) — still open; prime suspect is the same unfused-elementwise class.
172
- Method: xctrace shader-list diff vs mlx-lm (the qwen3.5 kernel-trace parity
173
- method), then `mx.compile` the site.
174
- - **P4 device-side step chaining** — depth-k chained step graphs, one host
175
- sync per k tokens (`docs/design/batching.md` P4). Attacks OUR FFI/readback
176
- cost — a different mechanism from oMLX's burst decode, whose refutation
177
- (§6) does not apply.
178
- - **Padded-B>1 per-step mask rebuild** — by design in the scheduler's padded
179
- branch; unmeasured at B>1, likely amortized. Measure via a forced-padding
180
- aggregate A/B before building a step-stable mask cache (PLAN.md 2026-07-06
181
- audit).
182
- - **MoE M=1 gather path** — see lever 2; the compute-bound gap on 26B/30B-A3B
183
- is a kernel item, not a bump item.
184
-
185
- ### Non-levers (measured; don't re-litigate without new evidence)
186
-
187
- - **Megakernels at M=1** — bandwidth floor: ceiling ~1.78× on CPM5, achieved
188
- 0.94× (`docs/design/generic-model-support.md`); multi-token amortization is
189
- required, which is lever 1 / batching.
190
- - **oMLX-style burst decode** — refuted for Bun (§6).
191
- - **Fused-decode / perf kernel / custom fused-gelu** — deleted 2026-07-05
192
- after losing the paired A/B (architecture doc §11). A future flash-decode
193
- kernel re-derives from the L1 baseline in the Lab.
194
- - **QKV / gate-up matmul fusion at M=1** — CPM5 2026-07-04: q/k/v blocked by
195
- OptiQ mixed precision (v_proj 8-bit vs q/k 4-bit); gate/up fusible in 18/24
196
- layers but the speed-ceiling version measured ~2% SLOWER — matmul
197
- dispatches are bandwidth-hidden and a concatenated `[2I]` qmv is less
198
- efficient at M=1 than two `[I]`. Contrast the swiglu win: elementwise ops
199
- are dispatch-bound.
200
- - **Host graph-build overlap** — already hidden by the pipelined loop
201
- (spin-injection proof in
202
- `docs/archive/investigations/decode-roofline-lookagain.md`).
203
- - **Debranching alone** — ~0% (host JS conditionals hidden by the GPU-bound
204
- pipeline); it stays a hygiene item in the architecture doc, not a speed
205
- lever.
206
-
207
- ## 3. Sequence
208
-
209
- The current Qwen3.8-27B order is section 7.7: trustworthy controls, graph
210
- capture, packed kernels and deterministic replay, then the remaining measured
211
- bottlenecks and serving interactions. MTP requires a changed cost model.
212
- For shared engine changes, also run `scripts/bench-matrix.ts modes` on the
213
- affected e4b/12B controls. Promote clean-machine rows to
214
- `docs/reference/benchmarks.md`.
215
-
216
- ## 4. Related design ownership
217
-
218
- Section 7 coordinates TTFT, prefill, decode, and throughput. Implementation
219
- design remains with its topic: prompt cache + SSD tier
220
- (`docs/design/kv-cache.md`), batching aggregate (`docs/design/batching.md`),
221
- prefill vs mlx-lm (PLAN.md "Prefill vs mlx-lm — paired re-measurement",
222
- "Qwen3.8 prefill — measurement + analysis", and the prompt-to-response
223
- attribution matrix in STATUS.md).
224
-
225
- ## 5. Measurement discipline
226
-
227
- - Every claim is a paired A/B on this machine, labeled host/chip/RAM; run
228
- spread is the quality signal (`bench-h2h` retries unstable cells and
229
- withholds verdicts). Numbers on a loaded machine are not quotable.
230
- - Wall-clock only. SSE-burst inflates naive tok/s; oMLX's own logs
231
- over-report.
232
- - Verify the served model id (`/v1/models`) before trusting any bench.
233
- - A perf gap vs mlx-lm/optiq is OUR bug until proven otherwise: copy the
234
- oracle op-for-op, prove the kernel set identical (xctrace shader-list
235
- diff, `export_to_dot` op-set diff), then optimize.
236
-
237
- ## 6. Port ledger vs oMLX
238
-
239
- oMLX (github.com/jundot/omlx, Apache-2.0) is the systematic port source for
240
- serving features: read its real implementation (the full source ships in the
241
- local app bundle under `/Applications/oMLX.app/Contents/Resources/omlx/`),
242
- port the IDEA into our architecture, keep it only if OUR benchmarks improve.
243
- Attribution: derived code is noted in `THIRD_PARTY_LICENSES.md` (the
244
- xgrammar row credits `api/grammar.py`); idea ports get a source comment.
245
-
246
- ### Where oMLX sits in the tier model
247
-
248
- It doesn't slot at L1 or L2 — it decomposes. The tiers are numerics
249
- contracts; oMLX is a Python appliance ON mlx-lm:
250
-
251
- - its stock forwards are mlx-lm's numerics = our existing L1 oracle (no new
252
- oracle value);
253
- - its own numeric inventions (oQ, custom kernels, DFlash, MTP) are
254
- oracle-less = Lab-class here, and get our Lab gating (KL/eval/envelope +
255
- kill switch) that they lack upstream;
256
- - its product surface (SSD cache, EnginePool, menu bar, MCP, grammar) is the
257
- tier-agnostic serving layer — keyed by the effective scheme, never part of
258
- the decode-numerics graph.
259
-
260
- ### Ported, kept (benchmarked wins)
261
-
262
- | feature | theirs | ours | result |
263
- |---|---|---|---|
264
- | Continuous batching | scheduler on mlx-lm `BatchGenerator` | `--batch N` (default 8) → `src/serve/batch-scheduler.ts`, per-row samplers/processors, SSM (Qwen3.5) rows, `--kv-budget` admission, universal (Llama) per-row RoPE | cpm5 aggregate win, e4b/Qwen3.5 within a few %, TTFT 2–3× better (`docs/design/batching.md`); B=1 through the scheduler 0.992–0.996 of serial (PLAN.md) |
265
- | SSD KV cold tier | `cache/paged_ssd_cache.py` (content-hashed blocks) | `src/ssd-cache.ts` + kv-store v2 (whole-entry spill, zero-copy mmap), inside `PromptCache.take()` | restart TTFT 12.1 s → 0.24 s vs their 1–3 s; 0% decode overhead vs their ~20% (`docs/design/kv-cache.md`) |
266
- | Structured output | `api/grammar.py` | `@mlc-ai/web-xgrammar` (WASM), full `response_format`/`guided_*` surface, serial AND batched, composes with spec | byte-identical content vs oMLX (`docs/reference/server-api.md`) |
267
- | Multi-model serving / EnginePool | `engine_pool.py` (LRU + pinning + load/unload) | `--isolate --model-pool N` → `ModelPool` in `src/serve/isolate.ts`: LRU residency over engine children, routing by the request `model` field, spawn-overlap switching, drain → demote-to-SSD → park | switch ~1.5 s, switch-back ~1.2 s with the conversation's KV restored from disk (PLAN.md 2026-07-05, M1 Max, cpm5⇄qwen0.8b) |
268
- | DFlash serving wiring | `engine/dflash.py` + their published drafts | `DflashSource` / `DeepSpecSource` behind the same `DraftSource` seam as every other drafter (`--draft-kind dspark|deepspec`) | serve-integrated; wall-clock negative on 12B so far (lever 1c) |
269
-
270
- ### Ported, refuted (do not re-add without new evidence)
271
-
272
- | feature | why it doesn't transfer |
273
- |---|---|
274
- | Adaptive burst decode (`engine_core.py _step_burst`) | Amortizes Python GIL/asyncio ping-pong (~1 ms/token). Bun's `setImmediate` hop costs microseconds; the faithful port REGRESSED cpm5 B=4 aggregate 345→289, batch-lane B=1 149→121, and TTFT ~+100 ms (first-token SSE flush waits out the burst). Reverted with a breadcrumb in `batch-scheduler.ts`. |
275
-
276
- ### Queue (by leverage; ★ = Josh explicitly wants)
277
-
278
- 1. **★ Menu bar app** (`apps/omlx-mac/`, native SwiftUI + Sparkle) — product
279
- layer. Their repo is the structural reference; our signed/notarized single
280
- binary is the sidecar. Supersedes `docs/design/web-chat-redesign.md`'s Electron
281
- ambivalence. Not started.
282
- 2. **oQ-style sensitivity-driven quantization** (`oq.py`,
283
- `docs/oQ_Quantization.md`) — Lab-class, would land in `convert` beside
284
- `--target-bpw`: calibration-measured per-layer sensitivity with boosts on
285
- non-expert tensors only and batched expert GPTQ. Note the distinction: our
286
- `sensitivity.ts` is a port of optiq's exact-KL sweep, not oMLX's oQ. Gate:
287
- perplexity + 6-task eval vs the knapsack at equal bpw. The 27B finding that
288
- quality saturates ≥4.5 bpw narrows where this can pay (sub-4 bpw).
289
- 3. **Vision feature cache** (`cache/vision_feature_cache.py`) — encoder
290
- features for repeated-image agent turns; natural second client of the SSD
291
- substrate (Layer 0 in the architecture doc). Not started.
292
- 4. **MCP tool execution in serve** (`--mcp-config`, `mcp_routes.py`) — Pi
293
- already owns tool orchestration for our UIs; scope to bare-API consumers.
294
- Not started.
295
- 5. **Prefill progress observability** (`prefill_progress.py`) — /stats + web
296
- UI surfacing for long prompts. Our `PromptResponseTrace` is a diagnostic,
297
- not a live progress signal. Not started.
298
- 6. **Rerank endpoint** (`/v1/rerank`) — needs a reranker model family first.
299
- 7. **Document ingestion (MarkItDown)** — would go through Pi attachments, not
300
- the server.
301
- 8. **Admin one-click benchmark with prefix-cache-hit testing** — fold into
302
- `scripts/bench-serving-load.ts` as a cache-hit-ratio mode; not present.
303
-
304
- ### Explicitly not porting
305
-
306
- - **Audio STT/TTS/STS** — our audio work is the input tower
307
- (`docs/design/generic-model-support.md`), not their pipeline.
308
- - **Their SSE burst streaming** — a side effect of the GIL workaround;
309
- per-token streaming is strictly better UX at zero cost here.
310
- - **Python-side scheduler details** (GIL executors, collector reaping) —
311
- runtime-specific.
312
-
313
- ### Porting discipline
314
-
315
- 1. Read their real source first (the local app bundle) — the README lies
316
- less than the code.
317
- 2. Port the idea into OUR architecture; never transliterate Python.
318
- 3. Benchmark before/after on THIS machine; keep only wins (burst decode died
319
- here). Wall-clock metrics only.
320
- 4. Numeric features get Lab gates + kill switches; serving features get
321
- effective-scheme keying; nothing touches the L1/L2 contracts.
322
- 5. Verify the served model id before trusting any bench.
323
-
324
- ## 7. Qwen3.8-27B research program
325
-
326
- Josh requested a complete inference optimization campaign on 2026-09-04.
327
- Optimize useful completed work at a measured quality and memory budget.
328
- The deliverable is a frontier of configurations, with a reason
329
- to keep or reject every investigated method; every number records the
330
- host/chip/RAM it was measured on. A smaller artifact, a faster
331
- microkernel, and a higher draft acceptance rate are intermediate results.
332
- Each must survive the full application measurement.
333
-
334
- Single-request performance is a primary acceptance target alongside aggregate
335
- serving. Use the existing `scripts/bench-serve.ts all` workload, which replaced
336
- the root `benchmark.sh` in `7d81462`: sustained decode, cold and cached TTFT,
337
- 1k and long-context prefill, decode at context, restart reuse, sampled RSS and
338
- load/readiness. Its prefill rate includes the work before the first streamed
339
- token; keep pure native prefill timing separate. A short-prompt TTFT gain does
340
- not establish a 1k/long-context gain. Record MLX active/peak allocations
341
- separately from sampled RSS, which does not account for all GPU memory.
342
-
343
- Preserve the refactor's request, completion, graph and session contracts.
344
- Keep numerical dispatch and resource handling in backend/model operations;
345
- HTTP parsing must not select kernels. Add an abstraction only when a retained
346
- change needs it. Remove closed experimental helpers after documenting their
347
- findings, and reject extra production caches or dispatch branches without a
348
- complete-request benefit.
349
-
350
- This program includes new weight formats, custom Metal kernels, fusion,
351
- unrolling, alternate algorithms, and deterministic replay without verification.
352
- It supersedes the older weights-leg restriction against new qmm kernels for
353
- this campaign. Numerical changes retain the repository's L1/L2/Lab contracts.
354
- The weight recipe remains in [turboquant.md](turboquant.md), cache design in
355
- [kv-cache.md](kv-cache.md), and replay/speculation design in
356
- [speculative-decoding.md](speculative-decoding.md). PLAN owns open status.
357
-
358
- ### 7.1 What the initial audit establishes
359
-
360
- The local artifacts select the dense `qwen3_5` graph: 64 layers, three
361
- GatedDeltaNet layers followed by one full-attention layer per group of four.
362
- Hidden width is 5120; MLP width is 17408. There are 192 MLP matrices.
363
- Full attention has 24 query heads, four KV heads, and head dimension 256.
364
- GDN has 16 key heads and 48 value heads, both with dimension 128.
365
- These are config/header observations, not measured shader dispatches.
366
-
367
- The packed Q3 metadata contains duplicate module aliases. Counting config
368
- entries reports twice the actual trellis matrix count. The new
369
- `scripts/bench/model-inventory.ts` counts tensors present in shard headers,
370
- groups matrices by role, logical shape, bits, group size and coding axis,
371
- and includes scales/biases in matrix storage. Its matrix bpw denominator is
372
- explicit; it does not claim whole-model bpw or resident memory. It does not
373
- read or hash weight payloads. Sidecars and MTP companions require their own
374
- inventory. Raw inventories and source pins go under `reports/qwen38-rd/`.
375
-
376
- The source inspection found these starting points:
377
-
378
- - `TrellisLinear.forward` uses packed matvec for flattened M ≤ 4 and dense
379
- expansion plus stock matmul above it. Prefill currently evaluates each
380
- projection, and `Qwen35Model.forwardLayers` evaluates cache outputs per
381
- layer, to bound live buffers. Removing these barriers without replacing
382
- their memory bound can recreate the OOM already being fixed.
383
- - Decode defaults to trellis variant 6. It computes f32 code×scale, whereas
384
- expansion rounds to bf16. A trace across M=4/5 therefore crosses both a
385
- performance boundary and a numerical boundary. Variant 4 has deliberately
386
- wrong numerics and is only a diagnostic cost floor.
387
- - Trellis dispatch hard-codes 128 threads, four SIMD groups and 128 scatter
388
- splits. Gate/up fusion requires compatible geometry. These are parameters
389
- to measure per chip and bit allocation, not universal optima.
390
- - `GatedDeltaNet.forward` separately dispatches convolution, SiLU, q/k norms,
391
- q/k scaling, gate computation, recurrence and gated output normalization.
392
- Its recurrence already keeps state in registers across sequence positions.
393
- - Full attention separately applies the output sigmoid and multiplication.
394
- Any fusion must reproduce the existing intermediate rounding to retain L1.
395
- - The existing `__deltaProf` instrumentation calls `evalAll` between stages.
396
- It is useful for isolation and changes execution overlap. Its times cannot
397
- be summed into a claimed production speedup.
398
- - Strict fill already uses `policy: "assert"`: no verification/readback in
399
- normal operation. It advances hidden states and all caches for the span,
400
- skips intermediate vocabulary heads, and discards an in-flight sample.
401
- The source still pays that discarded sample's scheduled work.
402
- - MTP is an optional, previously losing 27B arm. See the actual off/on
403
- experiment in speculative-decoding section 4.4. High acceptance never
404
- established a Qwen throughput win.
405
-
406
- The initial CPU inventory covers the locally available 27B artifacts. The
407
- first benchmark preflight refused the occupied M4. Subsequent native controls
408
- and candidate timings are diagnostic; the quiet HTTP baseline remains open.
409
- Environment details,
410
- including the different installed OptiQ versions, belong in
411
- [environment.md](../reference/environment.md).
412
-
413
- #### Refactor review: main at `673b43f` (2026-09-05)
414
-
415
- The 35 commits after `6d45ca1` merge the interface-based engine refactor.
416
- Its implementation and acceptance record are in
417
- [engine architecture §12.13](unified-engine-frontier-plan.md#1213-implementation-status-2026-09-05).
418
- They change the execution paths to inspect and the way we register candidates;
419
- they do not establish a new 27B performance baseline. The repeated upstream
420
- HTTP comparisons used MiniCPM5/Gemma e4b on a loaded M1 Max. The designated
421
- 27B quants, quiet performance and second-machine acceptance remain open.
422
- Upstream did not change `qwen3_5.ts`, `trellis-linear.ts` or `qwen3-delta.ts`
423
- in this merge. Retain the existing quant-quality controls and negative MTP
424
- result, then remeasure the complete serving path at the new revision.
425
-
426
- The M4 Pro audit now uses isolated, unmodified `6d45ca1` and `673b43f`
427
- checkouts. Their MLX binding and Qwen/Trellis numerical source blobs are
428
- identical. Six fresh-process native AB/BA pairs hold Bun, artifact, variant 6,
429
- greedy settings and a bounded prefill policy fixed. All warmup and measured
430
- IDs agree at 6/128/512 prompt tokens, every worker exits cleanly, and both
431
- source snapshots stay fixed. Native TTFT, complete-request timing and memory
432
- are approximately flat; this provides no evidence of a native regression on
433
- those workloads. Six serial HTTP process pairs also preserve every response,
434
- token count and finish reason, with fixed sources and clean shutdowns. TTFT,
435
- complete-request time and sampled peak RSS are approximately flat. Telemetry
436
- confirms the serial executor. Six additional default-scheduler pairs also
437
- preserve every response, with fixed sources and clean shutdowns. Per-request
438
- telemetry proves that these requests enter the scheduler. Complete-request
439
- timing is flat or slightly lower after the refactor, decode timing is flat,
440
- and sampled peak RSS is close. These controls provide no evidence of a
441
- refactor slowdown on the measured native or serving workloads. Both historical
442
- revisions run unmodified; no memory-fix overlay was needed for these bounded
443
- requests. Prompt/SSD caches are disabled throughout. Cached, sustained-pressure
444
- and second-machine acceptance remain separate checks.
445
- Evidence: `refactor-fixed-kernel-audit-plan.json`, `refactor-native-paired.json`
446
- and `refactor-native-paired-review.json`, plus
447
- `refactor-http-paired-{serial,default}-review.json`, under `reports/qwen38-rd/`.
448
-
449
- The refactor is completed infrastructure for this performance campaign.
450
- Its unrelated interface and product-acceptance work stays in its own program.
451
- Use the new seams to isolate the expensive computation, then measure whether
452
- a replacement pays off. The plan changes in five places:
453
-
454
- - **R0 follows the current execution path.** Freeze the merged source plus local
455
- diff, then run `tests/parity/qwen-quant-engine.test.ts` separately for each
456
- exact artifact via `MLX_BUN_QWEN_QUANT_PATH`. Follow with same-artifact
457
- serial/default/oracle controls. Use the same memory safeguards on any old/new
458
- revision comparison; the unpatched packed-prefill OOM path is not a viable
459
- baseline. Historical reports retain their original source identity.
460
- - **Register kernel candidates through the model implementation registry.**
461
- `model/implementation.ts` selects the declared graph/loader/loop and refuses
462
- missing or incompatible implementations. Give a changed graph, layout or
463
- method an explicit identity and compatible state/codec ABI. Verify the
464
- selected registration in every benchmark; no silent fallback arm.
465
- - **Profile the new lifecycle as well as the kernels.** Shared prefill now
466
- uses `inference/prefill.ts` and `backends/mlx/prefill.ts`; native serial
467
- ownership lives in `backends/mlx/serial-executor.ts`. Session demand,
468
- resolved policy, leases, snapshots and readback cleanup are part of the
469
- measured path. Shared prefill extraction does not implement B-wide prefill.
470
- - **Preserve bounded memory while tuning.** Local projection/cache evaluation
471
- barriers remain. The local serial headroom guard now enters through the MLX
472
- binding after cache acquisition and restores its previous model hook on
473
- every exit. SSD tensor steps share the gateway lease and pending writes drain
474
- before serial generation. Test failed demotion, cancelled replay and retained
475
- checkpoints before changing those boundaries in R2/R16/R17/R22.
476
- - **Replay and MTP must pass resolved-policy gates.** The new speculative
477
- bindings and rollback ownership are correctness infrastructure. They are not
478
- evidence of faster MTP. Confirm strict fill is active under the captured
479
- execution policy and that checkpoint identity includes that policy before
480
- timing R15. Keep MTP off in the initial controls.
481
-
482
- The earlier M4 DeltaNet discrepancy is resolved by an explicit pinned-oracle
483
- replay on unchanged inputs. Bun and Python match exactly; the old fixture
484
- differs at one output. The regenerated fixture records provenance and exact
485
- recurrent-state hashes, with no tolerance change. See
486
- [environment.md](../reference/environment.md) for the evidence and command.
487
- The model-free checkpoint passes with the experimental kernels and replayed
488
- fixture. Quiet application and full-model same-machine oracle acceptance
489
- remain open.
490
-
491
- The native control worker now freezes prompt token IDs for both engines and
492
- records the configured plus tokenizer EOS policy, fresh-cache wall time,
493
- TTFT, actual outputs and peak memory. Repeated short-prompt controls on the
494
- flagship, compact and RTN4 affine artifacts reproduce the oracle's greedy
495
- outputs. Their original timing comparison had unmatched wiring: the Python
496
- worker omitted mlx-lm's usual wired scope. That worker is corrected and
497
- matched-wiring timing controls must be repeated. Raw paired reports live in
498
- `reports/qwen38-rd/native-affine-paired/`; their residual-swap preflight fails,
499
- so they establish neither a quiet serving baseline nor full logit parity.
500
- The longer flagship prefill completed its warmup but crashed in the measured
501
- Bun request. Native exception tracing confirms a Metal OOM, also reproduced
502
- in the Python worker with its usual wired scope. Clearing the Bun allocator
503
- cache at request entry does not fix it. Both workers complete repeated
504
- requests with chunk size 512 and identical observed tokens. Chunking changes
505
- the numerical graph, so this does not prove identity against chunk size 2048.
506
- These direct workers bypass serving admission and pressure safeguards; their
507
- failures do not establish a regression in the repaired serving path. Evidence:
508
- `reports/qwen38-rd/native-memory-ledger.json` and `native-memory-chunk512-screen/`.
509
- Remaining quants and packed controls are separate cells. See
510
- [benchmark tooling](../reference/benchmarks.md) for commands.
511
-
512
- ### 7.2 Freeze the controls and workload matrix
513
-
514
- Start with packed Q3, the affine flagship, plain RTN4, compact affine, and
515
- published OptiQ. Retain the down-input-axis and unrotated artifacts as known
516
- quality-failure controls. Inventory the fake-quant and carrier artifacts,
517
- but do not load them on a machine where the full working set cannot fit.
518
- The bf16 teacher uses the existing streamed KL procedure on these Macs.
519
- Test every available artifact once; expand expensive sweeps around survivors.
520
-
521
- | axis | cells and controls |
522
- |---|---|
523
- | Stack | Same affine snapshot on mlx-bun serial and pinned mlx-lm first; default scheduler separately. Packed trellis has no stock mlx-lm loader. Its carrier is a different precision and footprint. vLLM-Metal is a same-MLX comparison where the artifact is supported; llama.cpp/GGUF is a separately qualified ecosystem comparison. |
524
- | Weights | Existing artifacts first; affine 2/3/4/5/6/8-bit with supported group sizes 32/64/128; mixed allocation; rotated/plain RTN and calibrated recipes; trellis k2/k3/k4 mixtures and the Q5 2.75 budget; supported mxfp4/nvfp4; new codes or layouts after microkernel evidence. Do not equate nominal bits with total bytes. |
525
- | Context | 128, 1k, 4k, 8k, 16k and 32k prompt tokens; 64k and larger only after a measured memory projection. Decode at each depth, without generating an entire long context to establish it. |
526
- | Prefill | Chunk sizes 128/256/512/1024/2048, plus unsplit only when it fits. Test a partial final chunk, cached suffixes, and the one-token tail convention. |
527
- | Output | 256 generated tokens for screening, plus a sustained 1024-token cell for finalists. Record actual counts, EOS and finish reasons. Never score early EOS as faster completion of the same task. |
528
- | B and M | B=1 serial control; scheduler concurrency 1/2/4/8 as memory permits. Kernel M=1/2/3/4/5/8/16/32/128/512, including B×sequence products with the same M but different cache semantics. |
529
- | KV | bf16, affine KV8/KV4, then TurboQuant k8v3 and measured alternatives. GDN state is a separate allocation. Verify the active codec, bytes and dispatch; RSS is insufficient. |
530
- | Work | Plain text, long reasoning, code generation/editing, multi-turn tool sessions, structured output, raw completions including the EOS-cliff items. Screen text first; finalists also cover repeated images and short video. |
531
- | Reuse | Cold process, process-warm with cold prompt, RAM prefix hit, SSD restore, exact resumed generation and edited-prefix miss. Pin cache budget and checkpoint policy. |
532
- | Replay/spec | Fill off baseline; strict no-verification fill; echo separately; MTP off/on only after head/verify economics. Unsupported combinations get a reason, not a silently inactive arm. |
533
-
534
- Freeze prompt token IDs, tokenizer/template hashes, thinking mode, tools,
535
- stop policy, sampler settings, context and output budgets. Use the same
536
- prompt and initial cache state within each pair. Greedy engine tests and
537
- representative stochastic serving tests answer different questions.
538
-
539
- Record source commit plus source diff hash, model revision and shard content
540
- hashes or existing trusted manifests, quantization map, compiled native library
541
- and metallib hashes, Python packages, Bun, OS, chip, RAM, wired limit, disk,
542
- power and thermal state. Hash large payloads outside timed runs. A matching
543
- config hash does not prove identical weights. Keep pinned-oracle comparisons
544
- separate from an isolated newer-MLX experiment; never upgrade the oracle in place.
545
-
546
- ### 7.3 Account for the complete graph
547
-
548
- Generation and serving each need a measured baseline and acceptance result.
549
- Native timing covers model computation, generation-loop scheduling and state
550
- cleanup. HTTP timing additionally covers preparation, admission/queue wait,
551
- cache lookup/restore, transport and stream completion. Measure cold prompts,
552
- RAM hits, SSD restores, edited prefixes, concurrent requests, disconnects
553
- and continued tool sessions. Keep per-request TTFT, stream gaps, complete
554
- request latency and aggregate throughput; a burst of SSE chunks is not a
555
- sequence of individually timed model tokens. Attribute the server overhead
556
- using request traces and matched native work, accounting for cache, batching
557
- and sampler differences before subtracting timings.
558
-
559
- Tune operations by their contracts, not by the model name. Each candidate
560
- records supported shapes, dtypes, strides, quant layout, reduction/rounding
561
- order, state ownership, hardware and workspace limits. Compare applicable
562
- algorithms and tune dispatch across those regimes. Retained kernels belong
563
- in the shared operation layer; model code selects them only when the
564
- contract holds and retains a tested fallback. Other models using that
565
- operation need their own call-site and full-model gates. A winner on this
566
- Qwen/M4 shape is evidence for that cell, not a universal best kernel.
567
-
568
- Use the knowledge graph to discover definitions, then follow the actual
569
- implementations and MLX/Metal dispatch. The static index sometimes resolves
570
- generic `forward`, `state` and `dispose` methods to unrelated classes. It is
571
- a navigation aid; runtime traces establish the executed graph.
572
-
573
- | stage | local entry points and work to account for |
574
- |---|---|
575
- | Request and admission | `serve/request-prep.ts`, `chat-stage.ts`, `session-completion-engine.ts`, `generation-gateway.ts`, `engine/session.ts` and `execution-coordinator.ts`: tokenization, demand, queue/lease wait, resolved policy, actual lane and admission. |
576
- | Model and method binding | `model/implementation.ts`, `backends/mlx/model-serving.ts`, `graph.ts`, `autoregressive.ts` and `serial-executor.ts`: exact registration, captured runtime, hidden-state/logit selection, state ownership and native execution. Trace the selected method rather than assuming every registration uses the compatibility binder. |
577
- | Prefill scheduling | `inference/prefill.ts`, `backends/mlx/prefill.ts` and `batch-group.ts`: shared chunk/tail/snapshot decisions, cache evaluation, maintenance, temporary disposal and scheduler yields. Distinguish shared scheduling from B-wide kernels. |
578
- | Embedding and output | `qwen3_5.ts`, `gemma4-base.ts`: embedding gather/dequant, final norm, untied vocabulary projection, dtype casts, sample/logits processors and host token readback. Include both embedding and head storage. |
579
- | Every layer | `Qwen3Layer.forward`: input/post-attention RMSNorm and residual adds. Count each dispatch, view, materialized copy and temporary. |
580
- | GDN projections | `GatedDeltaNet.forward`: qkv, z, a, b and output projections, including small head projections often missed by MLP-only profiling. |
581
- | GDN convolution | Prefix concat, depthwise conv, SiLU, tail copy, state lifetime and update; distinguish S=1 from prefill. |
582
- | GDN recurrence | `qwen3-delta.ts`: q/k normalization/scaling, computeG, sigmoid beta, scan, f32 state reads/writes, gated normalization and speculative prefix replay. |
583
- | Full attention | q-plus-output-gate projection, k/v projections, q/k norms, reshape/transpose, RoPE/mRoPE, cache update, SDPA dispatch, output gate and o projection. |
584
- | Quantized attention | `quantized-sdpa.ts` and `turboquant/`: quantize, pack, gather/dequantize, tile attention, rotations and reductions. Trace the selected branch and its masks. |
585
- | MLP | Affine QMV/QMM; trellis reduce/scatter/expand/fused gate-up; split-K partials, final sum/cast, SwiGLU and down projection for all 192 matrices. |
586
- | Generation loop | `generate.ts`, `backends/mlx/request-policy.ts`, `engine/resources.ts`, `mlx/ops.ts`, `mlx/ffi.ts`: graph construction, compile caches, async/blocking eval, pending sample and readback ownership, cancellation, disposal and memory cache management. |
587
- | Reuse and persistence | `prompt-cache.ts`, `kv-store.ts`, `ssd-cache.ts`: hashes, snapshots, state copies, cache-owned views, disk stalls, generation-lock contention and cancellation. |
588
- | Optional paths | `spec/serve-loop.ts`, `qwen-mtp-source.ts`, `fill/*`, batch scheduler, grammar sampling, vision tower/merger and image feature reuse. Activate and trace each separately. |
589
-
590
- For each exercised regime export the MLX graph before materialization and
591
- capture a warmed Metal trace. Use production scheduling for attribution;
592
- profiled/debug captures are never the reported timing run. MLX documents
593
- graph capture and source-labelled debug builds in its
594
- [Metal debugger guide](https://ml-explore.github.io/mlx/build/html/dev/metal_debugger.html).
595
- The installed mlx-c exports `mlx_export_to_dot(FILE*, mlx_node_namer,
596
- mlx_vector_array)`; its header and dylib symbol were checked without loading
597
- MLX. The Bun wrapper still needs that graph-export binding. Metal capture already
598
- exists as `metalCapture(path, fn)` in `src/mlx/metal-kernel.ts`, bound to
599
- `mlx_metal_start_capture`/`stop_capture`. Reuse it with
600
- `MTL_CAPTURE_ENABLED=1`; warm first, then evaluate outputs and cache state
601
- inside its synchronous callback so the capture contains executed work.
602
- Use Instruments for host/encode timing and counters alongside the capture.
603
-
604
- Export each region before its existing evaluation barrier. A graph exported
605
- only after the full forward can omit already-materialized projections and
606
- earlier prefill chunks. Join the fragments using named tensor/state edges and
607
- an explicit barrier ledger; do not remove the memory bounds to obtain a larger
608
- graph. Compiled/custom operations also require their source-level subgraphs
609
- and Metal pipelines in the coverage record.
610
-
611
- Each kernel row records caller, shader/pipeline, shape, strides, dtype,
612
- quantization, grid/threadgroup, registers/spills where tooling exposes them,
613
- threadgroup memory, dispatch count, GPU duration, logical read/write bytes,
614
- intermediate allocations and synchronization edges. Use counters to distinguish
615
- bandwidth, instruction throughput, latency and occupancy limits. Logical
616
- bytes divided by time is not a measurement of DRAM traffic.
617
-
618
- Cover all shader dispatches, graph nodes and explicit host/GPU waits in every
619
- selected regime. Group identical shapes for tuning, but retain layer counts
620
- and call-site mapping. Reconcile GPU intervals and host gaps with end-to-end
621
- wall time; investigate an unexplained remainder above 5%. Overlapping kernel
622
- times must not be added as though they were serial wall time. Untested branches
623
- remain marked untested.
624
-
625
- Microbench both dependent repeated work and independent work with production
626
- pipeline depth. Warm compilation, evaluate outputs and state, then time batches
627
- of operations with one final synchronization. Avoid an `eval()` per tiny op
628
- unless explicitly measuring sync overhead. Check against the real forward:
629
- constant-input reuse, cached expansions or dead graphs can create false wins.
630
-
631
- ### 7.4 Experiments, in execution order
632
-
633
- This is the initial search set. Each row expands into single-variable trials
634
- with its source reference, gate, raw result and stopping reason in the run
635
- ledger. A candidate's priority changes when the measured graph changes.
636
-
637
- | ID | experiment | measure and deciding condition |
638
- |---|---|---|
639
- | R0 | Exact artifact and execution controls for performance | Freeze `673b43f` plus the integrated local diff; matched token IDs, active graph/method/quant, raw timings and actual memory. Use relevant numerical and lifetime gates; the wider refactor acceptance program is separate. The M4 DeltaNet golden cell is resolved (§7.1; environment.md). |
640
- | R1 | Packed prefill tile decode plus matmul | Decode a tile into registers/threadgroup storage and consume it with supported Metal matrix operations. Compare with bounded dense expansion. Win must lower TTFT without a larger peak live working set. |
641
- | R2 | Bounded expansion scheduling | Compare per-projection, per-layer and bounded groups of projections; include cache outputs in dependencies. Test async evaluation and explicit memory budgets. A removed wait is a win only if memory lifetime stays bounded. |
642
- | R3 | Axis-0 scatter layout and split-K | Sweep splits 16/32/64/128/256, lane/output ownership, row tiling, vector loads and split-reduction fusion. Preserve the rotated coding axis. Include partial-buffer traffic and final reduction. |
643
- | R4 | Axis-1 reduce and gate/up fusion | Sweep 64/128/256 threads, rows per group, run unrolling, accumulator count and fused/separate gate-up. Inspect spills and occupancy; tune mixed-k eligibility rather than forcing incompatible fusions. |
644
- | R5 | Decode primitive | Compare precise/refined reciprocal, existing f32 variant, bf16-rounded reference, compressed/half LUT, hybrid lookup/computation and alternate computed codes. Exact rewrites keep identical decoded weights; changed codes need a new artifact and quality gate. |
645
- | R6 | Offline repacking without re-quantization | Tile/interleave code words and scales to make down-proj reads coalesced; optional expanded state-window indices trade bytes for ALU. Prove all reconstructed weights identical before model measurements. |
646
- | R7 | Small-M packed kernel | Reuse each decoded weight across 2/3/4/5/8 input vectors. Measure the M=4/5 boundary, fill spans and MTP verifies. Tune crossover by chip, shape, k and dtype, including temporary memory. |
647
- | R8 | Fused GDN conv/state/SiLU | Specialize the short convolution, update the state tail in the same dispatch, preserve the oracle's intermediate rounding. Compare vLLM-Metal's fused implementation; no blanket claim that it is L1-equivalent. |
648
- | R9 | GDN norm, gates and recurrence | Fuse q/k scaling into normalization, combine gate math where legal, unroll Dk loops, test layout/TG_DV, register-resident state and output norm/gate fusion. Validate f32 recurrent state, not just next-token logits. |
649
- | R10 | Parallel/chunkwise GDN prefill | Compare the sequential scan with chunkwise matrix formulations, scan decompositions and recomputation/workspace tradeoffs. Investigate CUDA CuTe/FLA algorithms; re-derive for Metal. Different reduction order is a Lab candidate unless exactness is proven. |
650
- | R11 | Affine QMV/QMM and native builds | Real Qwen shapes at every available bit/group size; compare current binary, newer MLX and selected backports, plus llama.cpp Metal tiling. Keep L1 against the matching oracle build. |
651
- | R12 | Norm/residual/activation/projection fusion | Enumerate producer/consumer pairs throughout the graph, including full-attention output gating and compatible QKV or GDN projections. Measure copy cost, register pressure and changed reductions. Older CPM5 fusion losses do not settle Qwen trellis. |
652
- | R13 | Attention and KV | Stock SDPA dispatch, tiling, grouped-query reuse, fused KV append/quantize, direct attention over compressed KV, mask specialization, RoPE fusion and paged versus contiguous storage. Measure quality, TTFT and decode by depth. |
653
- | R14 | Vocabulary head and sampler | Last-position-only projection, exact fused matvec/argmax for eligible greedy requests, GPU logits processors, reduced readbacks and structured-output singleton runs. Head elimination must respect logprobs and sampling contracts. |
654
- | R15 | Deterministic no-verification replay | Follow section 7.5. Improve proven coverage and span execution economics; report wall time and output identity independently. This is a first-class track ahead of speculative drafter training. |
655
- | R16 | MLX graph and loop | Use model-owned graph/method bindings for compiled regions, stable buffers/shapes, graph replay, cache donation, allocation removal, bounded device-side chaining and host/GPU overlap. Measure session/lease/readback costs without adding per-op evals. Preserve cancellation and ownership gates. | | | | Early-output native, HTTP, cancellation/overlap and cached/SSD acceptance is complete; see benchmarks.md for monitored repeats and activity limits. The MLX 0.32.2 submission screen is complete: retain upstream startup defaults, with the measured M4 Llama override available explicitly. The current native API has no model-scoped setter; revisit integration if that interface becomes available. See benchmarks.md for the cross-model results and activity records.
656
- | R17 | Hybrid prefix and recurrent state reuse | Exact prefixes, semantic anchors, page/block storage, compact active-state updates and checkpoint cadence. Test mixed prompt edits and cancellation; no KV-only hit that loses the corresponding recurrent state. |
657
- | R18 | Scheduler | Solo latency, actual B-wide prefill, continuous batching, chunked-prefill/decode interleaving and shape buckets. Report per-request latency and aggregate throughput; one cannot substitute for the other. |
658
- | R19 | Weight-quality allocation | Measured latency-aware allocation across MLP, attention, GDN, embedding and head; GPTQ/LDLQ calibration and damping; QTIP/YAQA rounding; group size, k, L, block length, rotations and sensitive-layer exceptions. Optimize quality/bytes/time together. |
659
- | R20 | MTP economics | Off versus gamma 1/2/3/4 with a compatible head; head quantization, bounded adaptive gamma, verification cost, state replay and peak residency. Native MTP's previous loss is the control. Accept-rate improvements alone fail. |
660
- | R21 | Other exact speculative sources | Prompt lookup, n-grams, suffix reuse and smaller draft models; grammar-aware proposals. Include target verification and rollback cost. This is separate from proven assert replay. |
661
- | R22 | Residency and shared memory | Weight loading, mmap/page alignment, wired-budget scopes, allocator cache, copy elimination and snapshot ownership. CPU work shares memory bandwidth with the GPU; overlap is measured, not presumed free. |
662
- | R23 | Media and task completion | Image/video tower, preprocessing, encoder feature cache and merger, plus tool streaming, checkpoint stalls and reconnects. Finalists must improve the actual agent session, not only synthetic decode. |
663
- | R24 | Larger departures | Learned/codebook quantization, sparse residual/outlier correction, activation quantization, pruning, layer skipping, low-rank approximations, QAT/distillation and alternative drafters. First estimate kernel support, quality, training memory and maximum possible benefit; only feasible candidates advance to bounded experiments. |
664
-
665
- For every row first derive its maximum possible end-to-end gain from the
666
- observed critical path. If a part occupies fraction f and could become s
667
- times faster, the serial approximation is `1 / (1 - f + f/s)`; account for
668
- overlap separately. A poor bound can close a candidate for this workload,
669
- provided its inputs and assumptions are recorded. A previous negative result
670
- on another chip, format or batch shape cannot close the current cell.
671
-
672
- ### 7.5 Deterministic replay without verification
673
-
674
- The intended fast path is to emit a known span, run one state-advancing append,
675
- and resume prediction at its end. Normal serving performs no token verification
676
- for an asserted span. Correctness audits are separate runs and are not part of
677
- that timing. The implementation details and contract now live in
678
- speculative-decoding section 7.4.
679
-
680
- Inventory candidate spans by tool schema, template, parser state and actual
681
- token boundaries. Separate a unique continuation under enforced constraints,
682
- a deterministic application transform, an exact cached continuation under the
683
- same state/policy, and a merely frequent continuation. Repeated text or a
684
- temperature-zero model is not by itself proof that a suffix is known.
685
-
686
- Screen the existing strict rows first. They currently use a suffix match,
687
- so test triggers inside quoted tool syntax, code blocks, prose and prior roles.
688
- Exercise shared tool-name prefixes, multiple calls, optional/extra keys,
689
- `additionalProperties`, escaped values, stop/EOS within spans, whitespace
690
- merges and non-ASCII tokenization. Template token containment establishes a
691
- possible serialization; the 27B output gate establishes observed agreement.
692
- A universally valid claim needs a rule that enforces the unique continuation.
693
-
694
- The existing strict weights test can now select an exact artifact using
695
- `MLX_BUN_TEST_FILL_MODEL`. Run it on the flagship and packed Q3, then expand
696
- to all retained quants and a frozen adversarial/real-session corpus. Compare
697
- every emitted token, stop decision, KV offset and subsequent teacher-forced
698
- logits/state. Require nonzero fills. Keep a held-out set of sessions unused
699
- while designing the rows. A passing small regression test is not a proof for
700
- all possible prompts.
701
-
702
- Then optimize the actual mechanism: remove redundant in-flight vocabulary
703
- work where pipeline ordering allows it, combine adjacent determined spans,
704
- cache compiled schema plans by exact tokenizer/template/tools identity, and
705
- choose append chunking from the packed M curve. Strict fill currently excludes
706
- batch placement, grammar, quantized KV, media, mounted drafts, logprobs and
707
- fixed seeds through its eligibility checks. Extend one combination at a time
708
- after proving state and sampler behavior. A mounted draft must not silently
709
- disable the arm being called a fill benchmark.
710
-
711
- Per event record available span length, injected length, independent agreement,
712
- append time, vocabulary projections avoided, wasted scheduled samples and
713
- resume cost. Per session record task outcome, TTFT, time to first tool call,
714
- emitted tokens, prediction steps, total GPU work and wall time. Disable
715
- `MLX_BUN_FILL_TRACE` for timings: its per-position vocabulary head/readback
716
- reintroduces work that production assert skips. All-assert acceptance counters
717
- are not a verification success rate.
718
-
719
- The optimistic saving at fill fraction f is bounded by the work actually
720
- removed. Even `1/(1-f)` assumes zero append cost and no other bottleneck.
721
- Filled positions still traverse the state-update graph. An emitted rate above
722
- a one-token-per-forward estimate shows amortization; it does not show that
723
- those positions never passed through model layers.
724
-
725
- ### 7.6 MLX and Metal opportunities, with outside implementations
726
-
727
- Start with algorithms and data dependencies. CUDA warp widths, tensor-core
728
- instructions, shared-memory budgets, graph capture and PCIe transfer models
729
- do not specify a good Metal implementation. Unified memory removes some
730
- copies, while CPU/GPU contention and page residency can still dominate.
731
- MLX can defer evaluation, fuse compiled regions, reuse buffers and overlap
732
- graph construction with GPU work. Explicit evaluation can also be necessary
733
- to release large live intermediates. Each opportunity needs an ownership and
734
- memory-lifetime argument alongside its speed result.
735
-
736
- Read source at pinned revisions and attach the relevant functions to each
737
- experiment. The initial source snapshot is recorded in
738
- `reports/qwen38-rd/upstream/sources.json`; downloaded code stays in reports.
739
- Sources used for the first candidate set:
740
-
741
- | source | transferable idea and local experiment |
742
- |---|---|
743
- | [vLLM-Metal fused conv](https://github.com/vllm-project/vllm-metal/blob/327d7cb7d19f47f3e32ebb1b561b535365e2b34e/vllm_metal/metal/kernels_v2/gdn_conv1d_silu_decode.metal) | Direct state-tail convolution, SiLU and compact state output in one launch, R8. Its f32 accumulation/activation order must be checked against our bf16 intermediate. |
744
- | [vLLM-Metal lazy GDN](https://github.com/vllm-project/vllm-metal/blob/327d7cb7d19f47f3e32ebb1b561b535365e2b34e/vllm_metal/attention/impls/gdn_lazy.py) | Lazy custom operations, compact active-request states and shape-specific recurrence dispatch, R9/R16/R17. Their prefill kernel still loops across sequence positions; it is not evidence of a parallel-scan win. |
745
- | [vLLM-Metal tiled attention](https://github.com/vllm-project/vllm-metal/blob/327d7cb7d19f47f3e32ebb1b561b535365e2b34e/vllm_metal/metal/kernels_v2/pagedattention_tiled.metal) | Paged variable-length attention and grouped-query reuse, R13/R18. M5 NAX work is a separate hardware arm, not an M1/M4 capability. |
746
- | [vLLM Qwen GDN](https://github.com/vllm-project/vllm/blob/6cbb3c154ef1449d2b3c9131a237f36faa695734/vllm/model_executor/layers/mamba/gdn/qwen_gdn_linear_attn.py) | Fused decode and chunkwise prefill are separate regimes. Inspect gates, normalization and state layout, then derive a Metal implementation, R9/R10. |
747
- | [vLLM hybrid cache design](https://github.com/vllm-project/vllm/blob/6cbb3c154ef1449d2b3c9131a237f36faa695734/docs/design/hybrid_kv_cache_manager.md) | Cache groups, prefix intersections and recurrent-state constraints, R17. Paging the 16 attention layers alone does not solve the 48 GDN layers. |
748
- | [vLLM graph execution](https://github.com/vllm-project/vllm/blob/6cbb3c154ef1449d2b3c9131a237f36faa695734/docs/design/cuda_graphs.md) | Distinct decode/prefill capture regimes and shape buckets, R16/R18. MLX compilation is not CUDA Graph replay; measure which host/encode work it actually removes. |
749
- | [llama.cpp Metal GDN](https://github.com/ggml-org/llama.cpp/blob/427291b5b34cd914a31b3fd3b61a68f6184f4b9f/ggml/src/ggml-metal/kernels/gated_delta_net.metal) | Compile-time dimensions, unrolled register state, transposed layout and optional recent-state snapshots, R9/R17/R20. Head mapping and scaling differ across implementations; preserve Qwen's equations. |
750
- | [MLX qmv_wide](https://github.com/ml-explore/mlx/pull/3764) | Decode a weight group once and reuse across small M, R7/R11/R20. The affine path is hardware-gated upstream; inspect the binary actually loaded. |
751
- | [MLX compilation](https://ml-explore.github.io/mlx/build/html/usage/compile.html) | Region fusion and caching, with explicit state and shape-dependent branches. Do not make the M=4/5 dispatch shapeless without proving the selected branch, R16. |
752
- | [XGrammar MLX bitmask](https://github.com/mlc-ai/xgrammar/blob/b5048784c65f70ca20bc5fb640b06c84583b7a92/python/xgrammar/kernels/apply_token_bitmask_mlx.py) | Compiled byte-to-bitmap lookup versus direct Metal bit extraction. Both avoid the current per-token CPU float-mask expansion. Compare host cost, complete sampling time, padded vocab, dtypes and lifetime; preserve additive-mask numerics, R14/R16. |
753
- | [QTIP](https://arxiv.org/abs/2406.11235), [YAQA](https://github.com/Cornell-RelaxML/yaqa-quantization) | Hardware-friendly computed/lookup code tradeoffs and improved rounding, R5/R19. CUDA speed results are hypotheses on Metal. |
754
- | [Gated Delta Networks](https://arxiv.org/abs/2412.06464) | Parallel training/chunk formulations of the gated delta rule, R10. Compare the equations and long-run state drift before a Metal implementation. |
755
- | [T-MAC](https://github.com/microsoft/T-MAC) | Activation lookup tables for mixed-precision CPU matmul, R5/R22/R24. Its bit-plane representation is not the current trellis code, and CPU work competes for shared bandwidth; test format compatibility and total wall time. |
756
- | [SGLang jump-forward removal](https://github.com/sgl-project/sglang/pull/4032) | The old scheduler's jump-forward path was removed for maintenance in March 2025. Study its grammar/state/tokenization integration for R15/R18; an old feature description or residual API is not a current runnable baseline. |
757
-
758
- Continue the source search around each measured bottleneck: FlashAttention
759
- tiling and online softmax, FlashInfer, FLA chunk algorithms, SGLang prefix reuse
760
- and structured-output jump-forward, MLX-LM/OptiQ/oMLX scheduling, and low-bit
761
- lookup methods such as T-MAC. Record a specific paper/function, hardware
762
- assumptions, local counterpart and falsifiable test before a port. CPU SIMD
763
- and GPU cooperating on shared memory are also candidates where the dependency
764
- graph permits it. No GPU-wide synchronization or persistent megakernel is
765
- assumed safe across threadgroups without a documented Metal mechanism.
766
-
767
- ### 7.7 Gates, scheduling and completion
768
-
769
- First establish trustworthy controls. Then capture the graph, run R1–R7 and
770
- R15 on the packed artifact, and R8–R14/R16 on both packed and affine controls.
771
- Use R17–R23 for full-serving improvements and interactions. Run R19 throughout
772
- the kernel work so the allocation objective uses measured latency, not bits
773
- alone. R24 advances only after a feasible memory/quality/cost screen.
774
-
775
- Use a warmup followed by at least five paired measurement blocks for an
776
- initial verdict, alternating or randomizing AB/BA within a balanced schedule.
777
- One model-owning process at a time on these Macs; restart paired server arms
778
- sequentially when both do not fit. Control cold-cache and warm-cache trials
779
- explicitly. Preserve all samples and interruptions. Do not keep retrying until
780
- a favorable result appears. Recheck residency, swap activity and thermal state
781
- between cells, and repeat finalists in a separate quiet-machine session.
782
-
783
- Estimate paired log-ratio confidence intervals with sessions/prompts as the
784
- independent units. A default speed win should exceed 3% and have a 95% lower
785
- bound above no improvement on its declared workload. Smaller repeatable wins
786
- may justify simple changes, with their uncertainty reported. Use enough
787
- requests to estimate tail latency; a handful of runs cannot establish p99.
788
- Test isolated wins together, since fusion, quant allocation, batching and fill
789
- often interact. Keep the incumbent if the combined arm regresses.
790
-
791
- L1/L2 changes pass the existing same-state oracle logit gates at matching B
792
- and machine. Trellis repacks also prove every reconstructed weight identical.
793
- Changed reductions/precision/algorithms enter Lab with teacher-forced logits
794
- and recurrent-state checks over chunk boundaries and long continuations.
795
- Evaluate actual packed serving, not only the carrier. Quantization quality
796
- uses frozen KL/ppl screens plus MMLU, templated GSM, raw GSM, code/tool tasks
797
- and the existing six-task suite. Track per-item failures and immediate EOS.
798
- Use a held-out set for finalists. Define task noninferiority margins before
799
- the trial and collect enough items to resolve them; n=50/100 is a screen,
800
- not evidence that a small quality regression is absent.
801
-
802
- Every candidate gets one outcome: repeatable win, measured loss, inconclusive
803
- with the next discriminating experiment, proven inapplicable to this hardware,
804
- or blocked with the missing resource named. Record hypothesis, baseline and
805
- candidate revisions, changed parameter, expected limiting resource, artifact,
806
- workload, correctness/quality evidence, performance distribution, memory,
807
- decision and the condition that would justify reopening it. Save raw samples,
808
- traces and commands in reports; record measured runs in the eval DB; promote
809
- only qualified numbers to [benchmarks.md](../reference/benchmarks.md).
810
-
811
- The campaign is exhausted for a declared machine/workload when every row has
812
- such evidence, all exercised graph branches are accounted for, finalists pass
813
- the combined and held-out gates, and a final source review finds no untested
814
- applicable candidate with meaningful remaining headroom. Blocked or
815
- unmeasured rows do not count as exhausted. This is a reproducible stopping
816
- rule for a finite search, not a claim that no future algorithm can be faster.
817
- §7.13 is the outcome ledger this rule requires: one row per R0–R24 with its
818
- outcome, retained flags, evidence, next discriminating step and reopen
819
- condition.
820
-
821
- The scope also includes every owned kernel and native operation used by the
822
- project's other model paths. Maintain an inventory of dispatch sites, generated
823
- specializations, dtype/shape/layout eligibility, callers, reference behavior,
824
- available workloads and measurements. Cover attention, projections, recurrent
825
- layers, embeddings, normalization, activation, sampling, masks, cache codecs,
826
- media paths and streamed experts, including graph construction and host work.
827
- Each inventory row needs an explicit result; a Qwen-only trace cannot close
828
- an operation used elsewhere. Keep unavailable-model or hardware cells visible.
829
- Run the final comparison on a quiet machine and record its host/chip/RAM.
830
- Pin source, runtime/library versions, artifacts, request settings and
831
- cache state so kernel gains are not confused with different test conditions.
832
-
833
- The final task benchmark uses
834
- [Luke's published kanban prompt](https://github.com/lukesdevlab/youtube/blob/3288d1918fa6140c10f3b2de2d37f9d717a5ab75/prompts/kanban.txt),
835
- pinned before execution (SHA-256
836
- `c40b3c8e0e4d37b316179281aafef187839df7bb0e945f5c1d0f6c5b79fbb521`).
837
- It requests a local vanilla web app with board/card editing, drag-and-drop,
838
- archive/restore, combined filters, themes and persistence. The upstream prompt
839
- asks the builder to verify through code review; independent browser evaluation
840
- happens after the agent finishes. Preserve the exact prompt in each run.
841
- The upstream repo supplies model settings but does not establish a pinned
842
- agent harness for this comparison. Record our harness and any differences
843
- explicitly; this is not a hardware-matched reproduction of a video score.
844
-
845
- Before running that final task, freeze one agent/tool interface, system prompt,
846
- dependencies, context/output/turn/time limits and seed list for every arm.
847
- Use clean isolated workspaces and identical tool access; save the full request,
848
- response, tool, usage and timing trace. Run the incumbent and final engine
849
- configurations on the same artifacts, with same-artifact MLX-LM controls where
850
- supported. Test different quants as separate quality/performance arms. Keep
851
- MTP, replay and cache policy explicit. Do not repair generated code during
852
- scoring or use final-task output to tune the candidate being evaluated.
853
-
854
- | Final task measure | Evidence and interpretation |
855
- |---|---|
856
- | Completion | All required behavior works without manual edits; report partial completion and timeouts. |
857
- | Functional behavior | Exercise edits, card/column movement, safe deletion, restoration, combined filters and reload persistence in a fresh browser profile. |
858
- | Usability | Record keyboard behavior, empty states, feedback and screenshots in both themes. |
859
- | Complete task time | Measure from first agent request to its completion, plus evaluation time separately. |
860
- | Engine contribution | Per-turn queue/TTFT/decode time, prompt/generated/cached tokens, tool round count, retries, errors and compactions. |
861
- | Resource use | Peak active/RSS/wired memory, swap activity, cache bytes and actual serving lane. |
862
- | Repeatability | All prespecified runs and seeds, including failures; compare success rate and time conditional on completion. |
863
-
864
- Source snapshots and the manifest are in
865
- `reports/qwen38-rd/lukes-kanban/`. The first attempted task is preserved in
866
- `reports/qwen38-rd/kanban-final/optimized-mtp-invalid-32k-sleep/` and excluded
867
- from completion-time claims. Its Pi profile incorrectly declared 32,768 tokens,
868
- causing premature compaction, and macOS sleep interrupted the run. The artifact
869
- declares 262,144 positions. The corrected profile derives the effective window
870
- from that metadata and the server's admission limit, recording both separately.
871
- Use Pi's standard compaction reserve and recent-history settings, hold
872
- `caffeinate -is`, and record real wall time plus active monotonic time. The
873
- original profile, traces and partial app remain available.
874
-
875
- The corrected thinking-off candidate completed generation without compaction,
876
- but failed static app acceptance: `main.js` redeclared a `let` variable and the
877
- requested README was absent. No manual edits or repair prompts were supplied.
878
- The original-source task exhausted two automatic retries during a long tool
879
- response. That run is excluded from task-time comparison because the recording
880
- proxy inherited Bun's socket idle timeout. An independent six-minute silent
881
- stream reproduces the default timeout and completes with `timeout: false`.
882
- Pi's own HTTP idle setting is now explicit. The runner also reads Pi's terminal
883
- events, because an exhausted retry can still leave a zero process exit code.
884
-
885
- Josh corrected the benchmark configuration: the task must use a named profile
886
- from Luke's `model-configs.ini`, including its sampling, context, thinking and
887
- effort settings. The agent-selected greedy configurations are invalid for this
888
- benchmark, including the later thinking-enabled attempt, which was stopped.
889
- Do not reuse their times as Luke benchmark results. The pinned prompt itself
890
- matches upstream. The profile audit resolves inherited defaults, records source
891
- hashes and rejects missing effort or changed sampling values. Context and effort
892
- differ across Luke's coding profiles. The selected section is
893
- `qwen3.8-27b-q3_k_xl-coding-128k`: 131072 context, xhigh thinking, temperature
894
- 0.6, top-p 0.95, top-k 20, min-p 0, presence penalty 0 and inherited seed 42.
895
- The task uses that exact prompt and request recipe. Its first attempt was
896
- stopped after a serving bug discarded the preceding thinking on tool turns.
897
-
898
- The MTP-prefix integration (merged in PR #47) permits Qwen uniform KV4 with start=0
899
- behind `MLX_BUN_QWEN_SPEC_KV4`. Prefill converts attention caches through
900
- `maybeQuantizeKv`; rollback binds after conversion, and prefix identity includes
901
- KV bits, group size and conversion policy. Recurrent state remains full precision.
902
- A native sampled test restores all sixteen quantized target layers plus draft
903
- state with identical continuation after forced rejected drafts. The HTTP check
904
- also preserves repeated output and acceptance decisions, with active speculation
905
- and cache reuse. The initial native coverage check failed only because its
906
- repetitive prompt accepted every draft; the forced-rejection check supplies that
907
- missing coverage. Both records remain in `reports/qwen38-rd/`.
908
-
909
- This is an explicit MLX adaptation. The target remains Josh's required packed
910
- 12 GB Trellis artifact. MLX affine KV4 group64 differs from GGUF q4_0; the single
911
- MTP-layer cache stays bf16. The corrected-history run uses the profile’s 256-token batch
912
- size for MLX prefill, bounding long-context attention workspace.
913
- `MLX_BUN_RD_CONTEXT_LIMIT` narrows the isolated server's physical admission
914
- ceiling to exactly 131072, never enlarges it. Pi uses the same context and
915
- xhigh effort. Responses run until EOS or remaining context, with no invented
916
- 16K cap. Task timing includes automatic tool use and retries; app scoring
917
- follows after inference exits. The completed retry is recorded below.
918
- Raw evidence and invalid runs remain in `reports/qwen38-rd/kanban-final/`.
919
-
920
- The paired cache currently captures prompt checkpoints only. Extending it to
921
- verified generated boundaries is still open: preserve target, draft and pending
922
- hidden alignment, and require an exact prefix of the next rendered conversation.
923
- Tool-argument serialization can change tokenization, so a completed-response
924
- snapshot alone cannot replace the earlier stable-prefix checkpoint. The uniform
925
- KV4 prefill path also retains native unfused quantized attention, which materializes
926
- query-by-context scores. Long tool-turn prefill needs its own memory and timing
927
- acceptance; decode memory alone does not establish that result. Measured task sources stay frozen while these costs are measured.
928
-
929
- The stopped profile attempt also reproduced a protocol bug. Pi returns prior
930
- assistant thinking as `reasoning`; Qwen’s template reads `reasoning_content`.
931
- Despite `preserve_thinking: true`, normalization previously dropped that history
932
- from the rendered prompt. The fix supplies the canonical alias without mutating
933
- the input or replacing an explicit canonical string. Unit tests cover tool calls,
934
- rendering and precedence. The recorded request now retains its complete reasoning.
935
- The active runner independently renders each prompt and checks its token count
936
- against engine usage. This failure remains separate from the earlier attempts
937
- that used incorrect sampling settings.
938
-
939
- The subsequent long-history HTTP gate passes with the corrected normalizer,
940
- 256-token prefill, target KV4 and MTP. Cold and restored requests preserve
941
- output and draft acceptance, including naturally rejected proposals. The
942
- corrected-history task runs with source hashes frozen and all original settings
943
- retained. Evidence: `reports/qwen38-rd/luke-history-kv4-preflight.json` and
944
- `reports/qwen38-rd/kanban-final/luke-q3-128k-xhigh-history-fixed/`.
945
-
946
- That task ended with only three app files. All prompt counts and MTP/cache
947
- checks passed, but a valid nested edit array failed in tool parsing. Qwen
948
- parameters now follow the pinned mlx-lm parser: raw entity text, with one
949
- framing newline removed at each end. Outer Qwen markup is selected before
950
- JSON repair can misread a parameter as a tool envelope. Legacy attribute XML
951
- keeps its existing decoding policy. The actual saved response now produces
952
- one intact edit call through the real tokenizer and streaming parser.
953
- Regression tests, strict-fill checks, both workspace typechecks and hygiene
954
- pass. The raw failed result and untouched app remain preserved; its numbers
955
- are in benchmarks.md. The fresh run with both fixes is preserved in
956
- `reports/qwen38-rd/kanban-final/luke-q3-128k-xhigh-tool-values-fixed/`.
957
-
958
- That run ended in a Metal out-of-memory error during the next long-history
959
- turn, before Pi finished. Completed requests kept the full rendered history
960
- and used MTP with cached prefixes. Static checks find no README. The separate
961
- browser smoke confirms basic creation but finds a blocking card-editor
962
- ReferenceError in the incomplete app. Its source is unchanged; no repair
963
- prompts were supplied. Timings, counts and memory measurements live in
964
- [benchmarks.md](../reference/benchmarks.md#fresh-pi-kanban-diagnostic-m4-pro-2026-09-07).
965
-
966
- Do not promote the isolated KV4/MTP/prefix composition or claim a successful
967
- task-time gain. Josh's known workload is roughly 100,000 generated tokens,
968
- including thinking, plus the initial prompt and subsequent tool history.
969
- Fixing only the observed failure boundary is insufficient. Start with a
970
- 110,000-token accumulated-context capacity screen, then check sustained
971
- generation, tool turns and cache reuse beyond the expected task size, within
972
- the unchanged published context settings. A short continuation at a large
973
- synthetic context is a memory screen, not proof of full task completion.
974
- The unchanged initial capacity screen finished target prefill but failed
975
- inside the first MTP draft round. Allocation traces and source hashes are
976
- preserved; numbers live in benchmarks.md. Draft prefill built a deferred KV
977
- graph across every chunk, and its pending hidden row was a view into the
978
- complete prompt buffer. The main source and isolated candidate now evaluate only draft KV
979
- at each existing chunk boundary and materialize the retained final row.
980
- Unused prefill attention/MLP outputs stay unevaluated. A focused allocation
981
- test fails before this change and passes afterwards. A separate sampling
982
- failure test exposed unowned in-flight output and logits; scoped disposal
983
- now releases them on errors as well. The small full-model comparison retains
984
- exact output tokens and MTP acceptance traces, including cached replay.
985
- The final-source native capacity screen completes repeated continuations at
986
- the larger context, preserves exact cached replay and recovers after an
987
- injected output-sink failure without additional retained request memory.
988
- Main-source ownership tests, a real-target short MTP identity gate and both
989
- workspace typechecks pass. Saved-history HTTP acceptance also passes, including
990
- the failed request, conversation growth and exact replay at the larger context.
991
- The guarded fresh Pi retry also failed with Metal out of memory, this time
992
- during sustained decode rather than the first draft after prefill. Its source
993
- and profile stayed fixed. The complete first response and its MTP acceptance
994
- trace match the preceding task; later tool results reflect their actual runs.
995
- The untouched app supplies its README but fails both the card-editor and
996
- archive-panel checks. Measurement and quality audits are preserved beside
997
- the raw result in `kanban-final/luke-q3-128k-xhigh-mtp-memory-fixed/`.
998
- This failure leaves sustained-generation acceptance open. The passing short
999
- capacity checks do not establish reliability over the full workload.
1000
-
1001
- The sustained allocation trace identifies a separate lifetime problem in
1002
- `mlx/ops.ts`: the range cache retained every distinct large `arange` for the
1003
- process lifetime. Quantized causal attention requests a new context-length
1004
- range on each verification round above the cache's minimum length. Disposing
1005
- the returned mask view did not release the cache's owner. The range cache now
1006
- limits retained array data to 8 MiB, evicts least recently used owners with
1007
- explicit disposal, and leaves oversized ranges owned only by their callers.
1008
- Repeated vocabulary and attention-layer ranges still share storage; outstanding
1009
- lazy views retain their native references after eviction. The focused allocation
1010
- regression fails before this change and passes afterwards. The full-model
1011
- sustained repeat preserves every output token and MTP acceptance decision,
1012
- with fixed sources and bounded retained allocation after model disposal.
1013
- Numbers and the single-pair timing limitation are in benchmarks.md.
1014
-
1015
- After fresh-task acceptance, screen a reusable integer position-range prefix
1016
- and the native integer `arange` path on Bun 1.4 against this bounded-cache
1017
- baseline. The current minimum cache length still rebuilds smaller attention
1018
- ranges across layers. Keep exact range/mask values, outstanding-view ownership
1019
- and the memory bound as gates; measure complete prefill and verification rounds
1020
- before retaining an allocation or dispatch optimization.
1021
-
1022
- The pinned MLX 0.32.2 source supplied a native scheduling experiment
1023
- for the three-query KV4 verification window. Qwen's 24 query heads share four
1024
- KV heads (GQA6), with D256. `quantizedSdpaUnfused` originally presented the heads
1025
- as separate broadcast batches. In `mlx/backend/metal/quantized.cpp`, the
1026
- M4-eligible affine key multiplication selects `qmv_wide`: three vectors per
1027
- threadgroup, eight reduction lanes, and a separate batch for each query head.
1028
- Its code already reuses weights across the three query positions.
1029
-
1030
- Screen pairing two query heads in the key multiplication only. Reshaping the
1031
- query from `[B,KV,6,3,D]` to `[B,KV,3,6,D]` keeps this dispatch below its matrix
1032
- threshold and keeps the native vector tile at three. The grid changes from
1033
- `(1,ceil(N/8),24)` to `(2,ceil(N/8),12)` for B=1, offering a way to change K
1034
- reuse and scheduling through native MLX operations. Restore the original score
1035
- shape before masking and softmax. This is an unmeasured hypothesis: actual
1036
- shader dispatch, layout/materialization and exact output must be checked;
1037
- source-level broadcast does not establish actual DRAM traffic.
1038
- If the paired-head screen passes, also screen groups of three heads. Its nine
1039
- query rows remain below the matrix threshold, but MLX selects five vectors per
1040
- threadgroup rather than three. That changes the compiled kernel specialization;
1041
- do not infer numerical identity from the common source body. Measure both real
1042
- strided queries and contiguous queries: `ensure_row_contiguous_matrix` may add
1043
- a copy before multiplication, and the complete attention timing must include it.
1044
- The recorded CLI selects uniform `--kv-quant 4`, which configures the unfused
1045
- MLX-LM composition through `applyDecodeRoute`; this runtime option is not an
1046
- inherited environment variable. Preserve that selection in the control. A
1047
- smaller graph experiment can reuse one materialized causal mask across Qwen's
1048
- full-attention layers: `forwardLayers` already shares a mask object, but its
1049
- causal string currently rebuilds the boolean array in each unfused attention
1050
- call. Keep the bf16 and OptiQ dispatch policies intact and measure the retained
1051
- mask's lifetime as well as complete-forward timing before retaining that change.
1052
-
1053
- The screen and full-model/HTTP comparisons are now complete. Three-head key
1054
- grouping is selected on M4 Pro for the tested B1/B2, L3, GQA6/D256,
1055
- KV4/group64, bf16/f32, N≥8192 geometry. Other geometry retains the existing
1056
- native selection. M1 grouped key scores differ, so its key geometry remains
1057
- unchanged. The permanent regression compares strided KV against the separate
1058
- head composition. Exactness, complete-forward and serving measurements are
1059
- recorded in benchmarks.md under Three-query affine attention head grouping.
1060
- The shared causal-mask experiment remains separate, unmeasured work.
1061
-
1062
- Do not apply that fold indiscriminately to the value multiplication. Its native
1063
- matrix threshold is four query rows, so the same reshape would change the
1064
- algorithm. At long context it uses `qvm_split_k`, with 32 partitions beyond
1065
- 8192 reduction elements and an explicit reduction of the intermediate results.
1066
- Preserve that partition and reduction contract in any custom scheduling arm.
1067
- The relevant implementation is `mlx/backend/metal/kernels/quantized.h` in the
1068
- pinned source. Run these experiments as separate arms against the frozen successful task's
1069
- source; require operation, complete-attention, full-model and serving gates.
1070
-
1071
- The fresh Pi retry with the bounded range cache completes under the same
1072
- published profile, prompt and settings, with source hashes frozen. Its untouched
1073
- app passes the required functional browser checks, including card editing,
1074
- combined filters, archive/restore, column controls, native card/header drags
1075
- and persistence. The README and modular plain-script entry are present. The
1076
- passing sustained replay preceded launch; all prior controls and failed tasks
1077
- remain preserved. No app code was edited and no repair prompts were supplied.
1078
- Browser checks ran after inference exited. The original intercepted-drag
1079
- probes and an incomplete mouse-drop probe remain beside the successful native
1080
- interaction checks, which deliver dragover before releasing the button.
1081
- Measured completion time, rates and memory are in benchmarks.md.
1082
-
1083
- The completed run includes Pi context compaction. Its summary request and
1084
- subsequent work remain inside task elapsed time. Pi serializes the older conversation
1085
- into a new summary prompt, so those tokens do not share the original chat's
1086
- exact prefix. Do not substitute the old KV state merely because the transcript
1087
- describes the same history. The JSON stream uses `compaction_start`; the frozen
1088
- outcome helper counts only `auto_compaction_start`. Derived lifecycle
1089
- counts now include both event names; the raw outcome and its saved helper remain
1090
- unchanged for audit. The shared helper was corrected only after the run ended.
1091
- Assess whether Pi's compaction reserve can avoid an
1092
- unnecessary summary while keeping the published context limit and sampling
1093
- settings. Check which settings the upstream protocol actually pins before
1094
- changing a client policy, and report that arm explicitly. Include context
1095
- admission, truncated responses and subsequent task quality in its acceptance.
1096
- The existing admission limit is not proof that the composed execution fits.
1097
- Generated
1098
- history checkpoints remain a separate opportunity to remove repeated prefill;
1099
- their target, draft and pending-token state must align with the next rendered
1100
- conversation prefix. For append-only caches with an unchanged codec, also
1101
- evaluate deferring the attention-KV view capture until request cleanup while
1102
- capturing the recurrent state and pending hidden row at the checkpoint. Older
1103
- KV rows remain available in the live cache; retaining a second native owner
1104
- throughout decoding can force an otherwise avoidable copy. This requires an
1105
- explicit lifetime contract, prefix availability checks, correct cleanup on
1106
- cancellation/errors, and accounting for shared backing storage. Sliding-window
1107
- eviction or requantization of older rows must disqualify that reuse. Generated
1108
- checkpoints must match actual next-request tokens; tool serialization is not
1109
- assumed identical. Keep a valid fallback checkpoint within the memory budget.
1110
- Collect matched successful original/final task-time comparisons. The completed
1111
- run establishes a usable result on this source, not an optimization percentage.
1112
- Capacity acceptance does not establish the fastest completion method. Measure
1113
- draft acceptance and verify-window attention cost at the context depths reached
1114
- late in the actual task. Compare complete request times when tuning the draft
1115
- schedule within the published profile; short-context MTP throughput cannot
1116
- stand in for those measurements.
1117
- The pinned quantized value-product dispatch makes draft depth three a concrete
1118
- next screen: its four-position target window reaches the native matrix-kernel
1119
- threshold, whereas the current three-position window uses split-K vector
1120
- multiplication at long context. Compare depths one, two and three and an
1121
- ordinary continuation at matched context, keeping the sampling recipe fixed.
1122
- This is a source-derived scheduling hypothesis, not a measured speed claim;
1123
- each window's native arithmetic, rollback, cache reuse and completed response
1124
- remain correctness and acceptance gates.
1125
-
1126
- ### 7.8 Execution log (archived)
1127
-
1128
- The chronological run log (2026-09-04 → 2026-09-08; harness preparation,
1129
- early first token, shared-M/tile/split-K kernels, graph exports and counter
1130
- calibration, MLX scheduling settings, shared affine kernels, GDN
1131
- specializations, strict fill, grammar mask, mmap loader, KV append census)
1132
- moved verbatim to
1133
- [qwen38-27b-campaign-log.md](../archive/investigations/qwen38-27b-campaign-log.md).
1134
- Every evidence filename it cites is kept there and resolves to
1135
- `reports/qwen38-rd/` on the measuring host. Outcomes, retained flags, next
1136
- steps and reopen conditions per row are in §7.13; §7.9–§7.12 stay live.
1137
- Changes that landed by default from that log are correctness or memory fixes,
1138
- not speed defaults: bounded 8 MiB range cache (§7.7), per-chunk draft-KV
1139
- evaluation (§7.7), compact state materialization through stock DynamicSlice,
1140
- SSD boundary-before-transfer fix, Qwen tool-parameter parser,
1141
- `reasoning_content` alias, EOS/finish-reason accounting, native pack 0.4.0.
1142
-
1143
- ### 7.9 Project kernel coverage
1144
-
1145
- The current AST census has 44 custom Metal kernel construction sites in 18
1146
- files, plus 12 direct compiled-function construction sites. The seven additions
1147
- since the earlier census are three paged-attention kernels, two normalized
1148
- greedy reductions, masked recurrent update and row-length-aware state replay.
1149
- Frozen source controls retain the two old-core affine kernels the
1150
- MLX 0.32.2 consolidation removed (§7.12). The initial inventory also counted
1151
- 355 calls into 162 distinct MLX C APIs; that count includes allocation,
1152
- configuration and graph operations, not native GPU kernels. Runtime
1153
- specializations still need shape, dtype, layout and stream coverage. Evidence:
1154
- `reports/prefill-observation/kernel-census.json` (current), with
1155
- `reports/qwen38-rd/project-kernel-consolidated-census.json` and
1156
- the earlier censuses in `project-kernel-inventory.json`,
1157
- `project-kernel-coverage.json`, `project-kernel-vector-expand-addendum.json`,
1158
- `project-kernel-turboquant-addendum.json`, `project-kernel-inverse-addendum.json`
1159
- and `project-kernel-wide-addendum.json`.
1160
-
1161
- | Owned kernel family | Sites | Current evidence and next coverage |
1162
- |---|---:|---|
1163
- | Packed grammar mask | 1 | Exact micro and HTTP outputs; serving timing inconclusive under external load. |
1164
- | Normalized greedy partial and final reductions | 2 | Same-machine operator and actual-model comparisons pass on both Macs; MiniCPM standard AB/BA improves throughput while packed Qwen MTP3/TQ is flat. Metadata, stochastic and custom samplers retain their prior path. |
1165
- | Direct paged-attention bf16, affine score and affine value | 3 | C5 operation/model/state and native HTTP checks pass. Recorded wins and regressions do not justify a default; block formats and attention remain optional through the cache/model interfaces. |
1166
- | Joint TurboQuant K/V decoding and selected inverse rotation | 2 | Experimental opt-in; exact operation/lifetime and R6/RTN4 integrated model gates pass on MLX 0.32.2. Integrated inverse-rotation HTTP passes six pairs per quant with decode gains in every pair; R6 complete time improves and RTN4 complete time is inconclusive. Six deferred-consumer pairs per MiniCPM/Gemma also improve complete requests on consolidated source. Combined/pressure and quiet acceptance remain. Direct packed-key attention is exact but slower. Details live in turboquant.md. |
1167
- | Flash attention forward, D, dKV and dQ | 4 | D256 alternative screen fails one KL gate; other attention shapes and backward costs remain. |
1168
- | GLM sparse-attention rank and contract keys | 2 | Both keys now use uint32 with stable score sorting. Operation and complete tiny-model state gates pass; six balanced pairs per shape improve selection latency. Real Colibri serving remains unmeasured. |
1169
- | GLM q4/q8 streamed expert gate/up and down | 4 | Synthetic resident-slot geometry screen and six balanced repeats preserve intermediate/output bytes and cleanup. BF16 timing is bimodal across identical process configurations; no geometry default retained. Attribute that variation before further timing claims. Real model and I/O overlap remain unmeasured. |
1170
- | Qwen causal convolution, SiLU and copied tail | 1 | Exact operation/model/state gates; fusion has no compelling full-model speed win. |
1171
- | Gated recurrent update, masked update and prefix-state replay | 3 | Unrolling, geometry, compilation and normalization fusion screened; full-model gains too small to retain. Masked padding and row-length replay preserve inactive state and accepted-prefix state in composed native/serving gates. Uniform state-only replay did not establish a serving win and remains unselected. |
1172
- | Qwen multimodal rotary embedding | 1 | Direct-stride fusion preserves operation/model state, but the complete-forward gain is too small to retain. Actual image/video HTTP coverage remains. |
1173
- | Trellis reduce, scatter, expand and gate/up variants | 9 | Shared rows and fusion improve measured cells. Device codebook lookup loses. A scoped threadgroup integer table improves repeated M3/4 scatter, full forwards and MTP HTTP requests with exact outputs; M1 loses and stays procedural. Scheduling and prefill controls remain. Broader bit/axis/shape/model coverage remains. |
1174
- | Trellis split-K projection and accumulation | 2 | Short-prefill model/serving acceptance; larger shapes and additional artifacts remain. |
1175
- | Trellis tiled projection | 1 | Short axis-1 tiles accepted diagnostically; larger tiles, context and memory pressure remain. |
1176
- | Trellis native-wide prefill | 1 | Reached under `MLX_BUN_TRELLIS_VARIANT=11..13`, including the current variant-13 default; variant 6 expands then uses native matmul. Matches MLX 0.32.2 small-prefill arithmetic on eligible GPUs. Operation, integrated R6 state/generation and six HTTP pairs per lane pass. Short-prefill TTFT improves; broader context and quiet acceptance remain. |
1177
- | Trellis vectorized expansion | 1 | Exact operation, full-model prefill and HTTP responses. Shorter serial and default-scheduler HTTP prefills improve; existing-suite timing mostly flat. Broader context, pressure and quiet-machine gates remain. |
1178
- | Cross-entropy forward/backward variants | 7 | All seven routes pass the vocabulary-partition screen, including 54 forced-fallback cases. The isolated fast-dispatch opportunity does not apply to the available models wired into this loss path; broader real-loss profiling remains. |
1179
-
1180
- The native-operation audit covers quantized/dense/gather matmul, SDPA,
1181
- normalization, rotary embeddings, elementwise activation, convolution,
1182
- reductions/sorts, indexing and scatter, quantization/dequantization, Hadamard
1183
- transforms, sampling, copies and cache growth. Account for compiled graph
1184
- boundaries, custom VJPs, host readbacks, allocator work and serialization.
1185
- An operation can remain native after a measured negative result; replacing
1186
- every kernel is not the exit criterion.
1187
-
1188
- An explicit codebook lookup does not improve the tested packed decode
1189
- kernels. The corrected screen preserves all 69 cases per candidate using
1190
- float32 integer values, int16 integer values or pre-scaled float32 values.
1191
- It covers reduce, both scatter layouts and fused gate/up across f32, f16 and
1192
- bf16, including the M4/5 fallback boundary. All four processes return active
1193
- allocation to zero. At the large Qwen M1 bf16 projections, even the int16
1194
- table takes 0.802 ms versus 0.331 ms for reduce, 0.747 versus 0.443 ms for
1195
- scatter, and 1.474 versus 0.615 ms for gate/up. These diagnostic operation
1196
- losses close the candidate before full-model testing. No lookup cache or
1197
- kernel is added to production.
1198
-
1199
- The first prototype changed the shared lookup table and failed dense-fallback
1200
- identity at M5/8. That fallback uses a precisely divided table, while the
1201
- packed matvec preserves the procedural decoder's multiply order. The corrected
1202
- prototype keeps the original expansion table and replaces both macro and
1203
- inline decode sites. Retain the initial failure and the corrected exact
1204
- negative result separately. Evidence is `trellis-codebook.json` and
1205
- `trellis-codebook-scoped{,-review}.json`.
1206
-
1207
- The distinct threadgroup-table follow-up leaves a narrower M3/4 scatter
1208
- candidate open. Six full-model and six MTP serving pairs preserve outputs
1209
- with small gains. Its results, unchanged-prefill controls and scope live in
1210
- [turboquant.md](turboquant.md). It does not justify a one-token decode change.
1211
-
1212
- A separate Metal constant-address-space table also loses at M1. Two balanced
1213
- pairs use the actual R6 packed projections, identical tensor hashes and the
1214
- same synthetic activation seed. A 4,096-entry int16 table nearly doubles
1215
- complete MLP latency in both orders on the M4 Pro with MLX 0.32.2. All four
1216
- workers exit normally and source hashes remain fixed. The benchmark's internal
1217
- v13-versus-v13 check does not compare output bytes across source arms, so this
1218
- is a rejected speed screen, not a correctness-qualified implementation. No
1219
- full-model run or production change follows. An earlier accidentally
1220
- overlapped pair was terminated and excluded. Evidence:
1221
- mlx-upgrade-0.32.2/trellis-constant-{screen,review,invalid-attempt}.json.
1222
-
1223
- The four streamed-expert kernels now have a synthetic resident-slot screen.
1224
- It covers Q4/Q8, bf16/f32, M1/2/4/8 and H/I=32/32 plus 6144/2048. The larger
1225
- dimensions come from the documented Colibri slot size and need confirmation
1226
- against actual artifact metadata. One, two, four and eight SIMD groups per
1227
- threadgroup preserve every gate/up intermediate and final SwiGLU output byte
1228
- in 96 candidate comparisons. All four processes return active allocation to
1229
- zero. This excludes disk I/O and full-model execution.
1230
-
1231
- Six balanced repeats at the larger dimensions preserve another 288 comparisons
1232
- across 24 fresh processes, again with zero final active allocation. The large
1233
- first-screen bf16 gains do not establish a retained geometry. Identical Q4 M2
1234
- controls vary from about 0.29 to 0.58 ms; Q8 M1 controls vary from about 0.24 to
1235
- 0.51 ms. Some candidate/control pairs reverse by nearly 2x. Float32 is much
1236
- steadier and generally flat across geometries. Attribute this bf16 timing
1237
- variation before further optimization claims. No geometry default changes.
1238
- These synthetic screens were measured on the M4 Pro 24 GB. Real Colibri serving remains unavailable;
1239
- the local GLM-5.3-Flash artifact uses a different architecture. Evidence:
1240
- `streamed-expert-screen{,-review}.json` and
1241
- `streamed-expert-repeat{,-review}.json`.
1242
-
1243
- Four identical four-SIMD-group processes with the normal-scheduling recorder
1244
- preserve all 64 cell outputs and return active allocation to zero. The bf16
1245
- timings are stable in this instrumented sample: Q4 M2 is 0.288–0.293 ms and
1246
- Q8 M1 is 0.240–0.244 ms. GPU command-span union per call is about 0.222 and
1247
- 0.177 ms respectively, with no measured gaps between command spans. This
1248
- does not capture the slow regime seen with the normal library, so it cannot
1249
- explain that variation. The recorder uses a separately built MLX library;
1250
- its wall timings cannot select the production geometry. Preserve the
1251
- inconclusive verdict until the real workload or a control captures both
1252
- regimes. Evidence: `streamed-expert-trace{,-review}.json`.
1253
-
1254
- Six balanced same-geometry blocks compare the stock library, the separate
1255
- build with recording disabled, and that build with recording enabled. All
1256
- 192 candidate comparisons preserve intermediate/output bytes and every
1257
- process releases its active allocation. The bf16 variation occurs in all
1258
- three arms. Recorder timestamps now capture both regimes: the Q4 M2 median
1259
- command span per complete operation ranges from 0.230 to 0.658 ms, and Q8 M1
1260
- from 0.177 to 0.451 ms. Each measured buffer still has sixteen dispatches for
1261
- eight complete operations. Some transitions happen within one process. This
1262
- rules out host overhead alone; command spans include waits and do not isolate
1263
- the underlying GPU cause. No geometry or library change is retained. Evidence:
1264
- `streamed-expert-library{,-review}.json` and
1265
- `streamed-expert-library-span-review.json`.
1266
-
1267
- The sparse-selection screen reduces the contract-order key from uint64 to
1268
- uint32: the above-threshold class needs one bit and valid MLX positions fit
1269
- in the remaining 31 bits. The score-ranking key is initially unchanged.
1270
- All 75 cases preserve selected positions and threshold bits, covering several
1271
- context/selection sizes, ties, signed zero and nonfinite values. Finite inputs
1272
- also match the host contract. Each case releases every active native byte.
1273
- Six AB/BA blocks at the deployed topK of 2,048 then preserve all 90 paired
1274
- cases. Median selection latency improves about 2–9%, or 28–39 microseconds,
1275
- on the M4 Pro 24 GB; every pair improves. This is the complete selection
1276
- operation, not model-generation or serving throughput. Evidence is
1277
- `dsa-order-u32-screen.json` and `dsa-order-u32-repeat{,-review}.json`.
1278
-
1279
- The pinned MLX implementation explains the crossover: uint64 sort keys use
1280
- smaller blocks, so a 2,048-key sort takes the multi-block path. It also sends
1281
- GPU `argpartition` through a full merge sort. MLX's documented stable
1282
- `argsort` permits a second reduction: retain the 32-bit descending IEEE score
1283
- key and let stability preserve ascending positions for equal score bits.
1284
- Use `argsort` explicitly for that guarantee. This preserves the existing
1285
- special-value ranking, without relying on stability from the partition API.
1286
- Primary sources are [MLX 0.31.2 sorting](https://github.com/ml-explore/mlx/blob/v0.31.2/mlx/backend/metal/sort.cpp)
1287
- and its [stable-sort contract](https://github.com/ml-explore/mlx/blob/v0.31.2/mlx/ops.h).
1288
- The combined prototype passes the same 75 cases. Six balanced blocks then
1289
- preserve all 90 paired cases and improve every pair: median selection latency
1290
- falls 10.47–15.80% across the tested context/pattern cells. Ordinary score rows
1291
- save about 48 microseconds at 2,049 positions and 218 microseconds at 262,144.
1292
- All native active bytes are released. Evidence is
1293
- `dsa-rank-u32-screen.json` and `dsa-rank-u32-repeat{,-review}.json`.
1294
-
1295
- The complete deterministic tiny-model comparison also preserves all six
1296
- teacher-forced/greedy/sampled cases at topK 1 and 2,048: every logit byte,
1297
- requested log probability, selection, cache state and usage record agrees.
1298
- Each arm executes 76 sparse selections and returns active memory to zero.
1299
- Existing model tests cover cache restore, mixed-length batching, streamed
1300
- execution, MTP and HTTP. A separate execution check confirms the transformed
1301
- module is used: all 34 tests pass. Evidence is `dsa-model-screen.json` and
1302
- `dsa-rank-u32-model-tests-v2{.txt,.transform.json}`. Bun's test run did not write
1303
- the initial process-exit observer file, so the second run asserts coverage
1304
- inside a test instead. The local artifact scan finds no compatible Colibri
1305
- configuration; the available GLM-5.3 Flash is `glm5_next`, not this
1306
- `glm_moe_dsa` path. Real-artifact serving remains open.
1307
-
1308
- The exact representation change is integrated in the existing DSA module
1309
- without another flag or interface. A permanent 8,193-position test checks
1310
- threshold ties on strided float32/float16/bfloat16 inputs. The first test run
1311
- uses the wrong import location for `Dtype`; after correcting that test import,
1312
- all 34 focused production tests and the three typechecks pass. Evidence is
1313
- `dsa-production-unit-v2.txt` and `dsa-production-typecheck-v2.txt`. The complete
1314
- model-free suite also passes: 1,840 passed, 10 skipped and zero failures, with
1315
- hygiene passing. Evidence is `dsa-production-model-free.txt` and
1316
- `dsa-production-hygiene.txt`. This is a measured shared-operation improvement;
1317
- it is not a Qwen throughput claim.
1318
-
1319
- The top-p sampling audit finds a removable inverse-permutation construction.
1320
- Keep the incumbent probability calculation, ascending sort and cumulative
1321
- sums, then scatter the cutoff mask directly to token positions. A pure MLX
1322
- mask scatter and a fused Metal output scatter preserve every output byte in
1323
- 216 cases across four vocabularies, three dtypes, three cutoffs, strided
1324
- inputs, ties and nonfinite values. The initial run stops at its cleanup
1325
- assertion on case 109: the current path intentionally caches the large
1326
- `arange` used for inversion. Fresh-process probes attribute the retained
1327
- 524,288/999,424 bytes to those index arrays, while both candidates release all
1328
- active bytes. This is an existing cache, not a disposal failure.
1329
-
1330
- The corrected screen prewarms that range cache and checks cleanup against
1331
- its measured baseline. The pure MLX rewrite is mostly flat; the fused kernel
1332
- has a modest operation-level gain. Compiling all three versions also
1333
- preserves all 216 cases, with exactly one trace per compiled function and
1334
- the expected remaining range-cache bytes. Evidence is
1335
- `top-p-scatter-screen-v2{,-review}.json`,
1336
- `top-p-scatter-compiled-screen{,-review}.json` and
1337
- `top-p-lifetime-{source,native,scatter,metal}.json`. The subsequent sampler,
1338
- model and HTTP gates below determine retention. The production sampler is
1339
- unchanged.
1340
-
1341
- The full seeded sampler screen then passes 180 cases across three vocabularies
1342
- and dtypes, four finite/masked distributions, both seeds and four step indices.
1343
- Top-p alone and its production combinations with top-k, min-p and XTC preserve
1344
- all sampled IDs in six implementations. All 54 compiled functions trace once;
1345
- disposal leaves only the incumbent range cache. The initial attempted B=3
1346
- case fails in the incumbent: this sampler's contract is one `[1,V]` row, as
1347
- used by sampled serving. That failed probe is retained. Evidence is
1348
- `top-p-sampler-screen-v2{,-review}.json`.
1349
-
1350
- The initial complete-generation screen passes 60 generations on Llama 1B and
1351
- Qwen packed/RTN4. Emitted IDs, requested log probabilities, live cache bytes
1352
- and usage agree. The packed quant's complete sampled timings are effectively
1353
- flat. RTN4's compiled-fusion arm also has a slower untouched greedy control,
1354
- so its timing needs a repeat before attribution. These are screens, not
1355
- retention evidence. Evidence is `top-p-native-screen{,-review}.json`.
1356
-
1357
- The actual HTTP screen passes 126 requests across 18 fresh servers, preserving
1358
- all 84 paired responses and usage records on serial and continuous execution.
1359
- A research-only default-seed provider returns 42 in both arms. Requests omit
1360
- the explicit seed field, which would select serial execution; placement is
1361
- unchanged and the continuous lane/submitted-row counters are asserted.
1362
- The apparent packed serial improvement does not survive six balanced pairs:
1363
- all 30 paired responses remain exact, but complete sampled request time is
1364
- 0.183% higher at the median and only one pair is faster. The untouched greedy
1365
- control moves by +0.058%. These loaded-machine results (M4 Pro) do not justify
1366
- retaining the fusion for Qwen. Evidence is `top-p-http-screen{,-review}.json`
1367
- and `top-p-http-r6-serial-repeat{,-review}.json`.
1368
-
1369
- Llama 1B's six balanced pairs per serving lane preserve all 84 paired
1370
- responses across 168 requests. Top-p-only complete time decreases by 0.399%
1371
- in serial and 0.380% in continuous serving, with all six pairs faster in each
1372
- lane. Top-p plus top-k changes by -0.132%/-0.196%; greedy remains effectively
1373
- flat. This is a small model-specific observation, not broad dispatch
1374
- eligibility or a Qwen gain. Keep it in the evidence ledger while testing
1375
- the complete graph's submission limits, traversal and synchronization.
1376
- No production sampler flag or kernel is added. Evidence is
1377
- `top-p-http-llama-repeat{,-review}.json`.
1378
-
1379
- Kernel timing is only a screen. Retention requires complete native generation
1380
- and actual serial/continuous HTTP comparisons at matched inputs, seeds and
1381
- compute shapes. Measure TTFT, prefill, decode, complete request time and memory.
1382
- When a fusion wins in isolation but loses in a request, inspect command-buffer
1383
- and encoder boundaries, synchronization, buffer lifetimes and overlap with the
1384
- next decode step. Capture traces separately from uninstrumented timing. A
1385
- smaller dispatch count does not establish better scheduling or throughput.
1386
-
1387
- The cross-entropy audit identifies two separate restrictions. The existing
1388
- hidden-width guard rejects Qwen's 5,120-wide head before kernel dispatch;
1389
- supporting that width is a separate task. For supported widths, vocabulary
1390
- partitioning can disable both Steel routes even when the vocabulary is
1391
- tile-aligned. Using the existing maximum block size of
1392
- 8,192 as the stride, with the final block capped at the vocabulary length,
1393
- keeps every tile in bounds. This fixed stride also avoids empty trailing
1394
- blocks at larger vocabularies. Every forward
1395
- and backward route must use the same partition, including block-skip metadata;
1396
- merely weakening the dispatch guard would permit unsafe final-tile loads.
1397
- The prepared head-only screen compares full-logit values and unfiltered
1398
- gradients, retains already-aligned controls, and measures actual dispatch and
1399
- allocation. Both initial arms pass 20 smaller cases and then hit the same
1400
- existing Qwen width restriction. A supported-width continuation passes all
1401
- 24 cases for 4/8-bit weights, varied token counts, softcap and boundary targets.
1402
- Candidate loss and unfiltered gradients remain within the predeclared
1403
- full-logit-reference tolerances; already-aligned forward controls retain
1404
- identical bytes. All tracked arrays are released. The changed partition and
1405
- kernel reduction order are not bit-exact to the old fallback. The isolated
1406
- timing screen favors the fast route at Llama-sized head geometry, but repeated
1407
- timing, actual-weight gradients, pruning and complete training/evaluation
1408
- measurements remain. This establishes no inference gain. Protocol and evidence:
1409
- `cce-block-alignment-plan.json`, `cce-block-alignment-{control,candidate}-screen.json`
1410
- and `cce-block-alignment-supported-review.json` under campaign reports.
1411
-
1412
- The follow-up forces SIMD, scalar and lane forward routes plus SIMD/scalar
1413
- backward on both partitions. All 54 cases pass the same full-logit and
1414
- unfiltered-gradient gates, including an unaligned vocabulary that must keep
1415
- its fallback. Maximum log-probability error is 1.91e-6; maximum gradient
1416
- relative L2 error is 1.12e-5. Every process returns to zero active bytes, with
1417
- fixed source. Together with the Steel screen this exercises all seven kernel
1418
- construction sites. Evidence is `cce-block-alignment-fallbacks{,-review}.json`.
1419
-
1420
- The production call-site audit closes this candidate without integration on
1421
- the current available workloads. `headQuant` in the loss path accepts Gemma4
1422
- and MiniCPM5. The available Gemma heads have vocabulary 262,144 and block stride
1423
- 8,192; MiniCPM5 has vocabulary 130,560 and stride 8,160. Both already satisfy
1424
- the Steel alignment guard. The Llama geometries that improved in isolation
1425
- are not wired into this loss helper. Changing their model support would be
1426
- separate work, and changing an already-aligned partition would add numerical
1427
- differences without the proposed dispatch benefit. Reopen if a supported
1428
- model actually reaches a misaligned block partition. No inference, full-loss
1429
- or training speedup is claimed; closed one-off helpers are removed after
1430
- recording the result.
1431
-
1432
- Local complete snapshots include Gemma e4b/12B/26B, diffusion Gemma, MiniCPM5,
1433
- Llama 1B/3B, assistant heads and GLM weights. Snapshot/file availability is
1434
- recorded in `reports/qwen38-rd/project-other-models.json`. Availability is not
1435
- execution acceptance. The GLM artifact exceeds device memory and requires its
1436
- streamed path; measure expert-slot kernels separately before full requests.
1437
-
1438
- A broader 4-bit prototype supports float16 and inner dimensions outside the
1439
- native fast-matvec regime. It must reproduce native dispatch's eight versus
1440
- sixteen values per lane, including the matching reduction order; masking the
1441
- old kernel's final loads alone is insufficient. All 320 synthetic dtype,
1442
- shape and strided-input checks pass. Six full-model pairs per append length
1443
- on Gemma 12B/e4b, MiniCPM5 and Llama 1B/3B preserve logits, live cache bytes
1444
- and continuation, with fixed source hashes. Gemma 12B improves at M4/8;
1445
- e4b improves at M8 but is approximately flat at M4. MiniCPM and both Llama
1446
- models regress in eligible cells. This prototype is not integrated: qualify
1447
- individual matrix shapes and full HTTP requests before widening dispatch.
1448
- Evidence: `affine-shared-cross-model-exactness.json` and
1449
- `affine-shared-cross-model-{gemma12,gemmae4b,minicpm5,llama1,llama3}-review.json`
1450
- under `reports/qwen38-rd/`.
1451
-
1452
- An actual-weight follow-up covers 44 matrix/append-length cases with exact
1453
- outputs, six AB/BA pairs, and both repeated dispatch and dispatch after a
1454
- scratch-memory sweep. Small attention projections generally favor native
1455
- MLX; large float16 output-head matrices identify a narrower shared-kernel
1456
- candidate. The initial Gemma 12B cells overlap an external Playwright/Node
1457
- burst recorded by preflight and vary substantially. Retain that run but repeat
1458
- those affected cells before deriving eligibility. Operation timing remains
1459
- distinct from full-model and HTTP acceptance. Evidence:
1460
- `affine-cross-model-matrix-{inventory,screen,screen-review}.json` under the
1461
- campaign report directory.
1462
-
1463
- A separate Gemma 12B repeat, with more dispatches per timing sample, preserves
1464
- all outputs and yields consistent improvements on its larger projections.
1465
- The smaller projection remains marginal or slower. The repeat retains its
1466
- own source hashes and machine observations; it does not replace the noisy
1467
- run. Evidence: `affine-cross-model-matrix-gemma12-repeat.json`.
1468
-
1469
- Restricting the float16 candidate to large output heads preserves every
1470
- 32-step greedy stream, live cache byte and continuation on Llama 1B/3B.
1471
- Six native pairs at B4/8 show small gains; B1 is flat. Six fresh-process HTTP
1472
- pairs per model then preserve all 312 paired responses, including usage and
1473
- finish reasons, with observed B4/8 overlap and clean server exits. The B8
1474
- serving gain is modest on 1B and below one percent on 3B; single-request
1475
- timing is flat. B4 is inconclusive. This does not justify widening production
1476
- dispatch. Both arms disable the existing shared-affine flag, and the candidate
1477
- pays its eligibility checks. The first two HTTP attempts failed overlap
1478
- qualification and remain excluded. Evidence:
1479
- `affine-head-batched-decode-mfirst-{llama1,llama3}-review.json` and
1480
- `affine-shared-head-http-{llama1,llama3}-overlap-review.json`. These
1481
- loaded-machine diagnostics (M4 Pro) do not replace quiet-machine acceptance. Closed head-only helpers
1482
- are removed; the broader operation's eligibility work remains open.
1483
-
1484
- A bf16-only selection uses large projections and leaves small matrices on
1485
- native MLX. The first selection preserves six full-model pairs per length on
1486
- Gemma 12B/e4b. Expanding the 12B selection to its other positive matrix shapes
1487
- preserves every checked logit, live cache byte and continuation. Both models
1488
- improve at M8; 12B also improves at M4. A 32-step fixed-B 12B repeat confirms
1489
- identity and the batched gain. Single-token controls are approximately flat.
1490
- The initial raw-completion HTTP comparison fails response identity at B4,
1491
- with differing admission histories and mostly repeated-character output in
1492
- both arms. Templated chat produces coherent text but also fails response
1493
- identity on its third B8 pair. A live diagnostic then compares every selected
1494
- projection against native MLX on the same inputs. All 36,704 operations are
1495
- byte-identical, including both M4 and M8, and both servers exit cleanly.
1496
- Those synchronizations invalidate its timing. A native A/A control with the
1497
- candidate disabled in both servers reproduces the same wording difference
1498
- when the second arm staggers arrivals by one millisecond per request. Both
1499
- servers exit cleanly, with stable sources and zero candidate calls. Thus the
1500
- response variation also occurs without the candidate; it is not evidence of
1501
- a candidate-only arithmetic error. Preserve both failed response gates.
1502
- Subsequent timing pairs retain every difference and require single-request
1503
- text identity, all usage/finish invariants and the independent same-input
1504
- numerical gates. Do not claim multi-request response identity when it fails.
1505
- Evidence:
1506
- `affine-large-projection-full-model-{gemma12,gemmae4b}-review.json`,
1507
- `affine-large-projection-v2-full-model-gemma12-review.json`,
1508
- `affine-large-projection-batched-decode-gemma12-review.json` and
1509
- `affine-large-projection-http-gemma12.json`,
1510
- `affine-large-projection-chat-http-gemma12.json` and
1511
- `affine-large-projection-verify-http-gemma12.json` and
1512
- `affine-large-projection-chat-http-native-control-gemma12.json`.
1513
- Six subsequent 12B timing pairs complete with stable sources, clean server
1514
- exits and all 156 paired responses identical in that run. Both observed B4
1515
- and B8 improve in every pair; B1 is approximately flat. Earlier response
1516
- failures remain part of the evidence. See
1517
- `affine-large-projection-chat-http-qualified-gemma12-review.json`.
1518
- The next control adds only large 4-bit bf16 projections whose K is divisible
1519
- by 256 but not 512, with M4/8 and both K and N at least 3072. The existing production
1520
- shared-affine flag is enabled in both arms, including its 3/8-bit kernels.
1521
- Six native pairs per append length preserve all logits, live states and
1522
- continuations. Both M4 and M8 improve in every pair; M1 and M128 controls are
1523
- approximately flat. The candidate exercises 105 additional projections at
1524
- M4/8. Evidence: `affine-nonfast-large-full-model-gemma12-review.json`.
1525
- The then-existing opt-in 4-bit kernel selected native eight- or sixteen-value
1526
- lane arithmetic for those shapes, off by default, with the 3/8-bit selection
1527
- restricted to its original shapes; that kernel and its flag were removed in
1528
- the MLX 0.32.2 consolidation (§7.12) and survive only in frozen source controls. Large nonfast
1529
- output heads with N≥65536 remain native because no such head has passed the
1530
- model/serving performance gate. This does not change the measured Gemma
1531
- projection selection. Focused tests
1532
- cover strided activations/metadata, compiled replay and native fallback.
1533
- The integrated version preserves six full-model pairs per append length and
1534
- improves M4/8. Six further production HTTP pairs improve B4/8 in every pair,
1535
- with single-request timing approximately flat, fixed sources and clean exits.
1536
- Two B8 warmup responses exhibit the same wording difference as the prior
1537
- native A/A control. All usage and finish invariants match; whole-response
1538
- identity does not hold for that run. Preserve those differences and the
1539
- independent numerical gates. Evidence:
1540
- `affine-nonfast-integrated-full-model-gemma12-review.json` and
1541
- `affine-nonfast-integrated-chat-http-gemma12-review.json`.
1542
- Live same-input verification then checks all 50,149 selected 4/8-bit operations
1543
- against native MLX with identical bytes, fixed sources and clean exits. Its
1544
- synchronizations invalidate timing. Evidence:
1545
- `affine-nonfast-integrated-verify-http-gemma12-review.json`. Six complete
1546
- flag-off/flag-on HTTP pairs also improve B4/8 in every measured pair, with
1547
- approximately flat single-request throughput, fixed sources and clean exits.
1548
- Two B8 warmup responses differ; preserve those alongside the live numerical
1549
- gate. All usage and finish invariants match. Evidence:
1550
- `affine-nonfast-integrated-chat-http-native-gemma12-review.json`. This does not establish a gain
1551
- for smaller models or justify enabling the flag across model families. Superseded projection and verification
1552
- helpers are removed after recording their findings; the incumbent comparison
1553
- helpers are removed after the native-flag control completes.
1554
-
1555
- One shared candidate is launch-configuration reuse. The current wrapper
1556
- recreates output/template/grid configuration on every custom-kernel call.
1557
- [mlx-c v0.6.0's implementation](https://github.com/ml-explore/mlx-c/blob/v0.6.0/mlx/c/fast.cpp)
1558
- copies that configuration into the apply call. A bounded per-kernel cache can
1559
- therefore reuse it while keeping tensor inputs dynamic. Qualify changed shapes,
1560
- template order, initialization, compile traces, eviction and disposal, then
1561
- measure full models and HTTP. No default change follows from the source audit.
1562
-
1563
- The first configuration-reuse prototype passes 160 changing shape/dtype
1564
- checks plus compiled replay, eviction and disposal. Six packed-model pairs
1565
- at M1/4/8/128 preserve logits, live cache bytes and continuation. Full-model
1566
- timings are approximately flat, with unchanged peak allocation. Compact
1567
- Qwen's affine control is also approximately flat. MiniCPM's single-forward
1568
- samples vary; a 32-step fixed-B repeat preserves every token, live state byte
1569
- and continuation with small B4/8 gains, but its unused B1 control also moves.
1570
- The subsequent HTTP run fails response identity in a later B8 wave. Its two
1571
- arms have different early admission histories. Six A/A pairs and six further
1572
- pairs with deliberately staggered arrivals do not reproduce the mismatch.
1573
- That leaves the cause unresolved; admission sensitivity is a hypothesis, not
1574
- a finding. The changed response occurred in the cache-disabled arm. Close
1575
- this prototype without integration: Qwen is approximately flat and MiniCPM
1576
- does not pass the serving gate. The HTTP mismatch remains unresolved in the
1577
- broader correctness coverage. Evidence:
1578
- `reports/qwen38-rd/metal-config-cache-exactness.json` and
1579
- `metal-config-cache-full-model-{packed,compact,minicpm5}-review.json`, plus
1580
- `metal-config-cache-batched-decode-minicpm5-api-review.json` and
1581
- `metal-config-cache-http-minicpm5.json`.
1582
- The control reports are `metal-config-cache-http-minicpm5-control-review.json`
1583
- and `metal-config-cache-http-minicpm5-admission-control-review.json`; their
1584
- passing responses do not replace the failed A/B gate.
1585
- Closed configuration-cache helpers are removed; raw reports remain.
1586
-
1587
- The multimodal rotary audit identifies repeated angle evaluation across
1588
- heads/layers and a contiguous-input requirement after Q/K transposes.
1589
- Separate prototypes test shared float32 angles, direct stride reads, and both
1590
- together. All 108 operation comparisons preserve bf16/f16/f32 bytes across
1591
- partial/full rotary dimensions, multiple positions and strided inputs. A
1592
- 16-layer Q/K schedule includes angle construction and uses distinct inputs
1593
- per layer. Short-sequence variants lose; direct stride reads improve the
1594
- prefill operation, while angle reuse alone is weaker. Timing varies within
1595
- the sweep and the operation is a small part of a complete 27B forward.
1596
- The full-body gate keeps shorter sequences native and uses fixed 3D
1597
- positions. All 35 logit/state/continuation cases match, but M128 is slightly
1598
- slower and M512 is approximately flat. Peak allocation decreases only
1599
- slightly. Close the prototype without integration; the operation gain does
1600
- not establish a useful complete-model gain. This gate excludes image encoding
1601
- and is not a real vision-request benchmark. Text-only generation uses native
1602
- fast RoPE. Evidence: `mrope-reuse-screen-review.json` and
1603
- `mrope-stride-full-model-packed-review.json`. Closed helpers are removed; raw
1604
- reports and source hashes remain.
1605
-
1606
- The final quiet-machine bundle must record host/chip/RAM, incumbent and
1607
- candidate source hashes, local diff, Bun/native/oracle versions, model hashes,
1608
- flags and workload files.
1609
- Run the existing serving suite and native generation separately on a quiet machine,
1610
- with fixed cache conditions and all paired samples retained. Its existing
1611
- numbers are historical controls until the workload and version metadata match.
1612
-
1613
- ### 7.10 Final benchmark and HTML comparison report
1614
-
1615
- Request tracing separates the gateway’s request-slot wait (`engine.request_wait`)
1616
- from execution-lock or row-admission wait (`engine.admission_wait`). Cache
1617
- prefetch/restore preparation has its own `cache.prefetch` span before execution;
1618
- later cache selection remains `cache.lookup_restore`. The prompt-response
1619
- report sums the two queue spans and the two cache spans in their respective
1620
- columns. Historical records without the new spans omit that work and must not
1621
- be interpreted as complete queue attribution. The shared serving HTTP reader
1622
- accepts a trace ID to correlate server phases with each scheduled request.
1623
-
1624
- The offline renderer and replay fixtures are implemented. It imports the
1625
- existing native/serve formats and saved Pi task results, retains failures and provenance, and suppresses
1626
- speed ratios for incompatible work or unqualified runs. Its current metrics
1627
- and limitations live in benchmarks.md. A bounded MiniCPM M1 diagnostic passes
1628
- the real measurement path with the explicit reference control; concurrent
1629
- output differences remain visible. Fixed-source block log-ratio intervals now
1630
- use a deterministic bootstrap across distinct workload seeds, with duplicate
1631
- seeds excluded and at least five blocks required. Task imports load adjacent
1632
- `quality.json` checks with file hashes, report failures and blocked categories,
1633
- and retain source/settings, per-turn request hashes, timing, usage and final
1634
- SSD flush records. Task rows do not enter engine-speed pairing. The read-only
1635
- quality-ledger exporter supplies portable model accuracy/KL/size records,
1636
- with source rows, configuration and machine provenance retained. Legacy
1637
- dataset/artifact identity limitations remain explicit; importing history
1638
- does not establish current-artifact quality acceptance. The frozen
1639
- final protocol and quiet final matrix remain acceptance work;
1640
- rendering saved evidence does not close this gate.
1641
-
1642
- After the optimization gates close, build and run a repeatable benchmark for
1643
- the incumbent, combined finalists and retained quantizations on a quiet
1644
- machine, recording its host/chip/RAM.
1645
- The benchmark must preserve the existing suite's measurements while making
1646
- native generation, serving, memory and quality comparisons easier to inspect.
1647
- Its protocol is frozen before final runs; the held-out Kanban task in section
1648
- 7.7 remains a separate task evaluation and is never an optimization fixture.
1649
-
1650
- Use Bun/TypeScript for orchestration, measurement, validation, statistics and
1651
- HTML generation. Python is confined to launching or instrumenting the pinned
1652
- MLX-LM/OptiQ reference. The mlx-bun arm loads and serves through the existing
1653
- engine and request interfaces. Browser rendering is outside the timed engine
1654
- and HTTP cells. Any later chat-UI profiling needs its own browser workload.
1655
-
1656
- Extend the current native worker, serving measurements, machine preflight,
1657
- artifact inventory and result persistence. Start from the serving suite's
1658
- versioned raw JSON and existing report functions; extract shared functions
1659
- only when both callers need them. Keep execution, comparison and HTML rendering
1660
- separate. Rendering saved results must require neither model weights nor a
1661
- running server, GPU, Python or network connection. Raw data remains portable
1662
- between machines, and the SQLite store is an index rather than the only copy.
1663
-
1664
- | Measurement group | Required cells and definitions |
1665
- |---|---|
1666
- | Single-request generation | Fixed token-ID prompts at the declared context depths, first emitted token, prefill time and processed tokens, sustained decode time, actual generated token count, total generation time and cleanup. Record computation boundaries so prefill throughput excludes unrelated loading or queue time. |
1667
- | Single-request HTTP | Serial execution and actual continuous execution with one request. Measure request start to headers, first byte, first visible content or tool output, final output and stream completion. Preserve server phase timings where available. SSE chunks are not tokens; client-visible output gaps and native token intervals have separate names. |
1668
- | Startup and reuse | Fresh-process readiness and first request, warm process with an uncached prompt, RAM prefix hit, SSD restore, exact continuation and edited-prefix miss. Record cache budget, persisted state and actual reused-token counts. A new process does not imply a cold filesystem cache. Page-cache-cold trials require an explicit controlled protocol. |
1669
- | Sustained serving | Fixed arrival schedules and concurrency levels within each machine's capacity; per-request queue time, TTFT, completion latency, stream stalls, aggregate completed requests and output tokens per second, error rate and throughput meeting declared latency limits. Verify actual lane, admitted rows and batch occupancy; a seed option must not silently route a continuous test through serial execution. Include cancellation, recovery and long multi-turn cache pressure. |
1670
- | Memory and resource use | Startup, prefill, decode, cache retention and post-disposal observations; peak server-process RSS, native active/peak allocations, allocator cache, KV and recurrent state, SSD cache size, system memory pressure and swap activity. Record sampler frequency and process ownership. Unified-memory and file-mapping accounting can change RSS without saving physical memory. Add energy only if supported measurement is calibrated and its overhead is excluded from ordinary timing. |
1671
- | Fidelity and quality | Same-input logits and cache/state gates at matched compute shapes, generated IDs where available, output bytes, usage and finish reasons. Different quantizations carry artifact bytes, quality results and task failures alongside performance. Early EOS, reduced thinking or incomplete output cannot count as faster completion of the same work. |
1672
-
1673
- For supported artifacts, pair each native/HTTP mlx-bun cell with the same
1674
- artifact on the pinned MLX-LM reference. Pin tokenizer, template, sampler,
1675
- seed, thinking, tools, budgets, cache state, prefill chunk/tail policy and
1676
- wiring. Store both requested and effective configuration. Identical seeds
1677
- alone do not establish equivalent graph shapes or RNG consumption. If a
1678
- reference lacks a feature or measurement, show an unsupported cell with its
1679
- reason. Packed trellis has no stock MLX-LM loader; a different affine or GGUF
1680
- artifact belongs in the quality/size comparison and cannot be its speedup
1681
- denominator. OptiQ and additional backends are separate supported controls.
1682
-
1683
- Record immutable machine, session, workload and artifact identifiers; OS,
1684
- chip, memory, power/thermal conditions, storage, Bun and oracle versions;
1685
- source commit/diff and native-library hashes; weight content manifests;
1686
- commands, resolved flags, protocol version, timestamps and preflight results.
1687
- Resolve accelerator details explicitly: actual draft architecture/artifact,
1688
- draft weight precision, block size, native MTP, prompt selection and KV format.
1689
- Requested flags or a model's nominal weight precision do not establish those
1690
- states. Report native active-memory peaks separately from process RSS.
1691
- Hash large files before timing. Preserve every attempted request, failure,
1692
- timeout, interruption and retry, with reasons for exclusions. Diagnostics
1693
- remain identifiable and cannot become quiet acceptance rows during import.
1694
-
1695
- Use the internal-SSD active-model policy in environment.md. Artifact transfer
1696
- and hash verification precede the timed run; record the active volume and
1697
- storage protocol. For startup, report readiness, first-request latency and
1698
- their combined elapsed time. Eager weight loading must not appear faster
1699
- merely because it moves disk work before the readiness signal. Historical
1700
- external-drive measurements stay separate from internal-drive comparisons.
1701
-
1702
- A Bun FFI collector prototype reads macOS `proc_pid_rusage` v4 directly for
1703
- an owned PID. Its layout is checked against the installed SDK; RSS, physical
1704
- footprint, lifetime peak physical footprint and disk-byte counters keep distinct
1705
- fields. The PID's start tick guards against reuse, and an exited or unreadable
1706
- process returns no sample. A 64 MiB allocation calibration matches Bun's RSS
1707
- and the expected physical-footprint growth; live/exited child reads and disposal
1708
- also pass. Two 32-sample blocks per arm measure about 0.0013–0.0015 ms per native
1709
- read versus 1.09–1.14 ms for the current `ps` subprocess. This is collector
1710
- overhead only, not an inference speedup. Validate real-server accounting and
1711
- sampling effects before using it in the final benchmark. Evidence:
1712
- process-memory-sdk-layout.json and process-memory-calibration.json under
1713
- reports/qwen38-rd. Existing timing reports keep their original collector.
1714
-
1715
- Apply section 7.7's balanced paired blocks, independent-session repeats and
1716
- correctness gates. Calculate speed ratios within a machine and compatible
1717
- protocol/artifact cells. Show raw distributions, sample counts and paired
1718
- uncertainty; estimate tail percentiles only with adequate request counts.
1719
- Use a prespecified stopping rule and acceptance thresholds. Keep supported
1720
- configuration tradeoffs visible instead of averaging different workloads,
1721
- precision levels or machines into a single score.
1722
-
1723
- The offline HTML report should provide machine/model/quant/backend/configuration
1724
- filters, baseline selection among compatible rows, absolute metrics and
1725
- within-machine deltas, distributions, memory-versus-speed and quality-versus-size
1726
- plots. Every summary links to raw JSON, provenance and correctness evidence.
1727
- Failed, skipped, unsupported and unmeasured cells remain visible. Escape saved
1728
- model output and other external strings; report generation must not execute
1729
- them. Embed the report's required assets so the exported file works offline.
1730
-
1731
- Exit requires a model-free replay fixture proving schema validation, unit
1732
- definitions, pairing, failure handling and renderer escaping; a bounded live
1733
- smoke through the real measurement paths; then the frozen final matrix on
1734
- a quiet machine. Compare the old suite and new suite on shared cells to
1735
- detect measurement changes before attributing a difference to the engine.
1736
- Publish qualified numbers only in the canonical benchmark reference, with
1737
- raw JSON and HTML under `reports/`. Machine access or unsupported cells that
1738
- remain unavailable must be named explicitly and cannot be counted as done.
1739
-
1740
- ### 7.11 Mac quant video follow-up
1741
-
1742
- The September 6 [RepoChad video](https://www.youtube.com/watch?v=dHK90xc9Q64)
1743
- names additional Mac quantization and serving configurations. Its description
1744
- contains chapters and hashtags, with no external artifact links. Automatic
1745
- captions were advertised but could not be retrieved. The investigation used
1746
- public storyboard frames to identify visible recommendations, then inspected
1747
- primary model cards and source. It did not recover a transcript. Metadata,
1748
- frames and pinned sources are retained in
1749
- `reports/qwen38-rd/video-dHK90xc9Q64/`.
1750
-
1751
- The concrete new weight candidate is
1752
- [`manjunathshiva/Qwen3.8-27B-tq3-mini-g64`](https://huggingface.co/manjunathshiva/Qwen3.8-27B-tq3-mini-g64/tree/5542979c87f72acaa9019633649cb6624e32699f).
1753
- It stores independent eight-centroid indices, ten codes per uint32, with
1754
- fp16 RMS scales per 64 inputs and online randomized Hadamard rotation.
1755
- Index storage is 3.2 bits/value before scales and other tensors. This differs
1756
- from the campaign's Trellis format. The custom wrapper can load it directly;
1757
- stock MLX-LM and our current loader do not implement this format.
1758
-
1759
- Its [M1 kernel](https://github.com/manjunathshiva/turboquant-mlx/blob/f4e3d34a831fc1f6acd8e7c29665bad358ce878e/kernels/polar_qmv.py)
1760
- uses five shared-memory barriers to reduce one SIMD group's partial sums.
1761
- First compare explicit converged SIMD shuffles with the same 16/8/4/2/1 tree,
1762
- element order, group scale placement and final cast. Include the wrapper's
1763
- bf16-to-f32 promotion and complete online rotation cost. The Apache-2.0 source
1764
- and attribution are pinned. [Conversion seeds rotations per projection path](https://github.com/manjunathshiva/turboquant-mlx/blob/f4e3d34a831fc1f6acd8e7c29665bad358ce878e/quantize_model.py);
1765
- gate/up sharing requires identical saved sign tensors. Do not reconstruct
1766
- those signs from a base seed, since conversion also uses Python string hashing.
1767
- Different small-M and expanded paths have separate rounding/reduction contracts.
1768
-
1769
- The video's attractive M4 Pro result matches
1770
- [oMLX record sio0vt3c](https://omlx.ai/benchmarks/performance/sio0vt3c): DFlash2,
1771
- quantized draft weights and block size five are enabled; native MTP is off.
1772
- It is not a plain Q4 decode baseline. The
1773
- [Qwen DFlash2 artifact](https://huggingface.co/z-lab/Qwen3.8-27B-DFlash2/tree/50307d4c4cde6860d4eee73e2547cd786fe8e8a4)
1774
- is a concrete R21 candidate. Existing Gemma draft support does not establish
1775
- support for this architecture. Any port needs target-state/rollback identity,
1776
- draft residency and full-request comparisons with ordinary decode and fixed-two
1777
- native MTP. Guaranteed structural appends remain a separate operation.
1778
-
1779
- The pinned oMLX package file actually selects
1780
- [dflash-mlx c55324c, v0.1.10+omlx.7](https://github.com/jundot/omlx/blob/aa8db73496bd8367989e2862f50b315885b9b91a/pyproject.toml).
1781
- The older v0.1.10+omlx.4 string is an engine compatibility comment. At that
1782
- [dependency revision](https://github.com/jundot/dflash-mlx/tree/c55324c86540c369f6818a0f47eae544d405475b),
1783
- DFlash2 adds dynamic grouped causal convolutions around both attention and
1784
- MLP, plus a selector that conditions each token on its selected predecessor
1785
- using top-16 candidates and rank-256 codebooks. Our existing DFlash provider
1786
- needs this architecture and selector in addition to Qwen target taps; loading
1787
- the checkpoint into the current provider would not implement DFlash2.
1788
-
1789
- The fork's flat greedy verify path concatenates proposed and target token IDs
1790
- for one host read, then checks acceptance and EOS from that result. Hidden
1791
- feature extraction launches asynchronously outside profiling. This does not
1792
- mean every mode has one synchronization: repetition penalties need another
1793
- ID read and stochastic acceptance follows a separate path. Our speculative
1794
- accept walk reads each sampled target position eagerly, and Qwen MTP reads
1795
- each draft token before the next draft step. Test grouped reads first for
1796
- history-independent greedy requests. Preserve the shared sampler's processor,
1797
- grammar, RNG and history contract; do not bypass it for a blanket fast path.
1798
- The pinned eleven-file
1799
- source bundle and hashes are in video-dHK90xc9Q64/dflash-source-manifest.json.
1800
-
1801
- The grouped-read experiment is closed without a production change. Two Bun
1802
- prototypes keep the existing independent per-position sampler calls: one
1803
- concatenates their IDs for one read; the other uses `evalAll` followed by direct
1804
- integer reads. Each passes 144 operation cases, including ties and nonfinite
1805
- logits, with unchanged inputs and zero retained allocation after disposal.
1806
- The operation improves when several positions are consumed, but computing
1807
- unused positions makes a first-position rejection slower.
1808
-
1809
- Six balanced three-arm HTTP blocks then preserve all 84 candidate/control
1810
- response comparisons, usage and acceptance traces across 126 requests. All
1811
- arms use the same R6 target, saved q4 MTP companion, gamma 2, bf16 KV and greedy
1812
- seed 42. Ordinary sampling makes 432 eager ID reads per server; either
1813
- prototype replaces verification reads with 152 grouped windows plus seven
1814
- ordinary first-token reads. All servers exit cleanly with equal active
1815
- capacity, and all 547 source hashes remain fixed. Complete-request paired
1816
- medians for concatenation improve only 0.33%, 0.06% and 0.23% across the code,
1817
- explanation and JSON fixtures. The `evalAll` alternative improves 0.26% and
1818
- 0.04% but regresses 0.44% on JSON. Losses remain in both results. These
1819
- diagnostics (M4 Pro) establish no broad serving benefit worth another sampler path.
1820
- Evidence: spec-grouped-greedy-screen.json, spec-grouped-greedy-eval-screen.json
1821
- and spec-grouped-greedy-three-http{,-review}.json. This tests target verification
1822
- readback only, not DFlash2's architecture or the separate forced-token method.
1823
-
1824
- The scalar checkpoint's reported four agent failures on a 16 GB Mac mix missing
1825
- tool calls, a queue timeout and perseveration ending in OOM. The same weights
1826
- pass on a larger Mac, with differing wrapper builds unresolved. These reports
1827
- do not isolate quantization damage. Borrow the long-agent memory/context tests
1828
- using current artifacts first. Likewise,
1829
- [SpecPrefill](https://github.com/jundot/omlx/blob/aa8db73496bd8367989e2862f50b315885b9b91a/omlx/patches/specprefill.py)
1830
- selects a prompt subset with a smaller model. Keeping RoPE positions does not
1831
- reconstruct skipped GDN recurrence updates. It belongs in an approximate Lab
1832
- arm with original/selected token counts, retrieval and task-quality gates.
1833
-
1834
- Priority is the bounded M1 scalar operation screen, current-artifact long-agent
1835
- memory/context coverage, then Qwen DFlash2 feasibility. Only positive operation
1836
- economics and quality evidence justify a new full-model loader or artifact.
1837
- Approximate prompt reduction follows the exact-path work. No external speed
1838
- or memory figure changes our baseline.
1839
-
1840
- The bounded Bun/Metal M1 screen now preserves all 54 fixture cases, including
1841
- online rotation, dtype promotion and incomplete packed rows. Six fresh-process
1842
- repeats preserve every fixture/output hash and release all active allocations.
1843
- For the 5120-to-17408 projection, explicit shuffles reduce complete rotated
1844
- operation time by a median 2.77–3.84% across the three input dtypes; the reverse
1845
- projection improves 0.63–1.06%. Every pair improves. Packed-word reuse is slower,
1846
- forced loop unrolling adds little, and larger threadgroups do not establish an
1847
- additional large-projection benefit. This is the literal upstream source run
1848
- through our Bun binding on synthetic matrices, not installed-wrapper parity or
1849
- a current-engine/full-model improvement. Evidence: `polar-qmv-screen-v2.json`,
1850
- `polar-qmv-variants.json`, `polar-qmv-geometry.json` and
1851
- `polar-qmv-repeat{,-review}.json`.
1852
-
1853
- A separate exact prototype fuses the upstream large-prefill unpack, centroid
1854
- gather and group-scale multiplication into one fp16 expansion. The original
1855
- fallback builds uint32 indices, narrows them to uint8, widens them for gather,
1856
- then multiplies the gathered weights by scales. The screen preserves all 16
1857
- expanded-weight and complete-operation cases, including small padded rows and
1858
- zero/subnormal/overflow scale values. Six fresh processes then preserve all 84
1859
- large-projection comparisons at M257/512, including rotation and native matmul,
1860
- with identical cross-process hashes and zero final active allocation. Median
1861
- complete-operation time falls 40.85–57.51%; peak temporary allocation falls
1862
- 765.00–765.05 MiB. Every pair improves. These were measured on the M4 Pro on synthetic
1863
- resident matrices. They do not measure real model quality, RSS or whole-model
1864
- speed, and they do not replace the separate small-M QMM arithmetic. Evidence:
1865
- `polar-expand.json` and `polar-expand-repeat{,-review}.json`.
1866
-
1867
- Our existing `TurboQuantKVCache.#decode` has the same unpack/gather/scale
1868
- pattern. The byte-packed KV decoder and the narrower inverse-rotation
1869
- operation are integrated behind `MLX_BUN_TURBOQUANT_FUSED_DECODE=1`; their
1870
- gates, numbers and the closed direct packed-key attention arm live in
1871
- turboquant.md, "Packed-value decode fusion investigation", and the ledger row
1872
- is §7.13 R13. The video's weight format still has no production loader or
1873
- kernel here.
1874
-
1875
- ### 7.12 Custom-kernel graph reuse and the MLX runtime update
1876
-
1877
- The pinned runtime separates three costs. `metal_kernel` constructs a lazy
1878
- custom primitive on each eager call. Its GPU evaluator uses MLX's ordinary
1879
- command encoder and cached Metal library/pipeline. `compile` separately caches
1880
- an optimized graph, then instantiates it with new inputs during native replay.
1881
- Avoiding JavaScript tracing does not remove all native graph or dispatch work.
1882
-
1883
- The actual Bun probe confirms shape-specific compilation works with custom
1884
- kernels: five calls over shapes 8/8/16/16/8 trace twice, invoke the shape/grid
1885
- callbacks twice and return exact outputs for changing values. Native shapeless
1886
- addition traces once across those shapes. Both custom shapeless variants fail
1887
- with `CustomKernel cannot infer output shapes`, even when JS callbacks supply
1888
- output shapes and the launch grid. All allocations release after disposal.
1889
- The wrapper comments now describe this accurately: callbacks run during eager
1890
- construction or tracing, never during native replay. Evidence:
1891
- custom-kernel-compile-probe.json; the earlier helper error is retained separately.
1892
-
1893
- This is an upstream limitation, not solely a Bun binding omission. The
1894
- [CustomKernel declaration at current MLX main](https://github.com/ml-explore/mlx/blob/ce916dbbcaa88e433b6fd1e60a17f766d49c27fe/mlx/fast_primitives.h)
1895
- still lacks `output_shapes`, and captures a concrete launch grid. A future
1896
- native operation must infer both result shapes and dispatch from current
1897
- inputs. Passing an output-shape callback through our existing JS interface
1898
- cannot supply that native behavior. Prior per-projection shape-specific caching
1899
- and launch-configuration reuse did not improve complete Qwen requests (§7.8/7.9);
1900
- those negative results remain. Next candidates must target larger reusable
1901
- regions or measured native construction costs, with growing-cache, compile,
1902
- state, cancellation and complete-request gates.
1903
-
1904
- Josh authorized upgrading to the latest stable MLX. The fresh upstream check
1905
- finds [MLX v0.32.2](https://github.com/ml-explore/mlx/releases/tag/v0.32.2), released
1906
- 2026-08-25; Homebrew currently offers 0.32.1. The staged runtime pairs that
1907
- version with [MLX-C c74db530](https://github.com/ml-explore/mlx-c/tree/c74db5307cc8ce122f48d97ef951b30578674e7f),
1908
- whose CMake dependency pins 0.32.2. The full source build stopped because this
1909
- Mac lacks the offline Metal toolchain. The completed build instead links the
1910
- C wrapper against MLX's verified official 0.32.2 native wheel libraries.
1911
- Bun loads those native libraries directly. Local build, archive and library
1912
- hashes are recorded in `reports/qwen38-rd/mlx-upgrade-0.32.2/`.
1913
-
1914
- The initial cross-version checks used a temporary dual-ABI adapter. The
1915
- consolidated production binding now directly uses the 0.32.2 C API. Attention
1916
- supplies `force_fused=false`, cumulative sum supplies an absent optional dtype,
1917
- and both cumulative operations call the axis-taking symbols. Startup checks
1918
- the linked core version. The original cross-version suites and the later
1919
- Trellis-port suites passed on both runtimes; their separate reports remain.
1920
-
1921
- The frozen shared-affine port was validated against the 0.31.2 core. Identical packed
1922
- weights, activations and metadata reproduce four exactness differences against
1923
- 0.32.2 native multi-row matmul. The custom outputs are unchanged across versions
1924
- and match separate native M1 rows. Upstream `qmv_wide` decodes each group once
1925
- for several vectors and uses different arithmetic and an eight-lane reduction.
1926
- Native dispatch on the new core preserves its numerical contract. The final
1927
- production code removes the old affine kernel and its experimental flag;
1928
- the frozen source controls retain that implementation for comparisons.
1929
-
1930
- Six balanced process pairs screen ten affine shapes with twenty alternating
1931
- operation samples per implementation. New native Q3 gate/up-shaped operations
1932
- improve over old shared operations in all six blocks; Q4 results are mixed by
1933
- shape and block, while Q8 loses in every block. These are loaded-machine
1934
- operation diagnostics, not full-model gains, and refer to affine Q3 rather
1935
- than Trellis. All input hashes agree and every process releases its arrays.
1936
- Evidence: affine-{old,new}-screen.json and affine-runtime-repeat{,-review}.json.
1937
- Same-version RTN4 oracle gates now pass on both cores and on both official
1938
- 0.32.2 macOS builds. Each comparison covers contexts 0/64/512 and append lengths
1939
- 1/4/8/128, checking complete logit arrays, every live cache array, and a fixed
1940
- continuation. All twelve cells are byte-exact against the matching MLX-LM
1941
- reference. The two new-core builds also agree with each other in those cells.
1942
- Source hashes stay fixed and every worker exits cleanly. Evidence:
1943
- runtime-oracle-rtn4.json and runtime-oracle-rtn4-macos14.json.
1944
- The package selects the verified macOS 14 native pack 0.4.0, now published;
1945
- distribution.md records the release. Final-source acceptance
1946
- passes 16 RTN4 same-version reference cases (including actual 4K/8K prompts),
1947
- 36 Trellis forward/state/continuation cases and six Trellis generations.
1948
- The Trellis control is the accepted new-core implementation; this is not a
1949
- claim of an external packed-Trellis oracle. All three workers exit cleanly,
1950
- with fixed source, library and reference hashes. Evidence:
1951
- `final-source-gates.json`. The consolidated model-free suite passes 1,875 tests
1952
- with ten skips; all three typechecks and hygiene pass. Integrated inverse-KV
1953
- serving also passes its repeated response and decode gates; its complete-time
1954
- verdict differs by quant, as recorded in turboquant.md. Broader same-version
1955
- reference checks and combined/pressure acceptance remain. The old runtime and both source controls remain
1956
- separate; environment.md records their paths.
1957
-
1958
- Production targets one pinned runtime. Trellis, rotation and TurboQuant
1959
- continue through their existing interfaces. The integrated inverse-KV decoder
1960
- passes its new-core R6 and RTN4 comparisons against the preceding joint decoder.
1961
- Each checks 12 full forward/state/continuation cases and four greedy/sampled
1962
- generations at 2K and 8K contexts. Logits, complete cache arrays, token IDs,
1963
- logprobs and usage are exact. Each pair has equal final active allocation and
1964
- clean exits. These comparisons isolate the KV change and do not establish
1965
- every Trellis variant's equivalence. Evidence: r6-kv-inverse-full.json and
1966
- rtn4-kv-inverse-full.json.
1967
-
1968
- The separate new-core Trellis v6/v13 model gate catches an M8 append mismatch.
1969
- M1/3/4/128/512 and all four tested generations remain exact. The first differing
1970
- cache appears after layer zero. Upstream `gemv_wide` changes the arithmetic of
1971
- contiguous small-M dense projections on M3 and newer GPUs. The old direct
1972
- Trellis prefill tile reproduces the preceding SIMD-matrix reduction instead.
1973
- A deterministic operation reproduction fails at every M5..15 row count and
1974
- passes again at M16, where native dispatch returns to GEMM. The replacement
1975
- kernel decodes packed Trellis weights to bf16 within the new eight-iteration,
1976
- four-value dot-product loop. Sharing each decoded row across all M vectors
1977
- preserves the native reduction and wins the initial complete-operation screen
1978
- for every tested 2/3/4-bit cell. A full-model prototype comparison passes all
1979
- 36 forward/state/continuation cells and four greedy/sampled generations.
1980
- Those timings are screening evidence, not serving results.
1981
-
1982
- The integrated implementation keeps geometry and arithmetic in
1983
- `trellis-wide-prefill.ts`. It is dispatched only under
1984
- `MLX_BUN_TRELLIS_VARIANT=11..13` (`TrellisLinear.forward` in
1985
- `src/model/trellis-linear.ts`); the default variant 6 still expands and uses
1986
- native matmul, so this path is opt-in, not production. Qwen supplies an explicit layout proof from its
1987
- RMSNorm output through the existing MLP and linear calls. Unproven layouts
1988
- return to native expansion/matmul for the affected sizes. Reading lazy-array
1989
- strides before evaluation cannot establish this proof, and inserting an eval
1990
- would change scheduling. Native arithmetic also depends on the GPU generation;
1991
- the gate reads MLX's architecture identifier once and retains the earlier
1992
- dispatch on pre-M3 hardware. The operation tests cover every M5..15 size for
1993
- all three bit widths and a full-size transposed-input fallback. The integrated
1994
- model comparison passes all 36 forward/state/continuation cases and six
1995
- greedy/sampled generations, including short prompts. Logits, tokens, logprobs
1996
- and cache state are exact. Both processes release to the same active-memory
1997
- baseline. The complete model-free suite passes on both cores, with 1,882 passes
1998
- and ten skips on the new core, and 1,881 passes and eleven skips on the old
1999
- core. The additional skipped test needs the new native reduction. All three
2000
- typechecks and hygiene pass. Preserve the
2001
- failed model report; no equality check is weakened. Evidence: trellis-runtime-full,
2002
- trellis-wide-screen, trellis-wide-perf, trellis-wide-full and
2003
- trellis-wide-integrated-full reports in the upgrade directory.
2004
-
2005
- Six balanced actual HTTP pairs per serial/continuous lane preserve every
2006
- response, usage count and finish reason. The raw 9/12-token prompts exercise
2007
- 8/11-row prefills with normal tail splitting. TTFT improves in every pair;
2008
- complete-request time improves in all but one measured fixture pair. Decode
2009
- and peak RSS are effectively unchanged. These are narrow, loaded-M4-Pro
2010
- diagnostics. The first continuous attempt supplied an explicit seed, which
2011
- correctly selected serial placement. Its failure remains recorded. The
2012
- corrected continuous requests use greedy decoding without an explicit seed
2013
- and assert actual scheduler admission and batched usage. Evidence:
2014
- trellis-wide-http.json, trellis-wide-continuous.json and
2015
- trellis-wide-http-review.json. This supports the new small-prefill path;
2016
- it does not establish a general decode gain from upgrading MLX.
2017
-
2018
- Two balanced runtime blocks complete all 24 native workers with fixed source
2019
- and library hashes. Short-prompt decode is effectively unchanged. RTN4's
2020
- short-prompt first-token time improves slightly in both orders. Long-prefill
2021
- timings vary substantially by order, so the initial apparent gain is not an
2022
- accepted upgrade result. Both new-core builds produce identical tokens across
2023
- all repeats. At the 4,096-token prompt, both quants produce stable but different
2024
- continuations across core versions. Those differences remain explicit in the
2025
- report. The additional same-version oracle uses the actual long-prompt IDs,
2026
- repeated for 8K, with 512-token prefix chunks and the final 511-token tail.
2027
- Both append lengths, one and eight tokens, pass at both contexts. Full
2028
- logits, every live cache array and the fixed continuation are byte-exact;
2029
- both workers exit cleanly with fixed source hashes. Evidence:
2030
- runtime-oracle-long-macos14.json and
2031
- native-runtime-screen{,-review}.json. These runs used a loaded machine (M4 Pro)
2032
- and are not canonical benchmark rows.
2033
-
2034
- A native proxy prototype establishes a narrower graph-reuse option. It holds
2035
- the original custom operation, delegates evaluation to MLX's existing encoder,
2036
- and supplies constant output shapes only after checking that every custom
2037
- input retains its captured shape and dtype. Other graph inputs may change
2038
- dimensions. The two-output probe returns exact results over five changing
2039
- input-value/native-shape calls with one JS trace. A changed custom input shape
2040
- throws before dispatch; returning to the original shape still works. Disposal
2041
- returns active memory to zero. This does not add general dynamic-shape custom
2042
- kernels or establish a model speedup. Evidence: fixed-custom-probe.json and the pinned native helper build
2043
- in the upgrade directory.
2044
-
2045
- The actual Qwen region probe also needs fixed-input `Slice` support. Its
2046
- native proxy retains the same strict shape/dtype checks. Default compilation
2047
- passes all 48 R6 recurrent/full-attention cases with one trace per region, but
2048
- changes an RTN4 full-attention output while preserving KV state. Disabling
2049
- fusion everywhere instead changes recurrent state. Keeping normal fusion in
2050
- recurrent regions and disabling additional fusion in full-attention regions
2051
- passes all 48 cases on both quants, including growing contexts and continuations.
2052
- All failed comparisons remain recorded; none becomes a tolerance-based pass. Evidence:
2053
- qwen-fixed-region-{r6,rtn4}-v{2,3,4}.json in the upgrade directory.
2054
-
2055
- Composing these regions as 64 cached per-layer graphs passes R6's eight full
2056
- forward/state cases and six greedy/sampled generations, including logprobs.
2057
- Every layer traces once and all compiled closures release. Request timing is
2058
- flat or slightly slower. RTN4 fails the full-model numerical gate despite the
2059
- regional passes. Its one-token forward changes logits while initially
2060
- preserving cache arrays; subsequent continuations also change state. RTN4
2061
- timing shows no gain. This per-layer implementation stays out of production.
2062
- It establishes a limited graph-reuse mechanism, but changing graph boundaries
2063
- still requires full-model identity and request-time evidence. Both arms exit
2064
- normally with equal final active allocation for each model. Evidence:
2065
- qwen-fixed-layer-r6-full-v2.json and qwen-fixed-layer-rtn4-full.json.
2066
-
2067
- A whole-model graph experiment preserves the existing inner compiled regions.
2068
- In the pinned MLX source, `detail::compile`
2069
- calls the original function when an input is already a tracer. Nested
2070
- `computeG` therefore expands into the outer trace, and an outer `no_fuse` mode
2071
- also removes its required inner fusion. Warming the inner cache does not
2072
- change that branch. A research helper temporarily restores ordinary inner
2073
- compilation, then restores tracer ownership before the outer graph is built.
2074
- The changing-input probe passes ten bf16/f32 cases with two traces and
2075
- unchanged input bytes. Both R6 and RTN4 then pass eight full forward/state
2076
- cases and six greedy/sampled generations each, including logprobs and
2077
- continuations. Each whole-model closure runs 394 times with two traces and
2078
- releases on weight disposal; both controls agree on final active allocation.
2079
- This resolves the earlier RTN4 composition failure for this implementation.
2080
- The first native timing screen is slower on both quants. It is not a balanced
2081
- performance verdict, but supplies no speed candidate. Attribute cache copying
2082
- and graph bookkeeping before further request-time comparisons. No production
2083
- tracer manipulation or whole-model compilation change is integrated.
2084
- Evidence: `compiled-region-probe.json` and
2085
- `qwen-fixed-hidden-regions-{r6,rtn4}.json` in the upgrade directory.
2086
-
2087
- A narrower experiment uses ordinary fixed-shape `CompiledFunction` for the
2088
- sixteen groups of three recurrent layers. Full-attention layers keep their
2089
- native capacity-backed KV updates. This needs no native proxy or tracer
2090
- manipulation: hidden inputs and initialized recurrent/conv states have fixed
2091
- decode shapes. Both R6 and RTN4 pass eight complete forward/state/continuation
2092
- cases and six greedy/sampled generations, including logprobs. Each group
2093
- traces once, the sixteen groups execute 6,304 calls, and all closures release
2094
- with the same final active allocation as the ordinary control. R6's initial
2095
- comparison uses the external archive; RTN4 uses the byte-verified internal
2096
- active copy specified in environment.md. The initial fixed-order timing
2097
- screens supply no request-time gain, but unchanged prefill timings also
2098
- drift. The follow-up alternates ordinary and compiled generation within one
2099
- loaded internal-SSD model, with four balanced pairs each at 8- and 128-token
2100
- prompts. Both quants preserve all forty warm/measured generations, logprobs,
2101
- live state and steady active ownership. Sixteen closures trace once per model
2102
- across 10,240 group calls, then close. Median paired complete-time reductions
2103
- are only 0.062% for R6 and 0.202% for RTN4, with one slower pair on each.
2104
- This does not justify adding model execution and lifetime machinery; no
2105
- production integration or HTTP speed claim. Evidence:
2106
- `qwen-fixed-ssm-groups-r6.json` and
2107
- `qwen-fixed-ssm-groups-rtn4-internal.json`, plus `qwen-ssm-hot-review.json`
2108
- and its raw per-quant reports in the upgrade directory.
2109
-
2110
- The broader matching-core audit catches a separate MiniCPM5 prefill gap.
2111
- M1/M8 agree, while M128 changes logits and state from layer four onward.
2112
- Its Llama MLP had limited compiled SwiGLU to decode, whereas MLX-LM compiles
2113
- the activation at every sequence length. Using the oracle operation for
2114
- prefill restores all six same-input logit/state/continuation cases in the
2115
- isolated control. The model-owned implementation now uses that existing
2116
- compiled helper at every length outside an enclosing compiled trace.
2117
- The explicit opt-out remains. Integrated MiniCPM5, Llama 1B and Gemma e4b
2118
- reference checks pass all eighteen cases. The retained opt-in regression
2119
- `tests/parity/runtime-oracle.test.ts` repeats the full logits, live state and
2120
- continuations with the matching runtime and sequential subprocesses; all
2121
- three model tests pass. Training and serving checks remain before this
2122
- runtime correction closes.
2123
- Evidence: `runtime-oracle-broader.json` and
2124
- `runtime-oracle-compiled-prefill.json` in the upgrade directory.
2125
-
2126
- The intervening release notes are:
2127
-
2128
- | Release | Changes relevant to this program |
2129
- |---|---|
2130
- | [0.32.0](https://github.com/ml-explore/mlx/releases/tag/v0.32.0) | Small-batch quantized matvec, RMSNorm register reuse, custom Metal math modes, compile cleanup and shapeless-reduction fixes. |
2131
- | [0.32.1](https://github.com/ml-explore/mlx/releases/tag/v0.32.1) | Lower custom-kernel naming overhead, reusable Metal hazard tracking, small-batch dense matvec, shader-cache collision and shapeless-matmul fixes. |
2132
- | [0.32.2](https://github.com/ml-explore/mlx/releases/tag/v0.32.2) | Optional forced fused attention, GQA8 reuse, sliced-array quantization and compiled-cast fixes; additional NAX paths apply to newer GPU architectures. |
2133
-
2134
- Useful upstream changes include [removing regex from custom-kernel name
2135
- construction](https://github.com/ml-explore/mlx/pull/3869), [reusing Metal hazard
2136
- tracking allocations](https://github.com/ml-explore/mlx/pull/3882), [fixing
2137
- same-name shader cache collisions](https://github.com/ml-explore/mlx/pull/3833),
2138
- and [correcting shapeless matmul's dynamic dimensions](https://github.com/ml-explore/mlx/pull/3813).
2139
- Their reported gains are not our measurements. New [GQA8 attention reuse](https://github.com/ml-explore/mlx/pull/4077)
2140
- has a narrow D64/128 dispatch; Qwen3.8-27B uses GQA6/D256, so it is an algorithm
2141
- lead rather than a direct dispatch win here. The [optional fused full-attention
2142
- path](https://github.com/ml-explore/mlx/pull/4185) explicitly trades throughput
2143
- for bounded temporary memory. Evaluate that tradeoff on the actual
2144
- eligible path. Reference numerical changes must be explained, never hidden by
2145
- loosening the oracle tolerance.
2146
-
2147
- Qwen layer evaluation bounds deferred prefill work. The exact oracle and
2148
- retained-history results, including superseded reservation trials, are in
2149
- [benchmarks.md](../reference/benchmarks.md). Josh's closeout machine policy
2150
- permits the recorded audio-daemon CPU activity with exclusive GPU ownership,
2151
- available memory and stable alternating pairs. Earlier diagnostic evidence
2152
- keeps its original classification.
2153
-
2154
- Josh subsequently chose request execution over predicted-memory refusal. The
2155
- reservation prototypes remain historical diagnostics. Default fit estimates
2156
- must neither reject prompts nor clamp completion caps; only explicit operator
2157
- limits and fixed representation capacities apply. The Qwen layer evaluation
2158
- fix stays, while reservation callbacks and their hot-path checks are removed.
2159
- Actual failures remain recorded in reliability and timing results.
2160
-
2161
- ### 7.13 Outcome ledger
2162
-
2163
- One row per §7.4 experiment, in the §7.7 vocabulary (repeatable win, measured
2164
- loss, inconclusive, blocked, unmeasured). Every campaign number was measured
2165
- on Joshs-MBP-2025.local (Apple M4 Pro, 24 GB) unless a row says otherwise;
2166
- the host is provenance, not scope. All "repeatable win" rows have at least
2167
- six balanced pairs with exact outputs. The original rows below describe
2168
- loaded-machine diagnostics. The closeout serial v6/v13 suite now passes six
2169
- balanced pairs under the recorded audio-CPU allowance, with every paired
2170
- request matching. Final-source native state and bf16/KV4 MTP-prefix gates
2171
- also pass. Later acceptance promoted variant 13 and shared batching in v0.4.0; early
2172
- first output is now also selected. Remaining combinations and measurement
2173
- limits are identified per row. New evidence is in `reports/qwen38-closeout/` and
2174
- [benchmarks.md](../reference/benchmarks.md). Historical evidence paths
2175
- are relative to `reports/qwen38-rd/` on the measuring host; the narrative
2176
- behind each row is the archived log
2177
- ([qwen38-27b-campaign-log.md](../archive/investigations/qwen38-27b-campaign-log.md)),
2178
- §7.9–§7.12, [turboquant.md](turboquant.md) "Packed kernel experiments" and
2179
- "Packed-value decode fusion investigation", and
2180
- [speculative-decoding.md](speculative-decoding.md) §4.7/§7.4.
2181
-
2182
- | ID | Experiment | Outcome | Retained flags / defaults | Evidence files | Next discriminating step or missing resource | Reopen condition |
2183
- |---|---|---|---|---|---|---|
2184
- | R0 | Exact artifact and execution controls | **Inconclusive.** Isolated unmodified `6d45ca1`/`673b43f` checkouts: six native AB/BA pairs per flagship/compact/RTN4 match every ID at 6/128/512 prompt tokens with flat TTFT/complete/memory; six serial and six default-scheduler HTTP pairs preserve every response with flat or slightly lower complete time. Updated Bun vs MLX-LM native controls (six pairs per affine artifact, 64 tokens) emit identical IDs, complete time close, small median Bun advantage. Graph exports (v6/v8 at M=1/4/5), dispatch inventory, per-operation counter calibration and a schedule recorder exist; dispatch-level GPU sampling is unsupported on the M4 Pro, so per-kernel attribution stays open. The M4 DeltaNet golden is resolved (stale fixture; Bun and Python agree). The quiet serial/default/mlx-lm HTTP baseline never ran; the packed target has no stock mlx-lm arm. | None (controls only). | `refactor-fixed-kernel-audit-plan.json`, `refactor-native-paired{,-review}.json`, `refactor-http-paired-{serial,default}-review.json`, `native-affine-paired{,-review}.json`, `native-affine-paired/`, `native-memory-ledger.json`, `native-memory-chunk512-screen/`, `graph-captures/`, `variant8-attached.trace`, `attached-trace-summary.json`, `labelled-v8-analysis.json`, `labelled-v8-kernels.txt`, `variant8-labelled.trace`, `metal-counter-capabilities.json`, `mlx-counter-source-manifest.json`, `mlx-counter-build.patch`, `metal-counter-pooled-unit.stderr.txt`, `metal-counter-calibration-review.json`, `mlx-schedule-source-manifest.json`, `mlx-schedule-smoke-v2.log`, `top-p-schedule-screen{,-review}.json`, `empty-submit-r6-steady-trace{,-review}.json`, `mlx-empty-submit-steady-source-manifest.json` | Exclusive M4 time is now available. Finish the final-source serving/reference controls: `bun scripts/bench-serve.ts all --model-path ~/models/Qwen3.8-27B-q3-trellis-ldlq-k300-packed-interleave2-rd --arms mlx-bun-serial --context 4096 --tokens 192 --workload-seed <block>` alternated with the default arm across blocks, plus the RTN4 affine artifact with `--arms mlx-bun-serial,mlx-lm` (the only same-artifact oracle cell); quiet preflight passing; distinct `--out` per block. | Any change to the controlled path: native pack bump, artifact layout change, new kernel default. |
2185
- | R1 | Packed prefill tile decode plus matmul | **Adopted in the v0.4.0 default.** Variant 11 (tiled axis-1 gate/up, M=5..32) and variant 12 (split-K axis-0 down, M=5..8) reconstruct bf16 weights inside tiles with exact full-model logits/state/continuation; six native paired blocks improve eligible M; six raw-completion HTTP pairs per lane improve TTFT and complete time (six-token prompt, 8/64 output tokens); the second tile pass improves eight-request throughput and B=1 TTFT in six pairs. All 40 larger tile geometries at M=128/512 are exact but none beats expansion plus native matmul in six AB/BA pairs. On MLX 0.32.2/M3+ the M5..15 axis-1 path uses the wide-prefill kernel (native `gemv_wide` arithmetic); six HTTP pairs per lane improve TTFT in every pair, decode and RSS unchanged. | Trellis variant 13 is the shipped default; older variants remain explicit controls. | `variant11-full-model-review.json`, `trellis-v11-http{,-review}.json`, `variant12-full-model.json`, `trellis-splitk-{screen,tuning,full-model}-review.json`, `trellis-v12-combined-http{,-review}.json`, `trellis-v12-combined-native-review.json`, `trellis-v12-native-failure-replay.json`, `trellis-tile-layout-screen-review.json`, `trellis-tile-full-model-review.json`, `trellis-splitk-bm8-{other-bits,full-model}-review.json`, `trellis-tile-integrated-forward-review.json`, `trellis-tile-http-review.json`, `trellis-tile-seeded-serial-http-review.json`, `trellis-tile-native{,-review}.json`, `trellis-large-prefill-screen{,-review}.json`, `mlx-upgrade-0.32.2/trellis-wide-{screen,perf,full,integrated-full}`, `mlx-upgrade-0.32.2/trellis-wide-http{,-review}.json`, `mlx-upgrade-0.32.2/trellis-wide-continuous.json` | Existing six-pair serial/default/combined comparisons and final-source native gates are accepted. Reuse them; broader pressure and final report work remain separately tracked in Phase 6. | A tile geometry beating native matmul at M≥128 on real k3 matrices, or a GPU generation that changes native small-M dispatch. |
2186
- | R2 | Bounded expansion scheduling | **Repeatable win (opt-in).** Unrestricted deferral (variant 9) and unrestricted async submission gain on short prompts but fail the saved-agent pressure gate (Metal insufficient memory at the 12,954-token request). The bounded policy (async only while MLX active allocation is below 75% of the recommended working set) passes serial and continuous pressure gates; integrated six HTTP pairs per lane: TTFT -4.00%/-3.96% at 128 prompt tokens (six wins), -1.43%/-1.40% at 512; wall -0.63..-0.88%; decode flat; native M16/128/512 forwards -2.09/-6.19/-2.80% with about +368/403 MB peak allocation. | `MLX_BUN_TRELLIS_ASYNC_EXPAND=1`, variant 13 only, default off. | `variant9-full-model.json`, `trellis-v13-boundary-full-model{,-review}.json`, `trellis-v13-boundary-http-serial{,-review}.json`, `qwen-long-boundary-serial{,-review}.json`, `qwen-long-async-serial{,-review}.json`, `trellis-v13-bounded-full-model{,-review}.json`, `qwen-long-bounded-{serial,default}{,-review}.json`, `trellis-v13-bounded-http-{serial,default}{,-review}.json`, `trellis-async-integrated-{typecheck,hygiene,model-free}.txt`, `trellis-async-production-full-model{,-review}.json`, `trellis-async-production-http-{serial,default}{,-review}.json`, `trellis-async-production-long-{serial,default}{,-review}.json` | The combined variant-13/fused-k8v3/MTP3 seven-request pressure gate passes on M4 after the existing M1 gate: all responses and complete usage match across roomy sync, constrained sync and constrained async arms; both threshold branches execute and persistence completes. See benchmarks.md and `reports/prefill-observation/combined-tq-mtp-pressure{,-review}.json`. Retain opt-in selection: the measured complete-request gain is modest and expansion overlap increases live allocation. Reopen for a changed model/barrier or a materially better timing/memory tradeoff; do not repeat the unchanged pressure gate. | A change to the memory headroom guard or to per-layer cache evaluation boundaries (R16/R17). |
2187
- | R3 | Axis-0 scatter layout and split-K | **Adopted in the v0.4.0 default.** Variant 8 (balanced word-aligned 3-bit scatter, all 32 lanes; k3/T256/L≤12) and variant 10 (scatter decode shared across M=2..4) pass exact full-model gates and improve M=1/2/4 and M=2..4 in six native blocks; row-loop unrolling not retained. A threadgroup integer codebook restricted to the M3/4 k3 interleaved down projection: six pairs -1.44/-2.00% forwards, six MTP HTTP pairs -1.07/-1.27/-1.19% complete time (5/6, 5/6, 4/6 wins), six four-request cohorts -1.49% (4/6); M1 loses and stays procedural; folded into variant 13. A 2.59% M128 control slowdown in one sequence was not reproduced by two controls. Variant 6 unchanged. | Trellis variant 13 is the shipped default; older variants remain explicit controls. | `balanced3-screen/`, `scatter-unroll-screen/`, `aligned3-screen/`, `variant8-paired/`, `variant8-full-model.json`, `shared-scatter-screen/`, `shared-scatter-all-screen/`, `variant10-full-model.json`, `trellis-threadgroup-codebook.json`, `trellis-threadgroup-scatter{,-m3}{,-review}.json`, `trellis-scatter-full{,-repeat}{,-review}.json`, `trellis-scatter-http{,-repeat}{,-review}.json`, `trellis-scatter-prefill{,-review}.json`, `trellis-scatter-sequence{,-review}.json`, `trellis-scatter-http-trace{,-review}.json`, `trellis-scatter-cohort-v2{,-review}.json`, `trellis-scatter-integration-source-change.json`, `trellis-scatter-integration-focused-tests-final.txt`, `trellis-scatter-integration-typecheck.txt`, `trellis-scatter-integrated-full{,-review}.json`, `trellis-scatter-integrated-http{,-review}.json`, `trellis-scatter-integrated-cohort{,-v2}{,-review}.json` | Existing six-pair serial/default/combined comparisons and final-source native gates are accepted. Reuse them; broader pressure and final report work remain separately tracked in Phase 6. | k2/k4 down projections (only k3 interleaved is qualified) or a new bit allocation from R19. |
2188
- | R4 | Axis-1 reduce and gate/up fusion | **Adopted in the v0.4.0 default.** Variant 7 shares each decoded gate/up weight across M=2..4 with fused gate/up, keeping the variant-6 accumulator order; exact matrix/MLP/full-model gates at M=1..5 and six AB/BA blocks retain the complete-MLP gain; the last-position append sweep confirms the M=4/5 cost discontinuity. Sharing activation loads across 2/4/8 output rows per SIMD group loses at k3 M=1; smaller threadgroups do not rescue it. The M=1 decode kernel is unchanged; the 64/128/256-thread and accumulator sweep with spill/occupancy inspection never ran because per-dispatch counters are unavailable. | Trellis variant 13 is the shipped default; older variants remain explicit controls. | `paired-shared-m/`, `variant7/`, `shared-m-full-model.json`, `shared-m-append-lengths.json`, `trellis-shared-rows-k3-r*-m1.json`, `trellis-shared-rows-k3-r*-s*-m1.json` | Missing resource: per-dispatch GPU counters or an Instruments shader profile (unsupported on the M4 Pro) to drive the M=1 thread/rows/accumulator sweep. | Kernel-level GPU timing becomes available, or a k mixture changes gate/up bit widths. |
2189
- | R5 | Decode primitive | **Measured loss.** Every alternate decoder loses at M=1 (M4 Pro): device f32 LUT (all bit widths), constant int16 table (0.802 vs 0.331 ms reduce, 0.747 vs 0.443 ms scatter, 1.474 vs 0.615 ms gate/up), device/threadgroup fp16 tables, and a constant int16 table on MLX 0.32.2 (nearly 2x complete MLP). The integer y-mad rewrite is exact with no useful gain; the readable expression stays. The only retained table is the scoped M3/4 scatter codebook (R3). The activation audit finds the packed fused SwiGLU uses a float32 precise-exp sigmoid unlike compiled MLX: a Lab distinction, no default change. | None. | `lut6-*.json`, `trellis-codebook.json`, `trellis-codebook-scoped{,-review}.json`, `trellis-constant-short-k3-m1.json`, `trellis-device-half-k3-m{1,4}.json`, `trellis-threadgroup-half-k3-m{1,4}.json`, `mlx-upgrade-0.32.2/trellis-constant-{screen,review,invalid-attempt}.json`, `trellis-y-mad-manifest.json`, `trellis-y-mad-k*-m*.json`, `trellis-activation-audit.json` | None for exact rewrites; a changed code family (QTIP/YAQA computed codes) needs a new artifact plus the KL/MMLU/tGSM/rawGSM screen before any kernel. | A hardware generation with faster threadgroup/constant memory relative to ALU, or a new code family with quality evidence. |
2190
- | R6 | Offline repacking without re-quantization | **Repeatable win (opt-in artifact).** Two-block interleaving of k3 axis-0 code words inverts to identical code bytes; prototype readers preserve 35 full-model cases. A separately written lossless artifact (quantizer `--interleave-codes`) read by every kernel from one resident code copy: six native pairs improve single-token/M4 forwards and 64-token generation in every pair with equal peak allocation; six serial and six default-scheduler HTTP pairs improve decode at 6/128/512 prompt tokens in every pair; TTFT small or mixed; RSS flat. | Not a default artifact change; served benchmarks use `Qwen3.8-27B-q3-trellis-ldlq-k300-packed-interleave2-rd`. | `trellis-block-interleave-screen-review.json`, `trellis-block-interleave-full-model-{g2,g10}-review.json`, `trellis-block-interleave-native-generation-g2-interface-review.json`, `trellis-block-interleave-http-{serial,default}-review.json`, `trellis-interleaved-readers-screen-review.json`, `trellis-interleaved-readers-full-model-count-review.json`, `trellis-interleaved-readers-order-full-model-review.json`, `trellis-interleaved-vector-schedule-screen-review.json`, `trellis-interleaved-readers-schedule-full-model-review.json`, `trellis-interleave-integrated-tests.txt`, `trellis-interleave-integrated-tail-tests.txt`, `trellis-interleave-model-free.txt`, `trellis-interleave-artifact-review.json`, `trellis-interleave-artifact-native-fd-review.json`, `trellis-interleave-encoder-tests.txt`, `trellis-interleave-artifact-http-{serial,default}-review.json`, `reports/prefill-observation/interleave-cache-shared-{0..11}.md.json`, `interleave-cache-shared-review.json` | **Accepted.** Six balanced original/interleaved pairs on M4 use the default shared scheduler, KV4/MTP2 and RAM/SSD prompt caching. All requests, complete usage and restart checks match, with decode and cached completion improvements in every pair. Machine activity and timing limits are recorded in benchmarks.md; no additional unchanged serial run is required. | Expanded state-window index variant (bytes for ALU) untested; k2/k4 interleaving unqualified. |
2191
- | R7 | Small-M packed kernel | **Adopted in the v0.4.0 default.** Shared-M variants 7/8/10 reuse decoded weights across M=2..4 (R3/R4); the M=4/5 whole-model cost discontinuity is confirmed and the packed-to-expanded crossover is also a numerical boundary: the M≤8 crossover prototype wins MLP time but changes output bytes for every bit width, so it is Lab and not retained. The wide-prefill kernel (variants 11–13 on MLX 0.32.2/M3+) shares each decoded row across all M=5..15 vectors reproducing native `gemv_wide` arithmetic: 36 forward/state/continuation cases and six generations exact; six HTTP pairs per lane improve TTFT in every pair with decode/RSS unchanged. Fill spans and MTP verifies inherit these curves (R15/R20). | Trellis variant 13 is the shipped default; older variants remain explicit controls. | `shared-m-append-lengths.json`, `m8-screen/`, `mlx-upgrade-0.32.2/trellis-runtime-full`, `mlx-upgrade-0.32.2/trellis-wide-{screen,perf,full,integrated-full}`, `mlx-upgrade-0.32.2/trellis-wide-http{,-review}.json`, `mlx-upgrade-0.32.2/trellis-wide-continuous.json` | M1 qualification of the existing wide kernel fails exactness, including every full-width cell; retain earlier dispatch there. A different pre-M3 kernel or the M≤8 crossover requires its own numerical and quality gates. | Any MLX runtime bump that changes small-M dense dispatch (rerun `trellis-runtime-full`). |
2192
- | R8 | Fused GDN conv/state/SiLU | **Measured loss.** A fused convolution/SiLU/copied-tail prototype matches bf16/f32 outputs and live tail at B=1/2 only with MLX's typed sigmoid expression; it passes full packed-model logits, live state, continuation and speculative rollback. Against an independently materialized baseline its full-model timing is approximately flat with similar peak memory; unpromoted. Side finding landed as default: `mlx_copy` aliasing retained the source buffer; compact state materialization now uses stock DynamicSlice. | None (DynamicSlice materialization is a memory fix, not a speed default). | `gdn-stage-probe.json`, `conv-probe-typed-sigmoid.json`, `qwen-conv-materialized-packed.json`, `materialize-final-packed-comparison.json` | None; the missing instrument is per-dispatch GPU timing of the conv stage. | Attribution shows conv/SiLU above 3% of the decode critical path. |
2193
- | R9 | GDN norm, gates and recurrence | **Measured loss.** Threadgroup layouts, fixed sequence lengths, unrolling, compiled wrappers and typed sigmoid fusion pass all 114 shape cells after correcting a float32 sigmoid rewrite that broke bf16 recurrence. A compiled fixed-length candidate preserves full-model identity but its isolated gains mostly disappear in full forwards; a fused recurrence + output RMSNorm + gate kernel passes 60 isolated cells and small-M full-model checks with a gain too small to integrate. Fixed-shape CompiledFunction over the 16 SSM groups (R16) gives -0.062%/-0.202% median. Production dispatch unchanged. | None. | `gdn-specialization-typed.json`, `gdn-static-full-model-review.json`, `gdn-fused-norm-probe.json`, `gdn-fused-norm-full-model-review.json`, `mlx-upgrade-0.32.2/qwen-fixed-ssm-groups-r6.json`, `mlx-upgrade-0.32.2/qwen-fixed-ssm-groups-rtn4-internal.json`, `mlx-upgrade-0.32.2/qwen-ssm-hot-review.json` | None until prefill-regime attribution shows the recurrence dominates (decode M=1 was the measured target). | Prefill attribution, or a transposed-state layout with a measured M=1 win. |
2194
- | R10 | Parallel/chunkwise GDN prefill | **Prefill attribution complete; no parallel rewrite retained.** Current packed-target controls and an operation observer preserve complete hidden/state hashes at 1k/4k/8k on both Macs. Gated-delta work is roughly 2.6–2.7% of M4 complete prefill, so it is not the principal bottleneck. M1 instrumentation perturbs larger runs. A chunkwise/scan formulation remains Lab because changing reduction order requires a separate quality contract. | None. | `upstream/sources.json` | Attribution is accepted; prioritize the measured expansion/projection/attention costs. A later chunkwise Metal arm needs same-input recurrent-state and held-out quality checks before any adoption. | Not applicable; never opened. |
2195
- | R11 | Affine QMV/QMM and native builds | **Inconclusive.** Shared-M affine kernels won M4/8 (and M3/5/6/7 4-bit, compact 3/8-bit) in six full-model pairs and six HTTP pairs per configuration with exact outputs and flat B1; cross-model, Gemma 12B large projections win while MiniCPM/Llama regress; a compiled-call cache was closed. MLX 0.32.2 (native pack 0.4.0) superseded it: upstream `qmv_wide` implements the same reuse with different arithmetic, so the custom kernel and its flag were removed (§7.12); frozen source controls keep it. New-core affine Q3 gate/up operations beat the old shared ops in all six blocks, Q4 mixed, Q8 loses (operation level); RTN4 short decode flat, long-prefill timing order-dependent; twelve RTN4 oracle cells and 4K/8K prompts byte-exact on both cores. No end-to-end Qwen gain from the runtime change is established. | Native pack 0.4.0 (MLX 0.32.2) is the pinned runtime; no flag. | `affine-qmv-screen.json`, `affine-qmv-compiled.json`, `affine-shared-m-probe{,-initial}.json`, `affine-shared-m-debug-scale-bits.json`, `affine-shared-m-full-model-{packed,rtn4}-review.json`, `affine-shared-m-http-rtn4-review.json`, `affine-shared-m-production-full-model-rtn4-review.json`, `affine-shared-m-shapeless.json`, `affine-shared-m-integrated-unit.txt`, `affine-shared-m-integrated-http-rtn4-review.json`, `affine-shared-m-width-{rtn4,full-model-rtn4}-review.json`, `affine-shared-m-all-bits-*.json`, `affine-shared-m-broader-*`, `shared-affine-frontier-http-{rtn4,compact}-review.json`, `affine-compiled-call-cache-{full-model,http}-compact-review.json`, `affine-shared-cross-model-exactness.json`, `affine-shared-cross-model-{gemma12,gemmae4b,minicpm5,llama1,llama3}-review.json`, `affine-cross-model-matrix-{inventory,screen,screen-review}.json`, `affine-cross-model-matrix-gemma12-repeat.json`, `affine-head-batched-decode-mfirst-{llama1,llama3}-review.json`, `affine-shared-head-http-{llama1,llama3}-overlap-review.json`, `affine-large-projection-*.json`, `affine-nonfast-*-review.json`, `mlx-upgrade-0.32.2/affine-{old,new}-screen.json`, `mlx-upgrade-0.32.2/affine-runtime-repeat{,-review}.json`, `mlx-upgrade-0.32.2/runtime-oracle-rtn4{,-macos14}.json`, `mlx-upgrade-0.32.2/runtime-oracle-long-macos14.json`, `mlx-upgrade-0.32.2/native-runtime-screen{,-review}.json`, `mlx-upgrade-0.32.2/final-source-gates.json` | Quiet-machine six-pair old-core vs 0.32.2 `bench-serve all` on the RTN4 artifact with the same-artifact mlx-lm arm, to separate the runtime change from kernel changes. | A native pack bump, or MLX changing `qmv_wide` eligibility for GQA6/D256 or Q8 shapes. |
2196
- | R12 | Norm/residual/activation/projection fusion | **Measured loss.** Residual-add/RMSNorm kernel (90 synthetic cases exact; six packed pairs at M1/4/8/128): M1 slightly slower, M4/8 flat, M128 varies. Fused affine gate/up/SwiGLU with the typed sigmoid (48 RTN4 cells exact): only M=1 wins in isolation, full-forward gain too small. Multimodal RoPE shared angles/direct strides (108 cases exact): M128 slightly slower, M512 flat, image encoding excluded. None integrated; helpers removed. Full-attention output-gate and QKV concatenation fusions were enumerated but not prototyped. | None. | `residual-rms-screen-scalar-review.json`, `residual-rms-full-model-packed-review.json`, `affine-gateup-debug{,-typed}.json`, `affine-gateup-typed.json`, `affine-gateup-full-model-review.json`, `mrope-reuse-screen-review.json`, `mrope-stride-full-model-packed-review.json` | None until per-kernel attribution shows elementwise/norm dispatches exceed 3% of the decode critical path. | Attribution evidence as above, or a real vision-request benchmark for mRoPE. |
2197
- | R13 | Attention and KV | **Adopted for TurboQuant decoding.** Joint TurboQuant K/V packed decode plus row-grouped inverse rotation at N≥8192: six 8,846-token HTTP blocks on R6 k8v3 improve decode 83.87% and complete time 12.77% versus the original codec, inverse rotation adds 5.39%/1.05%; on MLX 0.32.2 the inverse improves decode 4.69% (R6) and 5.98% (RTN4) in every pair, R6 complete -0.79% all six, RTN4 complete inconclusive; six MiniCPM and six Gemma deferred-consumer pairs improve complete time. Direct packed-key attention is exact but 6–19% slower than joint decode plus native SDPA (closed). Dense register-resident attention loses timing; Steel D256 fails one KL screen (Lab). KV append census: ordinary appends copy only the new row, rejecting the whole-cache-copy hypothesis; no append kernel. bf16-KV rows are unaffected. TurboQuant now composes with shared ordinary and speculative rows, including the accepted long cached/SSD run. | `MLX_BUN_TURBOQUANT_FUSED_DECODE` defaults on; `=0` retains the unfused control. Cache quantization remains an independent opt-in; details in turboquant.md. | `tq-value-*{,-review}.json`, `tq-kv-screen.json`, `tq-kv-independent.json`, `tq-kv-repeat{,-review}.json`, `tq-kv-full{,-review}.json`, `tq-kv-policy-http{,-review}.json`, `tq-kv-long-full{,-review}.json`, `tq-kv-rotation-{screen,repeat,rows-screen,rows-repeat,long,long-http}{,-review}.json`, `tq-kv-rtn4-full{,-review}.json`, `tq-kv-nonfinite.json`, `tq-kv-minicpm-full{,-review}.json`, `tq-kv-gemma-e4b-full{,-review}.json`, `tq-kv-integrated-*{,-review}.json`, `tq-kv-integrated-rtn4-http-acceptance.json`, `tq-kv-memory{,-review}.json`, `allocator-capacity-repro.json`, `tq-kv-inverse-integrated-r6-full{,-review}.json`, `mlx-upgrade-0.32.2/{r6,rtn4}-kv-inverse-full.json`, `mlx-upgrade-0.32.2/inverse-kv-http{,-replacement,-review,-isolation}.json`, `mlx-upgrade-0.32.2/deferred-kv-http{,-review}.json`, `tq-key-sdpa-screen.json`, `tq-key-sdpa-complete-repeat{,-review}.json`, `steel-attention-tune-manifest.json`, `attention-cpu-check.json`, `attention-oracle-check.json`, `attention-full-model-packed-128-512-review.json`, `dense-attention-memory-tune-review.json`, `kv-append-donation-probe{,-review}.json`, `kv-append-model-trace-2049{,-review}.json`, `kv-append-http-text-census{,-review}.json`, `kv-append-native-8193{,-review}.json` | The combined pressure gate is complete on both Macs. Current default shared off/default comparisons pass on M1 MiniCPM and M4 packed Qwen/MTP3; cached complete time improves in both orders, with mixed short-Qwen timing documented in benchmarks.md. The earlier native, six-pair serial and deferred-consumer gates remain accepted; no unchanged gate needs repeating. | MLX ships fused quantized SDPA for GQA6/D256, or a new codec shape/model exposes a numerical or complete-request regression. |
2198
- | R14 | Vocabulary head and sampler | **Adopted normalized greedy kernel; other candidates remain characterized separately.** Same-input model/operation checks pass on both Macs. MiniCPM standard AB/BA throughput improves and packed Qwen MTP3/TQ stays effectively flat. **Inconclusive.** Compiled Metal grammar bitmask (`MLX_BUN_TOKEN_MASK=metal`) preserves mask bytes and sampled IDs at three vocabularies and beats the host loop in eight paired blocks, but six compact HTTP pairs at B1/B4 are inconclusive (B1 flat, B4 regresses under residual swap); host masking remains default. Top-p inverse-permutation removal is exact in 216/180 cases; Qwen packed serial six pairs +0.183% complete time (loss), Llama 1B -0.399%/-0.380% with six wins per lane; no production change. DSA sort keys reduced to uint32 are integrated as a shared-operation win (selection latency -10.47..-15.80%), not a Qwen result. Grouped greedy verify readback closed (R21). The exact fused matvec/argmax head was never prototyped. | Shared normalized greedy selection is the default. Grammar-mask Metal selection remains opt-in; DSA uint32 keys are integrated. | `token-mask-probe.json`, `token-bitmask-unit.txt`, `token-bitmask-grammar-metal.txt`, `token-mask-sampling{,-review}.json`, `grammar-mask-http-compact-review.json`, `top-p-scatter-screen-v2{,-review}.json`, `top-p-scatter-compiled-screen{,-review}.json`, `top-p-lifetime-{source,native,scatter,metal}.json`, `top-p-sampler-screen-v2{,-review}.json`, `top-p-native-screen{,-review}.json`, `top-p-http-screen{,-review}.json`, `top-p-http-r6-serial-repeat{,-review}.json`, `top-p-http-llama-repeat{,-review}.json`, `dsa-order-u32-{screen,repeat}{,-review}.json`, `dsa-rank-u32-{screen,repeat}{,-review}.json`, `dsa-model-screen.json`, `dsa-rank-u32-model-tests-v2{.txt,.transform.json}`, `dsa-production-{unit-v2,typecheck-v2,model-free,hygiene}.txt`; `reports/prefill-observation/sampler-*` | Quiet-machine six-pair grammar-mask host vs metal at B1/B4 on a structured-output fixture (the only open candidate with a positive operation result). | Head attribution shows the vocabulary projection or readback material for greedy requests. |
2199
- | R15 | Deterministic no-verification replay | **Repeatable win (opt-in).** Strict fill has parser-state guards (complete `</parameter>` delimiter, request-local tool-only context), a schema open-object compiler fix, and model-owned four-token append chunks that reproduce M1 arithmetic via broadcast `[M,1,K]` weight views and split at MLX attention transitions (KV 1023/1024/8192/32768/65536 on `applegpu_g16s`). Final internal-SSD comparison: twelve balanced pairs, 96 exact responses, zero verification; complete time -9.83%/-15.40% (R6 weather/bash) and -1.63%/-2.94% (RTN4), every pair improving; tool output is buffered so this is not a decode-rate result. Staged-body prototype flat, closed. Quantized-KV composition: TurboQuant k8v3 passes after a lease fix, affine KV4/KV8 now preserve complete state after one-token attention is retained within shared projection appends. The qualified model binding declares KV4/KV8 and K8V3 support; delayed conversion passes real-generation state checks. Both quants retain exact HTTP responses in six-pair affine and TQ comparisons. Saved tool-history fixtures pass 20 affine pairs; held-out task quality and quantized verification remain separate. Shared strict fill now composes the common preparation, sampler, row state and RAM/SSD cache. Its qualified B1 append, delayed precision transitions and B2 retirement into B1 pass full hidden/cache/continuation checks; wider rows preserve one-position arithmetic. Six M4 HTTP arms complete 108 responses with exact paired outputs/counts/cache coverage and durable SSD restarts. The sequential fixture total improves 13.50%/13.57% against shared fill-off and remains within 0.13% of serial strict fill; concurrent latency tradeoffs remain. See benchmarks.md and reports/prefill-observation/shared-fill-http*.json. | `MLX_BUN_FILL=strict`, `MLX_BUN_FILL_APPEND_CHUNK_SIZE=0` (model limit), `MLX_BUN_FILL_MAX_SPAN=32`; default off. | `fill-parser-boundary-r6.json`, `fill-boundary-tokenizer-audit-v4.json`, `fill-boundary-cpu-tests-v8.log`, `fill-boundary-native{,-m1,-batch1,-batch1-v2-rtn4}-r6.json`, `fill-first-layer-{shape-probe,batched-m1}.json`, `fill-boundary-http-{screen,repeat,review}.json`, `fill-append-*.json`, `fill-append-final-model-free.log`, `fill-append-state-ownership-native-test.log`, `fill-schema-*`, `strict-fill-variant{6,7}.txt`, `strict-fill-v1{0,1}-cap{32,4}-served-eos.json`, `fill-adversarial-state-v12-eos-review.json`, `fill-state-v12-cap{32,4}-{eos,seed42}.json`, `fill-identical-input-append-review.json`, `fill-chunked-*-review.json`, `fill-integrated-{state-v12-seed42,http-packed}-review.json`, `fill-chunked-integrated-{unit,model-free,typecheck,hygiene}.txt`, `fill-staged-unit.txt`, `fill-staged-state-v13-seed42-review.json`, `fill-staged-complete-requests-review.json` | Frozen held-out real-session/adversarial corpus through `MLX_BUN_TEST_FILL_MODEL=<dir> MLX_BUN_FILL=strict bun test tests/parity/fill-strict.test.ts` on both quants (token IDs, stop decisions, subsequent logits/state), then a quiet six-pair HTTP repeat. | A Qwen tool-template or parser change, tool schemas with pattern properties, or a chunk-limit qualification on another GPU. |
2200
- | R16 | MLX graph and loop | **Earlier output adopted.** Early first token in the serial loop: six native pairs improve first-token latency at 6/128/512 tokens with exact tokens/state/usage; six chat HTTP pairs (84 requests, 42 exact) improve first visible output with complete time flat; raw prompts show no client gain because token 220 emits no event. The suffix screen finds a prefill-shape effect after a one-token return (seven packed/six RTN4 cases change state); explicit M=1 alignment restores exactness. The final caller-owned alignment passes both-machine state/continuation checks and monitored M4 serving comparisons; first visible output improves with complete time close. Closed: shape-specific compiled-call cache, Metal launch-config cache (MiniCPM HTTP mismatch unresolved), untouched-finalize elision (-0.069%), submission/traversal limits for Qwen (Llama 25/25 gives -2.44% native and -1.86..-3.02% HTTP, diagnostic, not integrated), fixed-input proxies, per-layer graphs (RTN4 fails identity), whole-model graph (slower), SSM-group compilation (-0.06%/-0.20%). Shapeless custom kernels are an upstream MLX limitation. | `MLX_BUN_EARLY_FIRST_TOKEN` defaults on; `=0` retains the old output order. | `first-yield-*`, `first-token-production-long-{serial,continuous}{,-review}.json`, `first-token-lifecycle-{llama,qwen}{,-review}.json`, `affine-compiled-call-cache-{full-model,http}-compact-review.json`, `metal-config-cache-*`, `mlx-untouched-finalize-source-manifest.json`, `untouched-finalize-*`, `graph-schedule-screen-plan.json`, `graph-schedule-screen{,-review,-contamination}.json`, `graph-schedule-rtn4-rescreen-v2{,-review}.json`, `graph-schedule-llama-repeat{,-review}.json`, `graph-schedule-llama-http-repeat{,-review}.json`, `mlx-upgrade-0.32.2/custom-kernel-compile-probe.json`, `mlx-upgrade-0.32.2/fixed-custom-probe.json`, `mlx-upgrade-0.32.2/qwen-fixed-region-{r6,rtn4}-v{2,3,4}.json`, `mlx-upgrade-0.32.2/qwen-fixed-layer-{r6-full-v2,rtn4-full}.json`, `mlx-upgrade-0.32.2/compiled-region-probe.json`, `mlx-upgrade-0.32.2/qwen-fixed-hidden-regions-{r6,rtn4}.json` | Early-output native, HTTP, cancellation/overlap and cached/SSD acceptance is complete; see benchmarks.md for monitored repeats and activity limits. The MLX 0.32.2 submission screen is complete: retain upstream startup defaults, with the measured M4 Llama override available explicitly. The current native API has no model-scoped setter; revisit integration if that interface becomes available. See benchmarks.md for the cross-model results and activity records. | MLX adds shape-inferring CustomKernel or graph replay, or per-token host-overhead attribution changes. |
2201
- | R17 | Hybrid prefix and recurrent state reuse | **Implemented and accepted for generated reuse.** One cache owns immutable target/recurrent state and draft companions, original generated token IDs, session/content lookup, RAM residency and queued SSD persistence. Native and HTTP checks cover continued mutation, cancellation, earlier-boundary fallback and fresh-process restoration on both Macs. The saved Kanban miss/OOM sequence passes with identical output; the completed session-cache Kanban run hits every follow-up and flushes all snapshots durably. Its app-quality defects remain separate from cache acceptance. | Shared RAM/SSD publication and generated-token provenance are enabled; whole-file SSD and LRU remain selected after measured alternatives. | `reports/kanban-cache-fixed-fresh/`, `reports/kanban-cache-fixed-repeat-r1/`, `reports/kanban-session-cache-r2/`; [cache implementation](kv-cache.md#54-background-persistence-and-ram-residency) and [measured task comparison](../reference/benchmarks.md#full-kanban-with-session-cache-and-queued-persistence). | No missing generated-history implementation. Reuse the completed native/HTTP and full-task evidence; do not rerun unchanged gates. | A reproduced history-alignment, retention, durability or reuse regression. |
2202
- | R18 | Scheduler | **Early output and shared batching adopted.** Continuous-scheduler early yield (same `MLX_BUN_EARLY_FIRST_TOKEN` flag): six AB/BA blocks, 84 responses, 42 exact, median TTFT -7.66% code / -7.90% explanation / -5.63% JSON (74–77 ms) with complete time +0.04..+0.15%; the integrated one-block check gives -68..-90 ms; 120 streaming cancellation/arrival requests pass on both quants and lanes. Concurrency evidence for kernels: v6 vs v12 four-request waves improve every pair and the tile pass improves eight-request throughput (R1). The historical four-request kernel waves predate shared cohorts. B-wide prefill is now adopted, and current default serving uses shared ordinary/speculative execution; mixed iteration work is measured and remains off. Two opposite-order fixed-arrival repeated-wave comparisons now preserve all 84 paired outputs and improve aggregate throughput at loads two/four/eight. First-request completion and stream gaps retain a tradeoff; see benchmarks.md. Longer steady-state capacity remains separate. | Early first output defaults on; `MLX_BUN_EARLY_FIRST_TOKEN=0` retains the control. | `first-prepare-scheduler-{control,candidate}.txt`, `first-prepare-http-screen-plan.json`, `first-prepare-http-{screen,repeat}{,-review}.json`, `first-prepare-production-{unit,model-free,typecheck,hygiene}.txt`, `first-prepare-production-http-r6-v2{,-review}.json`, `first-token-lifecycle-{llama,qwen}{,-review}.json`, `trellis-concurrent-http{,-review}.json`, `trellis-tile-http-review.json`, `trellis-scatter-integrated-cohort-v2{,-review}.json` | The fixed-arrival repeated-wave cell is complete with preserved outputs and documented latency tradeoffs. Longer stationary capacity remains a distinct measurement; do not repeat the accepted wave test without a relevant source change. | A change to admission, mixed-work scheduling or output/cache boundaries. |
2203
- | R19 | Weight-quality allocation | **MLP cost/allocation screen complete; quality acceptance open.** Actual k2/k3/k4 fused gate/up and down costs are measured at M1/M3/M4/M16 on both Macs in forward/reverse order. All 228 unchanged-reader checks match. A discrete size-constrained objective runs 64 machine/row/latency-weight cells; zero weight reproduces k300 exactly. Modest latency weight finds little estimated decode headroom. Aggressive M1-prefill proposals trade more external-codec sensitivity loss for time. Those losses are ranking proxies, not Trellis quality. No candidate is quantized or promoted. Existing Q3 and lossless-interleaving quality evidence remains unchanged. | Keep the existing artifact. | `reports/prefill-observation/r19-cost/`; benchmarks.md latency-aware MLP allocation screen | Teacher-based quantization and frozen KL/MMLU/tGSM/rawGSM screens; non-MLP allocation and calibration/rounding choices remain open. Checked primary model directories lack a complete original Qwen bf16 snapshot; promoted bits cannot be recovered from k300. | No measured full-model speed or quality claim from the proposal cost model. |
2204
- | R20 | MTP economics | **Repeatable win (opt-in).** Six balanced three-arm blocks versus native full-prefill on the packed artifact: fixed two drafts change complete time -43.22%/-38.81%/-44.92% (code/explanation/JSON) with every pair improving, TTFT -5.5..-8.4%, peak RSS +653 MiB; RTN4 -34.95%/-26.95%/-38.48%. Adaptive one-to-three drafts adds about 3% (ratios 0.9698/0.9782/0.9624) and stays research-only. Folded 4-bit/8-bit MTP heads: -1.48/-3.67/-2.95% and -0.65/-2.29/-1.86% with peak RSS 12.53/12.74 vs 13.04 GB; 1,184 vocabulary rows and 48 state samples byte-exact against serial replay. EOS and finish-reason accounting fixed. The quiet M1 Max control (0.821x at gamma 2, 2026-08-18) predates the kernel work. Shared serving has short depth-2/3/4 comparisons, native depth-3 coverage and completed late-context MTP1/2/3 controls. Current KV4/MTP2 and fused K8V3/MTP3 both pass the 78,678-token cached/SSD workload. KV4/MTP2 remains the measured long-agent recommendation; depth 3 crosses a different KV4 value-product dispatch boundary. See benchmarks.md. | `--draft-kind mtp --num-draft-tokens 2` opt-in; EOS/finish-reason fixes landed. | `mtp-v*-gamma*.json`, `mtp-corpus-screen/`, `mtp-screen-prompts.json`, `mtp-heldout-{plan,http,http-review}.json`, `mtp-heldout-native{,-review}.json`, `spec-token-counts-*.txt`, `mtp-post-eos-http{,-review}.json`, `spec-eos-serving-*.txt`, `mtp-eos-budget{,-integrated}-http{,-review}.json`, `spec-eos-continuous-*.txt`, `eos-budget-continuous{,-v2}-http{,-review}.json`, `mtp-quantized-draft-*-http{,-review}.json`, `mtp-draft-artifact-q4-{build,audit}.json`, `mtp-draft-quant-oracle.json`, `mtp-draft-artifact-q8-build.json`, `mtp-quantized-loader-*.txt`, `mtp-artifact-ownership{,-v2}.json`, `mtp-artifact-{screen,repeat}-http{,-review}.json`, `mtp-artifact-native{,-context}{,-review}.json`, `mtp-artifact-context-screen-http.json`, `mtp-matched-prefill-{r6,rtn4}-{screen-http,repeat}{,-review}.json`, `mtp-rtn4-screen-{plan,http,http-review}.json`, `mtp-rtn4-divergence-v2-audit{,-review}.json`, `mtp-rtn4-prefill-control{,-review}.json`, `mtp-v10-{planets,prose}-gamma{2,3}.json`, `mtp-provider-dispose-{before,after}.json`, `mtp-provider-ownership-tests.txt`, `mtp-post-dispose-http.json` | Late-context KV4 depths 1/2/3 and ordinary controls are complete; the current ordinary cached-repeat failure is resolved. TQ/MTP3 passes the original context, RAM repeat and SSD restart. Current-source KV4/MTP2 and automatic prefill sizing pass; KV4/MTP2 remains the measured agent recommendation. | Any change to verify-window arithmetic (KV4 head pairing, fused KV) or a DFlash2 drafter (R21). |
2205
- | R21 | Other exact speculative sources | **Shared lookup implemented; DFlash2 unimplemented.** Qwen DFlash2 (the z-lab artifact behind the oMLX record the video cites; block size five, native MTP off) needs dynamic grouped causal convolutions around attention and MLP plus a top-16/rank-256 selector; the existing DFlash provider does not implement that architecture, so loading the checkpoint would not be DFlash2. Grouped greedy verify readback is closed: six three-arm blocks, 84 exact comparisons, concatenation improves only 0.33%/0.06%/0.23% and the evalAll variant regresses JSON 0.44%. Prompt lookup is now adopted through the shared variable-proposal verifier, with both-machine bf16/KV4/KV8/TQ B4 serving, generated RAM/SSD and MTP regression checks. M4 arm orders show small single-request gains and lower aggregate throughput with changed concurrent outputs; it remains optional. The DSpark/DFlash execution provider has seeded-fixture coverage, but no trained checkpoint exists. This does not implement DFlash2. SpecPrefill remains a separate approximate Lab arm. | Shared prompt lookup is available; trained-drafter performance remains unmeasured. | `video-dHK90xc9Q64/`, `video-dHK90xc9Q64/dflash-source-manifest.json`, `spec-grouped-greedy-screen.json`, `spec-grouped-greedy-eval-screen.json`, `spec-grouped-greedy-three-http{,-review}.json` | Missing resource: a DFlash2 architecture/selector port with target-state/rollback identity and draft residency, then a three-arm block (ordinary / fixed-two MTP / DFlash2) on the held-out prompts. | The port exists, or an exact n-gram source shows at least 3% on the saved Kanban history. |
2206
- | R22 | Residency and shared memory | **mmap loss; range-construction improvement.** Page-aligned file-backed weights through Metal roots are exact in every payload/output case, but six native pairs give +0.25% (later +0.02%) on 64-token generation with no faster pair, six serial HTTP pairs +0.04..+0.14% complete and +0.14..+0.21% decode, and the balanced cold-start follow-up is worse in five of six pairs (+18.42% first token, +12.93% first generation). Peak RSS falls from 12,182,749,184 to 482,508,800 bytes as file-backed accounting only; physical RAM saving unproven. A read-only donation hazard was found and fixed in the prototype before closing; helpers removed. Retained as memory correctness, not speed: the 8 MiB bounded range cache in `mlx/ops.ts` (Kanban sustained run peak active -1,582,612,480 bytes, +2.171% time in one pair) and per-chunk draft-KV evaluation. | Native long position ranges reduce operator/host-allocation work without a material model/serving speed claim; bounded range cache and per-chunk draft-KV evaluation remain memory fixes. | `mmap-page-window{,-pointer}-screen.json`, `mmap-weights-native-{llama1,packed}-screen.json`, `mmap-weights-native-packed-paired{,-review}.json`, `mmap-weights-http-serial{,-review}.json`, `mmap-weights-ownership-packed{,-mapping}.json`, `mmap-weights-single-consumer-lazy{,-mapping}.json`, `mmap-weights-whole-consumer-lazy.json`, `mmap-whole-consumer-source-integrity.json`, `mmap-donation-{ro,cow}-screen.json`, `mmap-managed-donation-screen.json`, `mmap-weights-managed-whole-consumer-lazy{,-mapping}.json`, `mmap-managed-submitted.json`, `mmap-weights-managed-native-{repeat,screen}{,-review}.json`, `mmap-initial-residency-attribution.json`, `mmap-lazy-view-ownership.json`, `mmap-weights-lazy-managed-native-screen{,-review}.json`, `mmap-prefault-native-screen.json`, `mmap-cold-native-repeat{,-review}.json`, `mmap-managed-shard-release{,-mapping}.json`, `mmap-managed-active-accounting-review.json`, `kanban-arange-{allocation-evidence,regression,micro-memory,reconstruction}.json`, `kanban-sustained-77k-owned-control.json`, `kanban-sustained-arange-comparison.json` | Native long int32 positions are accepted as an operator/host-allocation optimization after exact range/view/bound checks, six monitored M4 complete-forward pairs and two standard serving arm orders. Model and serving performance are effectively flat; the initial unmonitored regression is not reproduced. A reusable power-of-two prefix remains unselected after an inconsistent M1 screen. See benchmarks.md for activity records and limits. | A controlled page-cache-cold startup cell (§7.10) exists; mmap lost warm but cold was never controlled. |
2207
- | R23 | Media and task completion | **Inconclusive.** The fresh Pi Kanban task on the 12.14 GiB packed target with Luke's `qwen3.8-27b-q3_k_xl-coding-128k` profile (131072 context, xhigh thinking, temperature 0.6, seed 42; KV4, MTP depth 2, paired prefixes, MLX 0.32.2) completed in 3h 33m 7.685s with 130,494 output tokens over 62 requests, 79.706% draft acceptance, 11.916 GiB peak combined RSS; the untouched app passes the functional browser checks. Earlier attempts failed on a tool-parser bug, dropped reasoning history, Metal OOM at the 85,238-token request and OOM during sustained decode. The later accepted R17 session-cache Kanban run completes in 83m57s with 76,031 output tokens, every follow-up cached and durable final persistence; its two application defects remain recorded. The automatic-prefill task misses the app-quality target, while the completed fixed-256 integrated control meets it and reproduces the earlier initial response. Keep the task-comparison profile fixed; results and browser evidence are in benchmarks.md. No matched successful original-source run exists, so these different trajectories cannot supply an engine-only task-time speedup. Gemma image/audio shared execution now passes both-machine native/HTTP and monitored M4 ABBA comparisons with all 78 paired responses/counts unchanged; concurrent gains and individual latency costs are recorded in benchmarks.md. Qwen image/video shared execution also passes both-machine source/group/HTTP and M4 ABBA checks; full usage matches, while changed concurrent geometry changes some text. Qwen encoder objects now reuse the shared RAM/SSD cache, with both-machine native/HTTP, fresh-process SSD and M4 source-controlled timing acceptance. First-use weight hashing costs more; repeated images improve with exact responses/usage. Gemma encoder reuse also passes both-machine identity/HTTP and M4 ABBA/fresh-process SSD acceptance, with all 168 paired responses/usage exact and repeated-request gains. Gemma and Qwen generated media KV reuse now pass both-machine native/HTTP, fresh-process SSD and M4 ABBA comparisons. The shared media-prefix option is selected by default; output and precision boundaries remain documented. | Tool-parameter parser and `reasoning_content` alias landed as correctness fixes; no speed default. | `lukes-kanban/`, `kanban-final/optimized-mtp-invalid-32k-sleep/`, `kanban-final/luke-q3-128k-xhigh-{history-fixed,tool-values-fixed,mtp-memory-fixed,arange-bounded}/`, `kanban-final/comparison.html`, `kanban-capacity-110k-control.json`, `kanban-capacity-8k-final-comparison.json`, `kanban-capacity-110k-owned-final.json`, `kanban-memory-http-{owned,responsiveness}.json`; numbers in benchmarks.md Kanban sections | The requested integrated fixed-profile task is complete. An original-source run is needed only for an engine-only task-time claim; no such ratio is claimed. Gemma image/audio shared serving acceptance is complete. Qwen image/video shared serving acceptance is complete with documented geometry and latency limits. Qwen encoder-cache acceptance is complete. Gemma encoder-cache acceptance is complete. Prepared Gemma/Qwen media-prefix reuse is accepted through the same cache interfaces. Chunked media prefill and wider configurations remain separate work. | No engine-only task-time ratio without a matched baseline. R17 generated-history acceptance is complete and does not need another unchanged task run. |
2208
- | R24 | Larger departures | **Inconclusive.** Feasibility and operation screens exist. For the video's tq3-mini codebook format (eight-centroid indices, ten codes per uint32, 3.2 bits/value), the literal upstream `polar_qmv` through the Bun binding on synthetic matrices: explicit SIMD shuffles cut the 5120-to-17408 rotated operation 2.77–3.84% (every pair), and a fused fp16 expansion cuts large-prefill operation time 40.85–57.51% with about 765 MiB less temporary allocation. No production loader or kernel, no quality evidence; the checkpoint's reported agent failures are unresolved. Section 7.14 now records kernel, quality, memory and potential-benefit requirements for those candidates. A both-machine same-weight native activation-quantization screen is a measured loss; static size/training bounds are recorded. Actual-weight unweighted low-rank and sparse-residual screens now reject their simple variants. Packed forwards fail differentiation without a custom VJP; the expanded frozen-weight control succeeds. Calibrated quality and packed backwards remain open. | None. | `video-dHK90xc9Q64/`, `polar-qmv-screen-v2.json`, `polar-qmv-variants.json`, `polar-qmv-geometry.json`, `polar-qmv-repeat{,-review}.json`, `polar-expand.json`, `polar-expand-repeat{,-review}.json` | Next: activation-calibrated candidates and an explicit packed backward operation, if pursued after the measured simple-variant losses. The tq3-mini format still needs a loader and actual-checkpoint KL/MMLU/tGSM/rawGSM before a model claim. | An artifact with quality evidence at or below Q2b bytes, or the operation gains reproduced whole-model. |
2209
-
2210
- Josh's original direction is to "only ask the model to decode tokens that we
2211
- can't reasonably already know." This includes reasoning snippets copied into
2212
- tool arguments, repeated atomic values such as URLs, and predictable tool JSON
2213
- structure and field order. The goal is deterministic continuation wherever the
2214
- application can establish the text, with known-text proposals where the model's
2215
- choice remains uncertain. Prefix-cache reuse avoids rereading history; it does
2216
- not by itself avoid generating the same text again. Strict appends and verified
2217
- copy proposals have different behavior contracts and must be measured as such.
2218
- Josh deferred the broader deterministic-continuation investigation. Generated
2219
- state reuse is active R17 work and comes first; it is part of the original
2220
- cache objective, not completion of the broader continuation direction.
2221
-
2222
- The R17 closeout audit confirms a reusable generated prefix in the saved
2223
- first tool turn: the first response's reasoning text tokenizes as an exact
2224
- extension of the original prompt inside the next rendered request. This is
2225
- textual opportunity evidence only, not an accepted recurrent-state snapshot
2226
- or a timing result. See `reports/qwen38-closeout/r17-first-tool-prefix-opportunity.json`.
2227
- A candidate must retain aligned target KV/recurrent state, draft KV and the
2228
- pending true hidden row at a completed decode boundary before tool formatting
2229
- can diverge. Preserve the original prompt snapshot as a fallback within the
2230
- existing cache budget. Test with independent prompts and verify snapshot
2231
- identity after further decode; saved task timings cannot substitute for that
2232
- state test. Quantities and original task timings belong in benchmarks.md.
2233
-
2234
- R17 uses the existing tiered cache. `createMlxSerialExecutor` now passes its
2235
- shared cache service into speculative execution. `QwenMtpProvider` supplies a
2236
- checkpoint codec and retains no prefix store of its own. Prefill publishes
2237
- paired target/draft state through `PromptCache.take`/`put`; processed output
2238
- publication remains unfinished. `PromptCache` owns RAM/SSD prefix selection,
2239
- eviction and write-behind persistence. The execution-state interface must capture, restore and serialize a
2240
- complete token-prefix checkpoint, regardless of whether those tokens came
2241
- from a prompt or generated output. Qwen MTP supplies its target KV/recurrent
2242
- state, draft KV and pending hidden row through that interface; it must not
2243
- grow a second storage policy.
2244
-
2245
- The first implementation step now gives ordinary and batched consumers the
2246
- same `PrefixCache` contract. MLX companion tensors flow through the existing
2247
- RAM budget, spill queue, streamed SSD writer/reader and durability coordinator.
2248
- The new storage tests pass on M1 Max and M4 Pro, including a fresh-process
2249
- restore; layout and ownership details belong in [kv-cache method companion state](kv-cache.md#method-companion-state).
2250
- Qwen MTP prefill migration now passes native bf16/KV4 RAM and SSD restart
2251
- continuation gates on both Macs. Live target/draft/hidden hashes, emitted IDs
2252
- and acceptance decisions match after reuse; the cache/provider restart also
2253
- checks stable draft identity. Raw gates are in
2254
- `reports/qwen38-closeout/composition-baseline/{m1,m4}-shared-mtp-cache-*.log`.
2255
- Generated-ID alignment, native fresh-process continuation and saved-request
2256
- performance acceptance remain unfinished.
2257
-
2258
- A subsequent isolated output-checkpoint candidate resolves the final verified
2259
- round and publishes only processed content. Synthetic stop/EOS/callback cases
2260
- pass. Generated-prefix SSD continuation matches fresh recomputation on M1 Max
2261
- in bf16/KV4 and on M4 Pro in KV4. M4 bf16 preserves checkpoint bytes but changes
2262
- the next argmax; a fresh split-prefill control also changes logits. The cause
2263
- is not yet established against a matched execution/oracle control, so this
2264
- candidate is not adopted. Evidence: `composition-baseline/m*-mtp-generated-reuse*.log`
2265
- under `reports/qwen38-closeout/`. Shared execution work continues independently.
2266
-
2267
- A subsequent shared-method implementation publishes target-row and draft-provider
2268
- snapshots through the common cache port before retirement. M1/M4 bf16/KV4/fused
2269
- TQ native tests preserve actual processed-ID coverage and RAM/SSD continuation,
2270
- including early stops and immutable donors after sibling/follow-up work.
2271
- Production parser/template replay also preserves the sampled prefix of bounded
2272
- tool turns with thinking off/on. Production HTTP RAM reuse and fresh-process
2273
- SSD restoration now also pass on both Macs in bf16/KV4/fused TQ with thinking off/on;
2274
- responses, logprobs and acceptance match within each restart pair. These
2275
- results do not replace the long Kanban or performance gates. The five-file
2276
- change is adopted; final native/HTTP composition with the prefill-policy fix
2277
- and its matched short M4 benchmark now pass. Long Kanban and pressure
2278
- acceptance remain. Details belong to the method-companion
2279
- section in kv-cache.md; evidence is in the separate
2280
- `generated-prefix-composition-validation` checkout's `reports/generated-prefix/`.
2281
-
2282
- The pre-refactor source and measured-evidence hashes are preserved under
2283
- `reports/qwen38-closeout/composition-baseline/manifest.json`. It distinguishes
2284
- the current unmeasured working tree from the frozen source used for the M4
2285
- comparisons. Baseline numbers and limitations remain in benchmarks.md. Keep
2286
- interface refactors, kernel experiments and the MTP depth comparison as
2287
- separate changes before measuring their composition.
2288
-
2289
- Acceptance must cover actual generated IDs at a rendered-stable boundary,
2290
- continued generation after capture without changing the retained state, RAM
2291
- reuse, eviction to SSD, a fresh-process SSD restore, and an exact-prefix miss
2292
- that still selects a usable earlier checkpoint. Retain shorter recurrent
2293
- boundaries because a later state cannot be trimmed back. Account for all
2294
- companion tensors in the existing cache budgets and persistence lifecycle.
2295
- Measure complete next-request time, including capture/write/restore cost;
2296
- the saved work is not literally free. The current Kanban candidate remains
2297
- frozen while this change is developed and supplies the pre-R17 task evidence.
2298
-
2299
- The private `joshuarossi/kanban-board` archive was audited at
2300
- `c34577fecbf5e1b4c48c13b14c7a7f92b92b6ba9`. Its first request and first SSE
2301
- response are byte-identical to the original saved evidence. The archived
2302
- second request changes two literal escape sequences inside reasoning from
2303
- `\u0000` to `\^@`; this explains its earlier reconstructed-prefix divergence.
2304
- Do not change either evidence copy or treat that archive difference as a Pi
2305
- serialization defect. The original saved request retains the full reasoning
2306
- prefix. Both comparisons retokenize decoded reasoning; the SSE has no original
2307
- sampled IDs, so the execution-state gate must record those IDs directly.
2308
- Evidence: `reports/qwen38-closeout/r17-repo-prefix-audit.json`.
2309
-
2310
- #### Shipped defaults and remaining experiment gates
2311
-
2312
- [Server configuration](../reference/server-config.md) owns effective defaults,
2313
- precedence and supported combinations. Trellis v13, eligible KV4 speculation
2314
- and paired MTP prompt reuse shipped in v0.4.0. Shared batching is the default;
2315
- R17 generated RAM/SSD persistence and long-agent setting selection are accepted.
2316
- Serial removal and exhaustive feature migration are deferred by the current
2317
- milestone. Remaining experiments do not reopen those completed gates.
2318
-
2319
- | Control | Accepted evidence | Remaining work |
2320
- | --- | --- | --- |
2321
- | `MLX_BUN_TRELLIS`, `MLX_BUN_TRELLIS_VARIANT` | Shipped selection; six serial, six continuous and six combined KV4/MTP pairs, plus native state gates. | Additional experimental variants retain their own numerical/performance requirements. |
2322
- | `MLX_BUN_TRELLIS_ASYNC_EXPAND` | Native, repeated short serving and saved long-agent pressure checks pass, including fused k8v3/MTP3 on M4 and M1. | Keep opt-in for the measured small request-time gain and higher live allocation. Combined pressure is accepted; reopen only for new models/barriers or a better tradeoff. |
2323
- | `MLX_BUN_EARLY_FIRST_TOKEN` | Streaming/cancellation/overlap and cached/SSD gates pass. Caller-owned M=1 alignment preserves state on M1 and M4. Monitored paired chat HTTP checks support earlier visible output; default on. | No open early-output acceptance gate. Invisible token zero need not improve raw-prompt latency; no decode-throughput gain claimed. |
2324
- | `MLX_BUN_TURBOQUANT_FUSED_DECODE` | Adopted on by default for an explicitly selected TQ cache after native/state, repeated codec serving, long cached/SSD and combined pressure gates, plus current M1/M4 shared serving. | Explicit off control remains; distinguish codec-kernel gains from quantization-setting comparisons. |
2325
- | `MLX_BUN_QWEN_SPEC_KV4` | Combined M4 pairs, completed tasks and the current 78,678-token cached/SSD workload pass. KV4/MTP2 remains the measured long-agent choice. | Three-query key-head grouping is integrated for the qualified M4 shape after operation, full-state and matched serving gates. Other geometries retain the existing dispatch. |
2326
- | `MLX_BUN_MTP_PROMPT_CACHE` | Shared byte accounting, generated-boundary checkpoints, RAM/SSD restart and full Kanban session retention pass. | No open R17 acceptance gate; new methods retain their own state contracts. |
2327
- | `MLX_BUN_FILL`, append chunk/span controls | Qualified Qwen committed appends preserve bf16/KV4/KV8/K8V3 state; balanced HTTP and saved tool-history fixture comparisons pass. | Held-out task quality, shared direct append, speculative/quantized verification and other model/GPU qualifications remain distinct cells. |
2328
- | Fill trace and echo-index controls | Trace is diagnostic; echo is a separate Lab algorithm. | Disable trace for timing; measure echo task quality and whole-request cost before promotion. |
2329
- | `MLX_BUN_RD_PREFILL_CHUNK` | Captured policy selects work size; explicit overrides remain. Automatic long hybrid prefill matches all 19 fixed-size responses through cached/SSD restart. | The completed fixed-256 integrated Kanban control reproduces the earlier first response and meets the app-quality target. Retain that task-comparison setting. The general automatic policy remains selected; one changed trajectory does not establish a general quality loss. |
2330
- | `MLX_BUN_RD_CONTEXT_LIMIT` | Explicit caller constraint; fit estimates remain advisory. | Benchmark control, not a speed candidate. |
2331
- | `MLX_BUN_TOKEN_MASK` | Exact structured-output responses; previous serving timing is inconclusive. | Controlled B1/B4 comparison if the mask implementation changes. |
2332
- | `MLX_BUN_PREFILL_TAIL_SPLIT` | Existing policy explains recorded RTN4 ordinary/MTP trajectory differences. | Changing that policy requires a separate numerical/quality comparison. |
2333
-
2334
- #### Closed candidates
2335
-
2336
- Do not re-open without new evidence of the kind named in the row's reopen
2337
- condition.
2338
-
2339
- - Device f32 code LUT for variant-6 decode: slower at M=1 for every bit width (`lut6-*.json`).
2340
- - Constant-address-space int16 codebook table: 0.802 vs 0.331 ms reduce; nearly 2x complete MLP on MLX 0.32.2 (`trellis-codebook*`, `trellis-constant-*`).
2341
- - Device/threadgroup fp16 code tables at M=1/4: lose; threadgroup table retained only for M3/4 k3 scatter inside variant 13.
2342
- - Integer y-mad final-sum rewrite: exact, no useful gain; readable expression kept.
2343
- - Shared activation loads across 2/4/8 gate/up rows per SIMD group: loses at k3 M=1.
2344
- - Row-loop unrolling of the aligned 3-bit scatter: no material gain.
2345
- - Larger fused prefill tiles at M=128/512 (40 geometries): all exact, none beats expansion plus native matmul.
2346
- - Contiguous packed reads with transposed threadgroup writes and threadgroup padding: slower; not retained.
2347
- - Variant 9 unrestricted deferred expansion and unrestricted async submission: fail the saved-agent pressure gate (Metal insufficient memory); superseded by the bounded 75% policy.
2348
- - M≤8 packed/expanded crossover: MLP win but changes output bytes; Lab, not in production dispatch.
2349
- - fp16 storage as a Steel GEMM throughput shortcut: source audit shows float accumulation regardless; rejected.
2350
- - Fused GDN convolution/SiLU/copied tail (R8): flat full-model timing; unpromoted.
2351
- - GDN compiled fixed-length recurrence and fused recurrence/RMSNorm/gate kernels (R9): gains too small; not integrated.
2352
- - Fixed-shape CompiledFunction over 16 SSM groups: -0.062%/-0.202%; no integration.
2353
- - Fixed-input custom-kernel proxies, 64 per-layer cached graphs (RTN4 fails identity) and whole-model graph (slower): no production tracer manipulation.
2354
- - Affine QMV layout screen (rows per SIMD group / groups per threadgroup): no accepted whole-model gain.
2355
- - Shared-M affine kernels and `MLX_BUN_AFFINE_SHARED_M` (4-bit M3..8, compact 3/8-bit, nonfast large projections): superseded by MLX 0.32.2 `qmv_wide`; kernel and flag removed, frozen source controls retain them.
2356
- - Shape-specific compiled-call cache around shared-affine kernels: HTTP gains shrink to flat; not integrated.
2357
- - Broader cross-model 4-bit shared-affine prototype: MiniCPM/Llama regress; float16 head-only B8 variant <1% on 3B; not integrated.
2358
- - Fused affine gate/up/SwiGLU: only M=1 wins in isolation; full-forward gain too small.
2359
- - Residual-add/RMSNorm fused kernel: M1 slightly slower, M4/8 flat; not integrated.
2360
- - Multimodal RoPE shared angles/direct strides: M128 slightly slower, M512 flat; closed.
2361
- - Metal launch-configuration cache: Qwen flat, MiniCPM fails the serving response gate (cause unresolved); closed.
2362
- - Untouched-finalize elision in the Metal backend: -0.069%/+0.108%; closed without integration.
2363
- - MLX submission/traversal/sync settings for Qwen: no compelling setting (0.94% traversal gain matched the 0.92% default drift); Llama 25/25 remains an explicit process-start override after current-version cross-model and both-machine controls; no universal default is adopted. See benchmarks.md.
2364
- - `MLX_METAL_FAST_SYNCH=1`: stalls the installed library's large bf16 three-stream case; not attributed to any prototype.
2365
- - Top-p inverse-permutation removal (pure MLX and fused Metal): Qwen +0.183% complete; Llama -0.4%; no production sampler change.
2366
- - Grouped greedy verify readback (concatenated and evalAll): ≤0.33% gain, JSON regression; closed.
2367
- - Direct packed-key TurboQuant attention: exact, 6–19% slower than joint decode plus native SDPA; closed.
2368
- - Fused inverse-Hadamard one-row layout inside the joint decoder: +12.76..+24.67% slower; only the row-grouped N≥8192 variant retained.
2369
- - Dense register-resident attention (vLLM-Metal port): loses timing; Steel D256 fails one 512-token KL screen; Lab, unintegrated.
2370
- - KV append whole-cache-copy hypothesis: rejected by native/HTTP census (one-row copies); no append kernel.
2371
- - mmap file-backed weight loader (immutable, managed, lazy, prefault variants): warm flat-to-slower, cold worse in 5/6; closed as a performance candidate.
2372
- - Staged-body strict-fill prototype (skip the discarded in-flight sample): flat; closed.
2373
- - Multi-query affine attention inside strict append: recurrent state diverges at layer 4. Superseded by the qualified one-token attention calculation within shared projection appends; KV4/KV8 now pass state and serving gates.
2374
- - Cross-entropy block-alignment partition: no wired model reaches a misaligned partition; closed without integration.
2375
- - Streamed-expert threadgroup geometry: bf16 timing bimodal in all three library arms; no geometry default retained.
2376
- - Proc-pid-rusage FFI collector: 0.0013 ms vs 1.09 ms per read, collector only; existing reports keep the ps collector.
2377
- - Video tq3-mini polar format: operation wins on synthetic matrices; no loader, kernel or quality evidence; not adopted.
2378
-
2379
-
2380
- ### 7.14 Larger-departure feasibility decisions
2381
-
2382
- R24 now has an explicit initial screen. Resource calculations and the
2383
- both-machine activation operation comparison live in
2384
- [benchmarks](../reference/benchmarks.md#r24-activation-quantization-and-resource-bounds-2026-09-13).
2385
- The following decisions apply to the current packed Qwen artifact and native
2386
- pack. They do not close unmeasured candidate quality or claim the whole campaign
2387
- is exhausted.
2388
-
2389
- | Candidate | Kernel and quality requirement | Training/calibration and next decision |
2390
- |---|---|---|
2391
- | Learned/codebook quantization | [AQLM](https://arxiv.org/abs/2401.06118) learns additive codebooks. Existing Trellis dispatch and the archived polar operation screen do not establish a loader or efficient decoder for that representation. New codes must pass the frozen quality suite. | Fit one matrix/block with calibration under the calculated memory budget before any whole-model conversion. A complete original bf16 Qwen snapshot was not found in the checked model directories; fitting the current packed reconstruction must be labeled as an additional approximation. |
2392
- | Sparse residual/outlier correction | [SpQR](https://arxiv.org/abs/2306.03078) separates exceptional weights from the low-bit representation. The sparse correction must fit inside savings from a lower-bit base and fuse with the target's matrix operation. | Bounded matrix reconstruction is feasible in principle; measure error versus bytes and sparse gather/reduction time first. Do not install a second dense correction matrix or assume CUDA speed transfers to Metal. Original-weight recovery needs original weights. |
2393
- | Activation quantization | [SmoothQuant](https://arxiv.org/abs/2211.10438) motivates jointly quantized weights/activations. The pinned native QQMM rounds then expands activations. The actual same-weight operation screen loses, especially at prefill sizes. | Current QQMM is rejected as a drop-in speed option. A direct compressed-activation kernel remains a separate implementation and quality experiment; INT8 input alone does not supply it. |
2394
- | Structured pruning | Zero values in the existing packed format still consume codes and matrix work. A useful artifact must physically remove aligned channels/heads and update model dimensions. | Rank channels with calibration, then test one width-reduced MLP before a model conversion. Preserve matching gate/up selections and down input columns. No unstructured sparsity speedup is assumed. |
2395
- | Layer skipping | [ShortGPT](https://arxiv.org/abs/2403.03853) ranks layer influence. A static reduced-layer artifact can remove work, but Qwen's recurrent/attention mix and cache topology must remain explicit. Dynamic token-dependent skips change recurrent evolution. | Start with static layer influence and held-out quality. Removing eight of 64 equally costly blocks would remove one eighth of block work only under that simplifying assumption; use measured layer costs before predicting time. No serving skip flag is selected. |
2396
- | Low-rank approximation | [SVD-LLM](https://arxiv.org/abs/2403.07378) combines activation-aware factorization and correction. Two dense factor multiplies can use existing operations, but a loader/linear binding and compression-quality evidence are still needed. | The rank/byte screen rules out high-rank bf16 factors as a size win against W3. The actual layer-one gate spectrum rejects plain unweighted SVD at a size-feasible rank. Activation-aware error and task quality remain separate work. |
2397
- | QAT/distillation | [QLoRA](https://arxiv.org/abs/2305.14314) shows why freezing a quantized base changes training memory. Full-resident 27B optimization does not fit either machine. `Qwen35Model.loraTargets()` explicitly excludes Trellis MLPs; existing adapter training does not establish packed-MLP recovery. | Layerwise QAT or adapter recovery needs a differentiable packed linear binding and measured activations. Stored teacher targets can separate teacher generation from student training. The quality gain and training duration remain unmeasured. |
2398
- | Alternative drafters | Existing grouped providers already separate proposals from verification. A trained drafter must improve accepted tokens per total target/draft time and respect target memory needs. | No trained DSpark/DFlash checkpoint exists. Keep their untrained correctness checks distinct from performance acceptance. R20's measured native-MTP depths remain the available comparison. The specific DFlash2 architecture is separate open work. |
2399
-
2400
- Actual-weight screens now reject the simple unweighted low-rank and sparse
2401
- variants. Differentiation confirms the need for a custom packed backward
2402
- operation; expanded frozen weights already differentiate. Further work needs
2403
- activation-calibrated candidates or that backward binding. No new deployment default,
2404
- model-quality claim or training run follows from the paper results alone.