@mlx-bun/inference 0.0.0-stage → 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 (467) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1475 -2
  3. package/THIRD_PARTY_NOTICES.md +3404 -0
  4. package/dist/native/libmlx_bun_ane.dylib +0 -0
  5. package/dist/native/libmlx_bun_expert_io.dylib +0 -0
  6. package/dist/native/mlx-bun-frame-extract +0 -0
  7. package/examples/fit-model.ts +25 -0
  8. package/examples/qwen3-forward.ts +42 -0
  9. package/examples/qwen3-generate.ts +28 -0
  10. package/examples/trellis-expand.ts +23 -0
  11. package/package.json +129 -4
  12. package/src/adapters/available.ts +110 -0
  13. package/src/adapters/index.ts +3 -0
  14. package/src/adapters/manager.ts +316 -0
  15. package/src/artifacts/auxiliary-files.ts +45 -0
  16. package/src/artifacts/config-dialects.ts +94 -0
  17. package/src/artifacts/config.ts +341 -0
  18. package/src/artifacts/draft-vocabulary.ts +30 -0
  19. package/src/artifacts/expert-offload-build.ts +75 -0
  20. package/src/artifacts/expert-offload.ts +89 -0
  21. package/src/artifacts/experts/index.ts +3 -0
  22. package/src/artifacts/experts/io.ts +386 -0
  23. package/src/artifacts/experts/residency.ts +1134 -0
  24. package/src/artifacts/experts/usage.ts +415 -0
  25. package/src/artifacts/fingerprint.ts +44 -0
  26. package/src/artifacts/glm52/container.ts +305 -0
  27. package/src/artifacts/glm52/expert-layout.ts +249 -0
  28. package/src/artifacts/glm52/index.ts +7 -0
  29. package/src/artifacts/glm52/kernel-layout.ts +124 -0
  30. package/src/artifacts/glm52/layout.ts +152 -0
  31. package/src/artifacts/glm52/memory.ts +500 -0
  32. package/src/artifacts/glm52/resident-weights.ts +135 -0
  33. package/src/artifacts/glm52/weights.ts +503 -0
  34. package/src/artifacts/glm52-config.ts +262 -0
  35. package/src/artifacts/identity.ts +94 -0
  36. package/src/artifacts/index.ts +15 -0
  37. package/src/artifacts/mmap.ts +90 -0
  38. package/src/artifacts/safetensors-writer.ts +249 -0
  39. package/src/artifacts/safetensors.ts +164 -0
  40. package/src/artifacts/turboquant-fold.ts +42 -0
  41. package/src/artifacts/weight-audit.ts +43 -0
  42. package/src/artifacts/weights.ts +255 -0
  43. package/src/contracts/index.ts +2 -0
  44. package/src/contracts/mlx/attention.ts +8 -0
  45. package/src/contracts/mlx/cache.ts +510 -0
  46. package/src/contracts/mlx/checkpoint.ts +10 -0
  47. package/src/contracts/mlx/draft-checkpoint.ts +14 -0
  48. package/src/contracts/mlx/draft-projection.ts +27 -0
  49. package/src/contracts/mlx/draft-target.ts +84 -0
  50. package/src/contracts/mlx/drafter.ts +176 -0
  51. package/src/contracts/mlx/forward-work.ts +23 -0
  52. package/src/contracts/mlx/glm52-weights.ts +25 -0
  53. package/src/contracts/mlx/graph.ts +309 -0
  54. package/src/contracts/mlx/head.ts +6 -0
  55. package/src/contracts/mlx/index.ts +15 -0
  56. package/src/contracts/mlx/kv-codec.ts +9 -0
  57. package/src/contracts/mlx/media.ts +113 -0
  58. package/src/contracts/mlx/positions.ts +16 -0
  59. package/src/contracts/mlx/row-table.ts +2 -0
  60. package/src/contracts/mlx/trainable.ts +103 -0
  61. package/src/contracts/mlx/whisper.ts +96 -0
  62. package/src/contracts/portable/composition.ts +106 -0
  63. package/src/contracts/portable/denoising.ts +17 -0
  64. package/src/contracts/portable/execution.ts +79 -0
  65. package/src/contracts/portable/generation.ts +103 -0
  66. package/src/contracts/portable/graph.ts +80 -0
  67. package/src/contracts/portable/index.ts +15 -0
  68. package/src/contracts/portable/memory-plan.ts +26 -0
  69. package/src/contracts/portable/object-cache.ts +8 -0
  70. package/src/contracts/portable/prefill.ts +63 -0
  71. package/src/contracts/portable/prefix-cache.ts +33 -0
  72. package/src/contracts/portable/prompt.ts +2 -0
  73. package/src/contracts/portable/resources.ts +25 -0
  74. package/src/contracts/portable/rollback.ts +7 -0
  75. package/src/contracts/portable/sampling.ts +44 -0
  76. package/src/contracts/portable/scheduling.ts +54 -0
  77. package/src/contracts/portable/token-delivery.ts +4 -0
  78. package/src/contracts/portable/tsconfig.json +14 -0
  79. package/src/embeddings/index.ts +1 -0
  80. package/src/embeddings/text.ts +85 -0
  81. package/src/execution/admission.ts +59 -0
  82. package/src/execution/batch-group.ts +1240 -0
  83. package/src/execution/batch-types.ts +225 -0
  84. package/src/execution/cancellation.ts +38 -0
  85. package/src/execution/continuation-request.ts +45 -0
  86. package/src/execution/continuation-types.ts +10 -0
  87. package/src/execution/coordinator.ts +70 -0
  88. package/src/execution/denoising-group.ts +180 -0
  89. package/src/execution/engine.ts +56 -0
  90. package/src/execution/fill-group.ts +505 -0
  91. package/src/execution/fit.ts +184 -0
  92. package/src/execution/gateway-binding.ts +178 -0
  93. package/src/execution/grammar-group.ts +224 -0
  94. package/src/execution/index.ts +18 -0
  95. package/src/execution/methods.ts +75 -0
  96. package/src/execution/mixed-iteration.ts +96 -0
  97. package/src/execution/plan.ts +65 -0
  98. package/src/execution/prefill-cohort.ts +100 -0
  99. package/src/execution/prefill-rows.ts +263 -0
  100. package/src/execution/request-policy.ts +19 -0
  101. package/src/execution/row-sampling.ts +49 -0
  102. package/src/execution/scheduler.ts +92 -0
  103. package/src/execution/session.ts +247 -0
  104. package/src/execution/speculative-group.ts +797 -0
  105. package/src/execution/tasks.ts +44 -0
  106. package/src/generation/autoregressive.ts +840 -0
  107. package/src/generation/bindings/autoregressive.ts +104 -0
  108. package/src/generation/bindings/denoising.ts +60 -0
  109. package/src/generation/bindings/prefill-policy.ts +36 -0
  110. package/src/generation/checkpoint-identity.ts +60 -0
  111. package/src/generation/denoising.ts +85 -0
  112. package/src/generation/diffusion.ts +583 -0
  113. package/src/generation/fill/echo-index.ts +188 -0
  114. package/src/generation/fill/index.ts +3 -0
  115. package/src/generation/fill/proposal.ts +69 -0
  116. package/src/generation/fill/schema-rows.ts +506 -0
  117. package/src/generation/fill/session.ts +464 -0
  118. package/src/generation/fill/tool-boundary.ts +103 -0
  119. package/src/generation/fill-append.ts +58 -0
  120. package/src/generation/generate.ts +44 -0
  121. package/src/generation/grammar-step.ts +39 -0
  122. package/src/generation/index.ts +14 -0
  123. package/src/generation/phase-dispatch.ts +115 -0
  124. package/src/generation/prefill.ts +33 -0
  125. package/src/generation/result.ts +49 -0
  126. package/src/generation/scopes.ts +157 -0
  127. package/src/generation/speculative/acceptance.ts +41 -0
  128. package/src/generation/speculative/adaptive-draft-gate.ts +166 -0
  129. package/src/generation/speculative/bindings/assistant-rows.ts +102 -0
  130. package/src/generation/speculative/bindings/autoregressive-rows.ts +124 -0
  131. package/src/generation/speculative/bindings/binding.ts +106 -0
  132. package/src/generation/speculative/bindings/deepspec-rows.ts +33 -0
  133. package/src/generation/speculative/bindings/draft-target.ts +10 -0
  134. package/src/generation/speculative/bindings/glm52-mtp-rows.ts +128 -0
  135. package/src/generation/speculative/bindings/projected-context-rows.ts +78 -0
  136. package/src/generation/speculative/bindings/projected-draft-rows.ts +95 -0
  137. package/src/generation/speculative/bindings/qwen-mtp-rows.ts +336 -0
  138. package/src/generation/speculative/bindings/two-model-rows.ts +63 -0
  139. package/src/generation/speculative/cache-identity.ts +16 -0
  140. package/src/generation/speculative/draft-kind.ts +149 -0
  141. package/src/generation/speculative/draft-policy.ts +41 -0
  142. package/src/generation/speculative/draft-registry.ts +118 -0
  143. package/src/generation/speculative/draft-vocab.ts +110 -0
  144. package/src/generation/speculative/index.ts +17 -0
  145. package/src/generation/speculative/output.ts +49 -0
  146. package/src/generation/speculative/round.ts +307 -0
  147. package/src/generation/speculative/source.ts +144 -0
  148. package/src/generation/speculative/sources/assistant-source.ts +64 -0
  149. package/src/generation/speculative/sources/deepspec-source.ts +70 -0
  150. package/src/generation/speculative/sources/dflash-source.ts +84 -0
  151. package/src/generation/speculative/sources/dflash2-source.ts +86 -0
  152. package/src/generation/speculative/sources/glm52-mtp-source.ts +66 -0
  153. package/src/generation/speculative/sources/ngram-source.ts +165 -0
  154. package/src/generation/speculative/sources/qwen-mtp-source.ts +154 -0
  155. package/src/generation/speculative/sources/two-model.ts +75 -0
  156. package/src/generation/types.ts +194 -0
  157. package/src/index.ts +20 -0
  158. package/src/input/audio/audiotoolbox.ts +112 -0
  159. package/src/input/audio/decode.ts +133 -0
  160. package/src/input/audio/features.ts +202 -0
  161. package/src/input/audio/index.ts +6 -0
  162. package/src/input/audio/transcode.ts +67 -0
  163. package/src/input/audio/whisper-mel.ts +185 -0
  164. package/src/input/audio/whisper-tokenizer.ts +238 -0
  165. package/src/input/chat-template.ts +389 -0
  166. package/src/input/index.ts +6 -0
  167. package/src/input/media-fetch.ts +439 -0
  168. package/src/input/packed-mixed.ts +43 -0
  169. package/src/input/special-tokens.ts +75 -0
  170. package/src/input/token-groups.ts +49 -0
  171. package/src/input/tokenizer.ts +336 -0
  172. package/src/input/tool-call.ts +689 -0
  173. package/src/input/vision/index.ts +3 -0
  174. package/src/input/vision/preprocess.ts +247 -0
  175. package/src/input/vision/prompt.ts +398 -0
  176. package/src/input/vision/qwen3vl-preprocess.ts +409 -0
  177. package/src/input/vision/qwen3vl-prompt.ts +237 -0
  178. package/src/input/vision/video-frames.ts +100 -0
  179. package/src/kernels/ane/fill.ts +101 -0
  180. package/src/kernels/ane/linear.ts +416 -0
  181. package/src/kernels/attention/flash.ts +694 -0
  182. package/src/kernels/attention/kvq4-decode.ts +155 -0
  183. package/src/kernels/attention/masks.ts +40 -0
  184. package/src/kernels/attention/multi-query.ts +193 -0
  185. package/src/kernels/attention/paged.ts +130 -0
  186. package/src/kernels/delta/gated.ts +306 -0
  187. package/src/kernels/delta/index.ts +3 -0
  188. package/src/kernels/delta/silu-rms-heads.ts +69 -0
  189. package/src/kernels/delta/state.ts +74 -0
  190. package/src/kernels/gated-rms-norm.ts +64 -0
  191. package/src/kernels/glm52/layout.ts +37 -0
  192. package/src/kernels/glm52/streamed-experts.ts +360 -0
  193. package/src/kernels/logits.ts +38 -0
  194. package/src/kernels/quantization/affine-row.ts +154 -0
  195. package/src/kernels/quantization/affine-rows.ts +36 -0
  196. package/src/kernels/quantization/affine-split-mma.ts +144 -0
  197. package/src/kernels/quantization/affine3-mma.ts +117 -0
  198. package/src/kernels/quantization/affine3-rows.ts +103 -0
  199. package/src/kernels/quantization/affine4-mma.ts +113 -0
  200. package/src/kernels/quantization/affine4-rows.ts +102 -0
  201. package/src/kernels/residual-rms-norm.ts +65 -0
  202. package/src/kernels/sampling/index.ts +2 -0
  203. package/src/kernels/sampling/normalized-argmax.ts +116 -0
  204. package/src/kernels/sampling/token-bitmask.ts +52 -0
  205. package/src/kernels/softcap.ts +35 -0
  206. package/src/kernels/trellis/codebook.ts +123 -0
  207. package/src/kernels/trellis/down-codebook.ts +184 -0
  208. package/src/kernels/trellis/down-factored.ts +180 -0
  209. package/src/kernels/trellis/down-k3-interleaved-factored.ts +146 -0
  210. package/src/kernels/trellis/down-mma-wide.ts +195 -0
  211. package/src/kernels/trellis/down-mma.ts +145 -0
  212. package/src/kernels/trellis/expand.ts +42 -0
  213. package/src/kernels/trellis/gate-up-codebook-mma.ts +141 -0
  214. package/src/kernels/trellis/gate-up-codebook.ts +137 -0
  215. package/src/kernels/trellis/gate-up-factored.ts +197 -0
  216. package/src/kernels/trellis/gate-up-mma-wide.ts +147 -0
  217. package/src/kernels/trellis/gate-up-mma.ts +148 -0
  218. package/src/kernels/trellis/gate-up.ts +248 -0
  219. package/src/kernels/trellis/geometry.ts +22 -0
  220. package/src/kernels/trellis/index.ts +103 -0
  221. package/src/kernels/trellis/launch.ts +12 -0
  222. package/src/kernels/trellis/mixed-gate-up-factored.ts +119 -0
  223. package/src/kernels/trellis/mixed-gate-up.ts +146 -0
  224. package/src/kernels/trellis/qualified.ts +34 -0
  225. package/src/kernels/trellis/reduce.ts +150 -0
  226. package/src/kernels/trellis/scatter.ts +407 -0
  227. package/src/kernels/trellis/splitk-prefill.ts +152 -0
  228. package/src/kernels/trellis/tiled-prefill.ts +131 -0
  229. package/src/kernels/trellis/vector-expand.ts +58 -0
  230. package/src/kernels/trellis/wide-prefill.ts +89 -0
  231. package/src/kernels/turboquant/decode.ts +82 -0
  232. package/src/kernels/turboquant/index.ts +5 -0
  233. package/src/kernels/turboquant/inverse.ts +122 -0
  234. package/src/kernels/turboquant/ops.ts +860 -0
  235. package/src/kernels/turboquant/signs.ts +130 -0
  236. package/src/kernels/turboquant/tables.ts +124 -0
  237. package/src/layers/affine-verify-linear.ts +75 -0
  238. package/src/layers/ane-prefill-split.ts +283 -0
  239. package/src/layers/compiled-normalization.ts +41 -0
  240. package/src/layers/delta-heads.ts +23 -0
  241. package/src/layers/dense-embedding.ts +29 -0
  242. package/src/layers/dense-linear.ts +32 -0
  243. package/src/layers/dequantized-linear.ts +72 -0
  244. package/src/layers/folded-attention.ts +42 -0
  245. package/src/layers/geglu.ts +130 -0
  246. package/src/layers/helpers.ts +7 -0
  247. package/src/layers/index.ts +36 -0
  248. package/src/layers/kv4-decode-attention.ts +15 -0
  249. package/src/layers/layer-norm.ts +24 -0
  250. package/src/layers/loading.ts +92 -0
  251. package/src/layers/lora.ts +150 -0
  252. package/src/layers/normalization.ts +9 -0
  253. package/src/layers/prefix-layout.ts +33 -0
  254. package/src/layers/quantized-append-attention.ts +32 -0
  255. package/src/layers/quantized-attention.ts +353 -0
  256. package/src/layers/quantized-embedding.ts +39 -0
  257. package/src/layers/quantized-linear.ts +137 -0
  258. package/src/layers/quantized-switch-linear.ts +37 -0
  259. package/src/layers/qwen-append.ts +12 -0
  260. package/src/layers/qwen-mrope.ts +238 -0
  261. package/src/layers/rope-2d.ts +110 -0
  262. package/src/layers/rope.ts +389 -0
  263. package/src/layers/swiglu.ts +23 -0
  264. package/src/layers/trellis-codebook-down.ts +52 -0
  265. package/src/layers/trellis-codebook-gate-up.ts +42 -0
  266. package/src/layers/trellis-down.ts +117 -0
  267. package/src/layers/trellis-gate-up.ts +71 -0
  268. package/src/layers/trellis-linear.ts +211 -0
  269. package/src/layers/trellis-prompt.ts +102 -0
  270. package/src/layers/trellis-reduce-gate-up.ts +73 -0
  271. package/src/layers/trellis-scatter-down.ts +98 -0
  272. package/src/models/ane-install.ts +74 -0
  273. package/src/models/audio/conformer.ts +656 -0
  274. package/src/models/cache-composition.ts +44 -0
  275. package/src/models/capabilities.ts +89 -0
  276. package/src/models/chat-template.ts +10 -0
  277. package/src/models/composition.ts +107 -0
  278. package/src/models/diffusion-gemma/experts.ts +59 -0
  279. package/src/models/diffusion-gemma/family.ts +21 -0
  280. package/src/models/diffusion-gemma/model.ts +900 -0
  281. package/src/models/diffusion-gemma/vision.ts +549 -0
  282. package/src/models/drafter-loaders.ts +49 -0
  283. package/src/models/drafters.ts +39 -0
  284. package/src/models/factory.ts +351 -0
  285. package/src/models/families.ts +70 -0
  286. package/src/models/family.ts +125 -0
  287. package/src/models/gemma4/assistant-target.ts +46 -0
  288. package/src/models/gemma4/assistant.ts +327 -0
  289. package/src/models/gemma4/blocks.ts +755 -0
  290. package/src/models/gemma4/compiled-decode.ts +452 -0
  291. package/src/models/gemma4/family.ts +39 -0
  292. package/src/models/gemma4/gemma4-12b.ts +677 -0
  293. package/src/models/gemma4/gemma4-26b.ts +544 -0
  294. package/src/models/gemma4/gemma4-e4b.ts +599 -0
  295. package/src/models/gemma4/graphs.ts +147 -0
  296. package/src/models/gemma4/media.ts +88 -0
  297. package/src/models/gemma4/model.ts +860 -0
  298. package/src/models/gemma4/serving-blocks.ts +72 -0
  299. package/src/models/gemma4/trainable.ts +186 -0
  300. package/src/models/gemma4/written-blocks.ts +232 -0
  301. package/src/models/gemma4/written-forward.ts +159 -0
  302. package/src/models/gemma4/written-input.ts +29 -0
  303. package/src/models/glm52/atlas.ts +507 -0
  304. package/src/models/glm52/coupling.ts +388 -0
  305. package/src/models/glm52/dsa.ts +601 -0
  306. package/src/models/glm52/family.ts +20 -0
  307. package/src/models/glm52/mla.ts +812 -0
  308. package/src/models/glm52/model.ts +1127 -0
  309. package/src/models/glm52/moe.ts +223 -0
  310. package/src/models/glm52/mtp.ts +60 -0
  311. package/src/models/glm52/pilot.ts +537 -0
  312. package/src/models/glm52/reference.ts +445 -0
  313. package/src/models/glm52/residency.ts +557 -0
  314. package/src/models/glm52/streamed-experts.ts +447 -0
  315. package/src/models/graph.ts +59 -0
  316. package/src/models/implementation.ts +230 -0
  317. package/src/models/index.ts +15 -0
  318. package/src/models/media-input.ts +15 -0
  319. package/src/models/memory-plan.ts +39 -0
  320. package/src/models/minicpm5/family.ts +29 -0
  321. package/src/models/minicpm5/model.ts +394 -0
  322. package/src/models/minicpm5/trainable.ts +90 -0
  323. package/src/models/profile.ts +337 -0
  324. package/src/models/qwen/blocks.ts +658 -0
  325. package/src/models/qwen/checkpoint.ts +190 -0
  326. package/src/models/qwen/families.ts +57 -0
  327. package/src/models/qwen/media-input.ts +161 -0
  328. package/src/models/qwen/mtp.ts +101 -0
  329. package/src/models/qwen/qwen3-moe.ts +355 -0
  330. package/src/models/qwen/qwen3.ts +323 -0
  331. package/src/models/qwen/qwen38-27b-trellis-m1max.ts +1532 -0
  332. package/src/models/qwen/qwen38-27b-trellis-m4pro.ts +1092 -0
  333. package/src/models/qwen/qwen3_5.ts +433 -0
  334. package/src/models/qwen/written-layers.ts +285 -0
  335. package/src/models/row-table.ts +1 -0
  336. package/src/models/runtime.ts +73 -0
  337. package/src/models/speculative/deepspec-artifact.ts +10 -0
  338. package/src/models/speculative/deepspec.ts +744 -0
  339. package/src/models/speculative/dflash.ts +553 -0
  340. package/src/models/speculative/dflash2-artifact.ts +9 -0
  341. package/src/models/speculative/dflash2-operations.ts +1 -0
  342. package/src/models/speculative/dflash2.ts +576 -0
  343. package/src/models/speculative/loader.ts +29 -0
  344. package/src/models/support.ts +79 -0
  345. package/src/models/universal/archs.ts +365 -0
  346. package/src/models/universal/blocks.ts +479 -0
  347. package/src/models/universal/dense.ts +255 -0
  348. package/src/models/universal/family.ts +17 -0
  349. package/src/models/vision/qwen3vl.ts +566 -0
  350. package/src/models/vision/siglip.ts +520 -0
  351. package/src/models/vision/unified.ts +176 -0
  352. package/src/models/whisper/family.ts +19 -0
  353. package/src/models/whisper/fast.ts +734 -0
  354. package/src/models/whisper/model.ts +430 -0
  355. package/src/runtime/compiled-trace.ts +16 -0
  356. package/src/runtime/config.ts +77 -0
  357. package/src/runtime/expert-trace.ts +71 -0
  358. package/src/runtime/graph-forward.ts +65 -0
  359. package/src/runtime/integers.ts +6 -0
  360. package/src/runtime/native.ts +16 -0
  361. package/src/runtime/resources.ts +53 -0
  362. package/src/runtime/row-operations.ts +42 -0
  363. package/src/runtime/trace.ts +161 -0
  364. package/src/sampling/curve.ts +122 -0
  365. package/src/sampling/draft.ts +55 -0
  366. package/src/sampling/extras.ts +45 -0
  367. package/src/sampling/filters.ts +134 -0
  368. package/src/sampling/grammar.ts +630 -0
  369. package/src/sampling/hlg.ts +290 -0
  370. package/src/sampling/index.ts +9 -0
  371. package/src/sampling/processors.ts +142 -0
  372. package/src/sampling/sampler.ts +120 -0
  373. package/src/sampling/step.ts +343 -0
  374. package/src/sampling/types.ts +161 -0
  375. package/src/sampling/window-filters.ts +46 -0
  376. package/src/scoring/decisions.ts +96 -0
  377. package/src/scoring/full-sequence.ts +103 -0
  378. package/src/scoring/index.ts +9 -0
  379. package/src/scoring/kl.ts +29 -0
  380. package/src/scoring/perplexity.ts +165 -0
  381. package/src/scoring/response-logps.ts +65 -0
  382. package/src/state/affine-attention.ts +180 -0
  383. package/src/state/attachment.ts +68 -0
  384. package/src/state/attention-read.ts +215 -0
  385. package/src/state/batched-kv.ts +294 -0
  386. package/src/state/batched-mask.ts +445 -0
  387. package/src/state/batched-quant.ts +389 -0
  388. package/src/state/batched-quantized-kv.ts +209 -0
  389. package/src/state/batched-rotating-quant.ts +457 -0
  390. package/src/state/batched-rotating-state.ts +149 -0
  391. package/src/state/batched-rotating.ts +430 -0
  392. package/src/state/batched-row-storage.ts +179 -0
  393. package/src/state/batched-ssm.ts +54 -0
  394. package/src/state/batched-turboquant-kv.ts +144 -0
  395. package/src/state/bf16-first-kv.ts +663 -0
  396. package/src/state/cache-service.ts +592 -0
  397. package/src/state/capabilities.ts +65 -0
  398. package/src/state/checkpoint.ts +46 -0
  399. package/src/state/continuation-persistence.ts +126 -0
  400. package/src/state/decode-step-inputs.ts +31 -0
  401. package/src/state/decoded-kv-donor.ts +12 -0
  402. package/src/state/delayed-quantized-kv.ts +141 -0
  403. package/src/state/delayed-rotating-quantized-kv.ts +178 -0
  404. package/src/state/delayed-turboquant-kv.ts +123 -0
  405. package/src/state/durability.ts +214 -0
  406. package/src/state/encoder-cache.ts +26 -0
  407. package/src/state/full-kv-row-append.ts +33 -0
  408. package/src/state/full-kv-row-donor.ts +54 -0
  409. package/src/state/full-prefill-padding.ts +56 -0
  410. package/src/state/full-prefill-row.ts +112 -0
  411. package/src/state/full-transitioning-kv-rows.ts +70 -0
  412. package/src/state/glm52-cache.ts +783 -0
  413. package/src/state/grouped-heads-kv4-cache.ts +26 -0
  414. package/src/state/index.ts +38 -0
  415. package/src/state/kv-attention-view.ts +77 -0
  416. package/src/state/kv-budget.ts +14 -0
  417. package/src/state/kv-scheme.ts +315 -0
  418. package/src/state/kv-storage.ts +57 -0
  419. package/src/state/kv-tensor-rows.ts +212 -0
  420. package/src/state/kv.ts +324 -0
  421. package/src/state/kv4-head256-cache.ts +46 -0
  422. package/src/state/latent-legos.ts +895 -0
  423. package/src/state/layout.ts +277 -0
  424. package/src/state/leases.ts +26 -0
  425. package/src/state/paged/cache.ts +689 -0
  426. package/src/state/paged/codec.ts +36 -0
  427. package/src/state/paged/rows.ts +223 -0
  428. package/src/state/persistence-types.ts +173 -0
  429. package/src/state/persistence-worker.ts +83 -0
  430. package/src/state/persistence.ts +1036 -0
  431. package/src/state/persistence.worker.d.ts +3 -0
  432. package/src/state/persistence.worker.js +264 -0
  433. package/src/state/prefix-cache.ts +685 -0
  434. package/src/state/quantized-kv.ts +369 -0
  435. package/src/state/quantized-tensor.ts +26 -0
  436. package/src/state/request-policy.ts +48 -0
  437. package/src/state/retention-policy.ts +37 -0
  438. package/src/state/rollback.ts +131 -0
  439. package/src/state/rotating-kv-donor.ts +35 -0
  440. package/src/state/rotating-kv-layout.ts +341 -0
  441. package/src/state/rotating-kv.ts +529 -0
  442. package/src/state/rotating-quantized-kv.ts +616 -0
  443. package/src/state/rotating-row-transaction.ts +35 -0
  444. package/src/state/rows.ts +104 -0
  445. package/src/state/softcap-attention.ts +118 -0
  446. package/src/state/speculative/glm52-mtp-state.ts +38 -0
  447. package/src/state/speculative/qwen-mtp-state.ts +34 -0
  448. package/src/state/speculative-rotating-kv.ts +113 -0
  449. package/src/state/ssd-cache.ts +434 -0
  450. package/src/state/ssm-prefill-padding.ts +39 -0
  451. package/src/state/ssm.ts +422 -0
  452. package/src/state/target-layout.ts +7 -0
  453. package/src/state/tiered-prefix-cache.ts +45 -0
  454. package/src/state/training-cache.ts +300 -0
  455. package/src/state/transitioning-kv-rows.ts +267 -0
  456. package/src/state/turboquant-attention.ts +97 -0
  457. package/src/state/turboquant-codec.ts +90 -0
  458. package/src/state/turboquant-kv.ts +442 -0
  459. package/src/state/views.ts +26 -0
  460. package/src/transcription/index.ts +3 -0
  461. package/src/transcription/silero-vad.ts +379 -0
  462. package/src/transcription/whisper/decode.ts +773 -0
  463. package/src/transcription/whisper/format.ts +74 -0
  464. package/src/transcription/whisper/index.ts +4 -0
  465. package/src/transcription/whisper/timing.ts +274 -0
  466. package/src/transcription/whisper/transcribe.ts +394 -0
  467. package/src/transcription/whisper/types.ts +22 -0
@@ -0,0 +1,860 @@
1
+ // TurboQuant KV-cache codec — reference operations ported op-for-op
2
+ // from the vendored vllm-metal reference
3
+ // (`02d723a:lab/repro/vllm-metal-turboquant/turboquant_reference.py`). See
4
+ // `02d723a:docs/design/turboquant.md` for the algorithm writeup and the untracked
5
+ // goldens/turboquant.json (via `02d723a:tests/research/turboquant-ops.test.ts`) for the
6
+ // bit-exactness oracle. Quantization groups run along the LAST axis
7
+ // (head_dim) only — never the token axis, per the standing invariant.
8
+ //
9
+ // Dtype routing: encodeKeys upcasts its input to fp32 before any
10
+ // min/max/scale/zero-point/round arithmetic (mirroring the value path,
11
+ // where the FWHT sign-multiply already forces an fp32 promotion — see
12
+ // fwht()). This matters because production callers
13
+ // (packages/inference/src/state/turboquant-kv.ts TurboQuantKVCache) feed bf16 K
14
+ // tensors straight from the model, not the
15
+ // fp32 the vendored reference/goldens exercise; running the affine-quant
16
+ // arithmetic at bf16 precision measurably shifts rounding-boundary indices
17
+ // vs the fp32 reference. Only scale/zero are cast to fp16 at the end —
18
+ // this is deliberate and reproduces a real reference defect: a
19
+ // constant-valued block drives scale to exactly 0, and the resulting
20
+ // zero_point (finite in fp32, ~5e7) OVERFLOWS fp16 to +Infinity. We do not
21
+ // paper over this; the golden test asserts it.
22
+
23
+ import { Dtype, type MlxHandle } from "@mlx-bun/mlx/ffi";
24
+ import { MlxArray, gpuStream } from "@mlx-bun/mlx/array";
25
+ import * as ops from "@mlx-bun/mlx/ops";
26
+ import { LLOYD_MAX, TURBOQUANT_VALUE_BITS, type TurboQuantValueBits } from "./tables";
27
+ import { SIGN_VECTORS, TURBOQUANT_HEAD_DIMS, type TurboQuantHeadDim } from "./signs";
28
+
29
+ import { tryJointDecodePackedKv, type PackedKvArrays } from "./decode";
30
+ import { tryDecodePackedKvInverse256 } from "./inverse";
31
+ import { isShapelessTracing } from "@mlx-bun/mlx/compile";
32
+
33
+ type S = MlxHandle;
34
+
35
+ const BLOCK_SIZE = 32;
36
+ export { BLOCK_SIZE as TURBOQUANT_BLOCK_SIZE };
37
+
38
+ /** Port of packed_dim(): byte count for `dim` elements at `bits` width
39
+ * (bits===8 is one byte/element, unpacked). Throws on a non-byte-aligned
40
+ * product, matching the reference's own guard. */
41
+ export function packedDim(dim: number, bits: number): number {
42
+ if ((dim * bits) % 8 !== 0) {
43
+ throw new Error(`turboquant packedDim: dim=${dim} * bits=${bits} is not byte-aligned`);
44
+ }
45
+ return (dim * bits) / 8;
46
+ }
47
+
48
+ function isSupportedHeadDim(d: number): d is TurboQuantHeadDim {
49
+ return (TURBOQUANT_HEAD_DIMS as readonly number[]).includes(d);
50
+ }
51
+
52
+ // --- sign vectors (host-side constants, generated from key(42)) ---------
53
+
54
+ const signArrayCache = new Map<TurboQuantHeadDim, MlxArray>();
55
+
56
+ /** [dim] float32 array of the ±1 sign table for this head_dim. Cached —
57
+ * it's a shared constant like the Lloyd-Max centroid tables, never
58
+ * per-token. */
59
+ function signArray(dim: TurboQuantHeadDim): MlxArray {
60
+ let a = signArrayCache.get(dim);
61
+ if (!a) {
62
+ a = MlxArray.fromFloat32(new Float32Array(SIGN_VECTORS[dim]), [dim]);
63
+ signArrayCache.set(dim, a);
64
+ }
65
+ return a;
66
+ }
67
+
68
+ // --- Lloyd-Max centroid/boundary constants -------------------------------
69
+
70
+ const centroidArrayCache = new Map<number, MlxArray>();
71
+ const boundaryArrayCache = new Map<number, MlxArray>();
72
+
73
+ function isSupportedValueBits(bits: number): bits is TurboQuantValueBits {
74
+ return (TURBOQUANT_VALUE_BITS as readonly number[]).includes(bits);
75
+ }
76
+
77
+ function lloydMaxTableFor(bits: number) {
78
+ if (!isSupportedValueBits(bits)) {
79
+ throw new Error(`turboquant: no Lloyd-Max table for bits=${bits}`);
80
+ }
81
+ return LLOYD_MAX[bits];
82
+ }
83
+
84
+ function centroidsFor(bits: number): MlxArray {
85
+ let a = centroidArrayCache.get(bits);
86
+ if (!a) {
87
+ const table = lloydMaxTableFor(bits);
88
+ a = MlxArray.fromFloat32(new Float32Array(table.centroids), [table.centroids.length]);
89
+ centroidArrayCache.set(bits, a);
90
+ }
91
+ return a;
92
+ }
93
+
94
+ function boundariesFor(bits: number): MlxArray {
95
+ let a = boundaryArrayCache.get(bits);
96
+ if (!a) {
97
+ const table = lloydMaxTableFor(bits);
98
+ a = MlxArray.fromFloat32(new Float32Array(table.boundaries), [table.boundaries.length]);
99
+ boundaryArrayCache.set(bits, a);
100
+ }
101
+ return a;
102
+ }
103
+
104
+ // --- FWHT (fwht() in the reference: sign-multiply then/or Hadamard) -----
105
+
106
+ /** Rotation step used by both encode and decode. `encode=true`: x*signs
107
+ * then hadamard_transform (forward). `encode=false`: hadamard_transform
108
+ * then x*signs (inverse — Hadamard is self-inverse up to the 1/sqrt(d)
109
+ * normalization mlx's hadamard_transform already applies by default, so
110
+ * applying it twice with signs on the outside undoes the rotation
111
+ * exactly, matching the reference's `fwht(x, encode=False)`). */
112
+ export function fwht(x: MlxArray, encode: boolean, s: S = gpuStream): MlxArray {
113
+ const dim = x.shape[x.shape.length - 1]!;
114
+ if (!isSupportedHeadDim(dim)) {
115
+ throw new Error(
116
+ `turboquant fwht: head_dim ${dim} not in supported set ${TURBOQUANT_HEAD_DIMS.join(",")}`,
117
+ );
118
+ }
119
+ const signs = signArray(dim);
120
+ if (encode) {
121
+ const signed = ops.mul(x, signs, s);
122
+ const rotated = ops.hadamardTransform(signed, null, s);
123
+ signed.dispose();
124
+ return rotated;
125
+ }
126
+ const rotated = ops.hadamardTransform(x, null, s);
127
+ const signed = ops.mul(rotated, signs, s);
128
+ rotated.dispose();
129
+ return signed;
130
+ }
131
+
132
+ // --- searchsorted: index = count(boundaries < x) -------------------------
133
+ // Reference: (x[..., None] > boundaries).sum(axis=-1) — broadcast compare
134
+ // then reduce over the boundary axis (the LAST axis after broadcasting,
135
+ // since boundaries is 1-D and lands in the new trailing dim).
136
+
137
+ function searchsorted(boundaries: MlxArray, x: MlxArray, s: S = gpuStream): MlxArray {
138
+ const xExpanded = ops.expandDims(x, -1, s);
139
+ const cmp = ops.greater(xExpanded, boundaries, s);
140
+ xExpanded.dispose();
141
+ const idx = ops.sumAxis(cmp, -1, false, s);
142
+ cmp.dispose();
143
+ return idx;
144
+ }
145
+
146
+ // --- key encode/decode: asymmetric per-32-group affine -------------------
147
+
148
+ export interface TurboQuantKeyEncoded {
149
+ /** int8 (signed=true, 8 bits) or uint8 (unsigned) indices, one element
150
+ * per input element — NOT bit-packed here; call packBits separately
151
+ * (mirrors the reference's turbo_quant_encode_key / turbo_quant_encode
152
+ * split: quantize() returns unpacked indices, turbo_quant_encode packs
153
+ * sub-8-bit ones). */
154
+ indices: MlxArray;
155
+ /** fp16, shape [..., headDim/32] */
156
+ scales: MlxArray;
157
+ /** fp16, shape [..., headDim/32] */
158
+ zeros: MlxArray;
159
+ }
160
+
161
+ /** Port of quantize() in the reference. `bits` in {2,4,5,8}; `signed` is
162
+ * only meaningful (and only ever true) for bits===8 (q8_0/int8) — every
163
+ * sub-8-bit key type in QUANT_PARAMS is unsigned. Groups run along the
164
+ * LAST axis (head_dim), BLOCK_SIZE=32 elements per group. */
165
+ export function encodeKeys(
166
+ x: MlxArray, bits: number, signed: boolean, s: S = gpuStream,
167
+ ): TurboQuantKeyEncoded {
168
+ const shape = x.shape;
169
+ const dim = shape[shape.length - 1]!;
170
+ if (dim % BLOCK_SIZE !== 0) {
171
+ throw new Error(`turboquant encodeKeys: head_dim ${dim} not divisible by ${BLOCK_SIZE}`);
172
+ }
173
+ // Upcast to fp32 for the affine-quant arithmetic below regardless of the
174
+ // caller's dtype — production callers hand this bf16 K straight off the
175
+ // model, and doing min/max/scale/zero-point/round at bf16 precision
176
+ // measurably shifts which rounding boundary an element lands on (see the
177
+ // dtype-routing note above). fp32 input is a no-op cast.
178
+ const x32 = x.astype(Dtype.float32, s);
179
+ const nGroups = dim / BLOCK_SIZE;
180
+ const groupShape = [...shape.slice(0, -1), nGroups, BLOCK_SIZE];
181
+ const xg = ops.reshape(x32, groupShape, s);
182
+ x32.dispose();
183
+
184
+ const xMin = ops.minAxis(xg, -1, true, s);
185
+ const xMax = ops.maxAxis(xg, -1, true, s);
186
+
187
+ const eps = ops.scalarLike(1e-8, xMax);
188
+
189
+ let scale: MlxArray;
190
+ let zeroPoint: MlxArray;
191
+ let indices: MlxArray;
192
+ const maxVal = signed ? (1 << (bits - 1)) - 1 : (1 << bits) - 1;
193
+
194
+ if (signed) {
195
+ // scale = (max-min) / (2*max_val)
196
+ const range = ops.sub(xMax, xMin, s);
197
+ const twoMaxVal = ops.scalarLike(2.0 * maxVal, range);
198
+ scale = ops.div(range, twoMaxVal, s);
199
+ range.dispose();
200
+ twoMaxVal.dispose();
201
+
202
+ const scaleEps = ops.add(scale, eps, s);
203
+ const two = ops.scalarLike(2.0, scaleEps);
204
+ const denom = ops.mul(two, scaleEps, s);
205
+ two.dispose();
206
+ scaleEps.dispose();
207
+
208
+ const sumMinMax = ops.add(xMax, xMin, s);
209
+ const zpRaw = ops.div(sumMinMax, denom, s);
210
+ sumMinMax.dispose();
211
+ zeroPoint = ops.round(zpRaw, s);
212
+ zpRaw.dispose();
213
+
214
+ const scaleEps2 = ops.add(scale, eps, s);
215
+ const xOverScale = ops.div(xg, scaleEps2, s);
216
+ scaleEps2.dispose();
217
+ const shifted = ops.sub(xOverScale, zeroPoint, s);
218
+ xOverScale.dispose();
219
+ const rounded = ops.round(shifted, s);
220
+ shifted.dispose();
221
+ const loBound = ops.scalarLike(-maxVal, rounded);
222
+ const hiBound = ops.scalarLike(maxVal, rounded);
223
+ const clipped = ops.clip(rounded, loBound, hiBound, s);
224
+ rounded.dispose();
225
+ loBound.dispose();
226
+ hiBound.dispose();
227
+ denom.dispose();
228
+ indices = ops.reshape(clipped, shape, s);
229
+ clipped.dispose();
230
+ } else {
231
+ // scale = (max-min) / max_val
232
+ const range = ops.sub(xMax, xMin, s);
233
+ const maxValArr = ops.scalarLike(maxVal, range);
234
+ scale = ops.div(range, maxValArr, s);
235
+ range.dispose();
236
+ maxValArr.dispose();
237
+
238
+ const scaleEps = ops.add(scale, eps, s);
239
+ const zpRaw = ops.div(xMin, scaleEps, s);
240
+ scaleEps.dispose();
241
+ zeroPoint = ops.round(zpRaw, s);
242
+ zpRaw.dispose();
243
+
244
+ const scaleEps2 = ops.add(scale, eps, s);
245
+ const xOverScale = ops.div(xg, scaleEps2, s);
246
+ scaleEps2.dispose();
247
+ const shifted = ops.sub(xOverScale, zeroPoint, s);
248
+ xOverScale.dispose();
249
+ const rounded = ops.round(shifted, s);
250
+ shifted.dispose();
251
+ const loBound = ops.scalarLike(0, rounded);
252
+ const hiBound = ops.scalarLike(maxVal, rounded);
253
+ const clipped = ops.clip(rounded, loBound, hiBound, s);
254
+ rounded.dispose();
255
+ loBound.dispose();
256
+ hiBound.dispose();
257
+ indices = ops.reshape(clipped, shape, s);
258
+ clipped.dispose();
259
+ }
260
+
261
+ eps.dispose();
262
+ xMin.dispose();
263
+ xMax.dispose();
264
+ xg.dispose();
265
+
266
+ const outDtype = signed ? Dtype.int8 : Dtype.uint8;
267
+ const indicesTyped = indices.astype(outDtype, s);
268
+ indices.dispose();
269
+
270
+ const scaleSq = ops.reshape(scale, [...shape.slice(0, -1), nGroups], s);
271
+ scale.dispose();
272
+ const zeroSq = ops.reshape(zeroPoint, [...shape.slice(0, -1), nGroups], s);
273
+ zeroPoint.dispose();
274
+ const scaleF16 = scaleSq.astype(Dtype.float16, s);
275
+ scaleSq.dispose();
276
+ const zeroF16 = zeroSq.astype(Dtype.float16, s);
277
+ zeroSq.dispose();
278
+
279
+ return { indices: indicesTyped, scales: scaleF16, zeros: zeroF16 };
280
+ }
281
+
282
+ /** Port of dequantize(): x = (indices + zero_point) * scale, output cast
283
+ * to bf16 (the cache's working dtype). `indices` must be UNPACKED
284
+ * (one element per array element) and scales/zeros are [..., dim/32]. */
285
+ export function decodeKeys(
286
+ indices: MlxArray, scales: MlxArray, zeros: MlxArray, s: S = gpuStream,
287
+ ): MlxArray {
288
+ const shape = indices.shape;
289
+ const dim = shape[shape.length - 1]!;
290
+ const nGroups = scales.shape[scales.shape.length - 1]!;
291
+ const groupShape = [...shape.slice(0, -1), nGroups, dim / nGroups];
292
+
293
+ const idxF32 = indices.astype(Dtype.float32, s);
294
+ const idxG = ops.reshape(idxF32, groupShape, s);
295
+ idxF32.dispose();
296
+
297
+ const zerosExp = ops.expandDims(zeros, -1, s);
298
+ const scalesExp = ops.expandDims(scales, -1, s);
299
+
300
+ const sum = ops.add(idxG, zerosExp, s);
301
+ idxG.dispose();
302
+ zerosExp.dispose();
303
+ const scaled = ops.mul(sum, scalesExp, s);
304
+ sum.dispose();
305
+ scalesExp.dispose();
306
+
307
+ const out = ops.reshape(scaled, shape, s);
308
+ scaled.dispose();
309
+ const outBf16 = out.astype(Dtype.bfloat16, s);
310
+ out.dispose();
311
+ return outBf16;
312
+ }
313
+
314
+ // --- value encode/decode: FWHT + Lloyd-Max per-32-group RMS scale --------
315
+
316
+ export interface TurboQuantValueEncoded {
317
+ /** uint8 indices in [0, 2^bits - 1], one per input element (unpacked). */
318
+ indices: MlxArray;
319
+ /** fp16, shape [..., headDim/32] */
320
+ scales: MlxArray;
321
+ }
322
+
323
+ /** Port of turbo_quant_encode_value(): rotate (fwht) then Lloyd-Max
324
+ * quantize (lm_quant) per 32-group RMS scale. */
325
+ export function encodeValues(x: MlxArray, bits: number, s: S = gpuStream): TurboQuantValueEncoded {
326
+ const rotated = fwht(x, true, s);
327
+ const shape = rotated.shape;
328
+ const dim = shape[shape.length - 1]!;
329
+ if (dim % BLOCK_SIZE !== 0) {
330
+ throw new Error(`turboquant encodeValues: head_dim ${dim} not divisible by ${BLOCK_SIZE}`);
331
+ }
332
+ const nGroups = dim / BLOCK_SIZE;
333
+ const groupShape = [...shape.slice(0, -1), nGroups, BLOCK_SIZE];
334
+ const xg = ops.reshape(rotated, groupShape, s);
335
+ rotated.dispose();
336
+
337
+ const sq = ops.square(xg, s);
338
+ const meanSq = ops.meanAxis(sq, -1, true, s);
339
+ sq.dispose();
340
+ const scale = ops.sqrt(meanSq, s);
341
+ meanSq.dispose();
342
+
343
+ const eps = ops.scalarLike(1e-8, scale);
344
+ const scaleEps = ops.add(scale, eps, s);
345
+ eps.dispose();
346
+ const xNorm = ops.div(xg, scaleEps, s);
347
+ scaleEps.dispose();
348
+ xg.dispose();
349
+
350
+ const boundaries = boundariesFor(bits);
351
+ const idxG = searchsorted(boundaries, xNorm, s);
352
+ xNorm.dispose();
353
+
354
+ const idxShaped = ops.reshape(idxG, shape, s);
355
+ idxG.dispose();
356
+ const idxU8 = idxShaped.astype(Dtype.uint8, s);
357
+ idxShaped.dispose();
358
+
359
+ const scaleSq = ops.reshape(scale, [...shape.slice(0, -1), nGroups], s);
360
+ scale.dispose();
361
+ const scaleF16 = scaleSq.astype(Dtype.float16, s);
362
+ scaleSq.dispose();
363
+
364
+ return { indices: idxU8, scales: scaleF16 };
365
+ }
366
+
367
+ /** Port of turbo_quant_decode_value(): centroid lookup + block rescale,
368
+ * then inverse FWHT. Output cast to bf16. */
369
+ /** Dequantize to the ROTATED (FWHT) domain in f32: centroids[idx] * scale,
370
+ * no inverse rotation. Shared tail of decodeValues / decodeValuesRotated. */
371
+ function dequantScaled(
372
+ indices: MlxArray, scales: MlxArray, bits: number, s: S,
373
+ ): MlxArray {
374
+ const shape = indices.shape;
375
+ const dim = shape[shape.length - 1]!;
376
+ const nGroups = scales.shape[scales.shape.length - 1]!;
377
+ const groupShape = [...shape.slice(0, -1), nGroups, dim / nGroups];
378
+
379
+ const idxI32 = indices.astype(Dtype.int32, s);
380
+ const idxG = ops.reshape(idxI32, groupShape, s);
381
+ idxI32.dispose();
382
+
383
+ const centroids = centroidsFor(bits);
384
+ // mx.take_axis over the LAST axis: centroids[idx] element-wise lookup.
385
+ const xNorm = ops.takeAxis(centroids, idxG, -1, s);
386
+ idxG.dispose();
387
+
388
+ const scalesExp = ops.expandDims(scales, -1, s);
389
+ const scaled = ops.mul(xNorm, scalesExp, s);
390
+ xNorm.dispose();
391
+ scalesExp.dispose();
392
+
393
+ const flat = ops.reshape(scaled, shape, s);
394
+ scaled.dispose();
395
+ return flat;
396
+ }
397
+
398
+ export function decodeValues(
399
+ indices: MlxArray, scales: MlxArray, bits: number, s: S = gpuStream,
400
+ ): MlxArray {
401
+ const flat = dequantScaled(indices, scales, bits, s);
402
+ const rotatedBack = fwht(flat, false, s);
403
+ flat.dispose();
404
+
405
+ const outBf16 = rotatedBack.astype(Dtype.bfloat16, s);
406
+ rotatedBack.dispose();
407
+ return outBf16;
408
+ }
409
+
410
+ /** Dequantized values still in the ROTATED domain (bf16) — the deferred-
411
+ * inverse-FWHT read path. Attention over V is linear in V, so
412
+ * InvFWHT(Σᵢ wᵢ·v̂ᵢ) = Σᵢ wᵢ·InvFWHT(v̂ᵢ): sdpa may run on these directly
413
+ * and the caller un-rotates the attention OUTPUT once per query row
414
+ * (unrotateValues) instead of un-rotating every cached token per step —
415
+ * vllm-metal's deferred-V trick, O(q·d log d) instead of O(T·d log d).
416
+ * Not bit-identical to the eager path (reduction order differs); both are
417
+ * valid decodes of the same cache bytes. */
418
+ export function decodeValuesRotated(
419
+ indices: MlxArray, scales: MlxArray, bits: number, s: S = gpuStream,
420
+ ): MlxArray {
421
+ const flat = dequantScaled(indices, scales, bits, s);
422
+ const outBf16 = flat.astype(Dtype.bfloat16, s);
423
+ flat.dispose();
424
+ return outBf16;
425
+ }
426
+
427
+ /** Optional exact packed K/V decode. Inputs stay borrowed; the caller owns
428
+ * the returned pair. The eager path keeps the reference inverse rotation. */
429
+ export function tryDecodePackedKv(
430
+ inputs: PackedKvArrays, kBits: number, vBits: number, headDim: number,
431
+ deferV = false, s: S = gpuStream,
432
+ ): [MlxArray, MlxArray] | null {
433
+ // Reject unsupported value widths before requesting their centroid table.
434
+ if (![2, 3, 4, 5, 8].includes(vBits)) return null;
435
+ if (!deferV && headDim === 256 && kBits === 8 && vBits === 3 &&
436
+ s === gpuStream && !isShapelessTracing() && inputs[0].shape[2]! >= 8192) {
437
+ const decoded = tryDecodePackedKvInverse256(
438
+ inputs, centroidsFor(vBits), signArray(256), kBits, vBits, headDim, s,
439
+ );
440
+ if (decoded) return decoded;
441
+ }
442
+ const decoded = tryJointDecodePackedKv(inputs, centroidsFor(vBits), kBits, vBits, headDim, deferV, s);
443
+ if (!decoded || deferV) return decoded;
444
+ const [key, rotated] = decoded;
445
+ try {
446
+ const value = fwht(rotated, false, s);
447
+ try { return [key, value.astype(Dtype.bfloat16, s)]; }
448
+ finally { value.dispose(); }
449
+ } catch (error) { key.dispose(); throw error; }
450
+ finally { rotated.dispose(); }
451
+ }
452
+
453
+ /** Undo the value rotation on an attention output computed against
454
+ * decodeValuesRotated values. f32 through the transform (matching the
455
+ * eager decode path's precision), returned in the input's dtype. */
456
+ export function unrotateValues(x: MlxArray, s: S = gpuStream): MlxArray {
457
+ const dt = x.dtype;
458
+ const f32 = x.astype(Dtype.float32, s);
459
+ const rotatedBack = fwht(f32, false, s);
460
+ f32.dispose();
461
+ const out = rotatedBack.astype(dt, s);
462
+ rotatedBack.dispose();
463
+ return out;
464
+ }
465
+
466
+ // --- bit packing ----------------------------------------------------------
467
+ // Flat little-endian bitstream: element i occupies bits [i*b, i*b+b) —
468
+ // ports of _pack_2bit/_pack_3bit/_pack_4bit/_pack_5bit and their unpack
469
+ // twins. Values are always uint8 (or promoted to uint32 internally for
470
+ // widths needing >8-bit intermediate combination, matching the reference's
471
+ // own dtype choices exactly since bitwise ops on the wrong width silently
472
+ // truncate differently).
473
+
474
+ function u8(value: number, like: MlxArray): MlxArray {
475
+ return ops.scalarLike(value, like);
476
+ }
477
+
478
+ function groupsOf(a: MlxArray, groupSize: number): { xg: MlxArray; shape: number[]; nGroups: number } {
479
+ const shape = a.shape;
480
+ const dim = shape[shape.length - 1]!;
481
+ const nGroups = dim / groupSize;
482
+ const xg = ops.reshape(a, [...shape.slice(0, -1), nGroups, groupSize]);
483
+ return { xg, shape, nGroups };
484
+ }
485
+
486
+ /** Split the last axis into single-element lanes and drop that trailing
487
+ * axis, DISPOSING the raw split slices (2026-07-07 review: the bare
488
+ * `split().map(reshape)` orphaned every slice node — each pinned the full
489
+ * window-sized input on the per-decode-step unpack path, ~8 MB/call at 2k
490
+ * context, OOM within dozens of tokens of real serving). */
491
+ function splitLanes(a: MlxArray, indices: number[]): MlxArray[] {
492
+ return ops.split(a, indices, -1).map((l) => {
493
+ const r = ops.reshape(l, l.shape.slice(0, -1));
494
+ l.dispose();
495
+ return r;
496
+ });
497
+ }
498
+
499
+ /** vals: [..., dim] uint8, each using only 2 bits. Returns [..., dim/4] uint8. */
500
+ function pack2bit(vals: MlxArray): MlxArray {
501
+ const { xg } = groupsOf(vals, 4);
502
+ const lanes = splitLanes(xg, [1, 2, 3]);
503
+ xg.dispose();
504
+ const mask = u8(0x3, lanes[0]!);
505
+ const v0 = ops.bitwiseAnd(lanes[0]!, mask);
506
+ const v1raw = ops.bitwiseAnd(lanes[1]!, mask);
507
+ const shift2 = u8(2, lanes[0]!);
508
+ const v1 = ops.leftShift(v1raw, shift2);
509
+ v1raw.dispose();
510
+ const v2raw = ops.bitwiseAnd(lanes[2]!, mask);
511
+ const shift4 = u8(4, lanes[0]!);
512
+ const v2 = ops.leftShift(v2raw, shift4);
513
+ v2raw.dispose();
514
+ const v3raw = ops.bitwiseAnd(lanes[3]!, mask);
515
+ const shift6 = u8(6, lanes[0]!);
516
+ const v3 = ops.leftShift(v3raw, shift6);
517
+ v3raw.dispose();
518
+ mask.dispose(); shift2.dispose(); shift4.dispose(); shift6.dispose();
519
+ lanes.forEach((l) => l.dispose());
520
+
521
+ const o1 = ops.bitwiseOr(v0, v1); v0.dispose(); v1.dispose();
522
+ const o2 = ops.bitwiseOr(o1, v2); o1.dispose(); v2.dispose();
523
+ const packed = ops.bitwiseOr(o2, v3); o2.dispose(); v3.dispose();
524
+ return packed;
525
+ }
526
+
527
+ function unpack2bit(packed: MlxArray, origDim: number): MlxArray {
528
+ const shape = packed.shape;
529
+ const g = ops.reshape(packed, [...shape.slice(0, -1), packed.shape[packed.shape.length - 1]!, 1]);
530
+ const mask = u8(0x3, g);
531
+ const v0 = ops.bitwiseAnd(g, mask);
532
+ const s2 = u8(2, g);
533
+ const g2 = ops.rightShift(g, s2); const v1 = ops.bitwiseAnd(g2, mask); g2.dispose();
534
+ const s4 = u8(4, g);
535
+ const g4 = ops.rightShift(g, s4); const v2 = ops.bitwiseAnd(g4, mask); g4.dispose();
536
+ const s6 = u8(6, g);
537
+ const g6 = ops.rightShift(g, s6); const v3 = ops.bitwiseAnd(g6, mask); g6.dispose();
538
+ mask.dispose(); s2.dispose(); s4.dispose(); s6.dispose(); g.dispose();
539
+ const cat = ops.concatAxis([v0, v1, v2, v3], -1);
540
+ v0.dispose(); v1.dispose(); v2.dispose(); v3.dispose();
541
+ const out = ops.reshape(cat, [...shape.slice(0, -1), origDim]);
542
+ cat.dispose();
543
+ return out;
544
+ }
545
+
546
+ /** vals: [..., dim] uint8 (each using 3 bits). Returns [..., dim*3/8] uint8.
547
+ * Matches _pack_3bit exactly: 8 values -> 3 bytes, via uint32 intermediates
548
+ * to avoid overflow while combining >8 bits per lane. */
549
+ function pack3bit(vals: MlxArray): MlxArray {
550
+ const { xg } = groupsOf(vals, 8);
551
+ const xg32 = xg.astype(Dtype.uint32);
552
+ xg.dispose();
553
+ const lanes = splitLanes(xg32, [1, 2, 3, 4, 5, 6, 7]);
554
+ xg32.dispose();
555
+ const v = lanes;
556
+ const mask7 = u8(0x7, v[0]!);
557
+
558
+ const m = (i: number) => ops.bitwiseAnd(v[i]!, mask7);
559
+ const shl = (a: MlxArray, n: number) => {
560
+ const sh = u8(n, a);
561
+ const r = ops.leftShift(a, sh);
562
+ sh.dispose();
563
+ return r;
564
+ };
565
+ const shr = (a: MlxArray, n: number) => {
566
+ const sh = u8(n, a);
567
+ const r = ops.rightShift(a, sh);
568
+ sh.dispose();
569
+ return r;
570
+ };
571
+
572
+ // Or-accumulate DISPOSING the previous accumulator (2026-07-07 review:
573
+ // the bare `b = ops.bitwiseOr(b, x)` reassignment orphaned the prior
574
+ // node — same discipline as pack5bit's byteVal loop).
575
+ const orInto = (acc: MlxArray, x: MlxArray): MlxArray => {
576
+ const next = ops.bitwiseOr(acc, x);
577
+ acc.dispose();
578
+ x.dispose();
579
+ return next;
580
+ };
581
+
582
+ // b0 = v0 | (v1<<3) | (v2<<6)
583
+ const m0 = m(0);
584
+ const m1 = m(1); const m1s = shl(m1, 3); m1.dispose();
585
+ const m2 = m(2); const m2s = shl(m2, 6); m2.dispose();
586
+ let b0 = ops.bitwiseOr(m0, m1s); m0.dispose(); m1s.dispose();
587
+ b0 = orInto(b0, m2s);
588
+
589
+ // b1 = (v2>>2) | (v3<<1) | (v4<<4) | (v5<<7)
590
+ const m2b = m(2); const m2bs = shr(m2b, 2); m2b.dispose();
591
+ const m3 = m(3); const m3s = shl(m3, 1); m3.dispose();
592
+ const m4 = m(4); const m4s = shl(m4, 4); m4.dispose();
593
+ const m5 = m(5); const m5s = shl(m5, 7); m5.dispose();
594
+ let b1 = ops.bitwiseOr(m2bs, m3s); m2bs.dispose(); m3s.dispose();
595
+ b1 = orInto(b1, m4s);
596
+ b1 = orInto(b1, m5s);
597
+
598
+ // b2 = (v5>>1) | (v6<<2) | (v7<<5)
599
+ const m5b = m(5); const m5bs = shr(m5b, 1); m5b.dispose();
600
+ const m6 = m(6); const m6s = shl(m6, 2); m6.dispose();
601
+ const m7 = m(7); const m7s = shl(m7, 5); m7.dispose();
602
+ let b2 = ops.bitwiseOr(m5bs, m6s); m5bs.dispose(); m6s.dispose();
603
+ b2 = orInto(b2, m7s);
604
+
605
+ mask7.dispose();
606
+ v.forEach((l) => l.dispose());
607
+
608
+ const mask255 = u8(0xff, b0);
609
+ const b0m = ops.bitwiseAnd(b0, mask255); b0.dispose();
610
+ const b1m = ops.bitwiseAnd(b1, mask255); b1.dispose();
611
+ const b2m = ops.bitwiseAnd(b2, mask255); b2.dispose();
612
+ mask255.dispose();
613
+
614
+ const b0e = ops.expandDims(b0m, -1); b0m.dispose();
615
+ const b1e = ops.expandDims(b1m, -1); b1m.dispose();
616
+ const b2e = ops.expandDims(b2m, -1); b2m.dispose();
617
+ const packed32 = ops.concatAxis([b0e, b1e, b2e], -1);
618
+ b0e.dispose(); b1e.dispose(); b2e.dispose();
619
+ const shape = vals.shape;
620
+ const dim = shape[shape.length - 1]!;
621
+ const packedFlat = ops.reshape(packed32, [...shape.slice(0, -1), (dim / 8) * 3]);
622
+ packed32.dispose();
623
+ const packed = packedFlat.astype(Dtype.uint8);
624
+ packedFlat.dispose();
625
+ return packed;
626
+ }
627
+
628
+ /** Inverse of pack3bit. packed: [..., dim*3/8] uint8 -> [..., dim] uint8. */
629
+ function unpack3bit(packed: MlxArray, origDim: number): MlxArray {
630
+ const shape = packed.shape;
631
+ const { xg } = groupsOf(packed, 3);
632
+ const xg32 = xg.astype(Dtype.uint32);
633
+ xg.dispose();
634
+ const bytes = splitLanes(xg32, [1, 2]);
635
+ xg32.dispose();
636
+ const [b0, b1, b2] = bytes;
637
+
638
+ const s8 = u8(8, b0!);
639
+ const s16 = u8(16, b0!);
640
+ const b1s = ops.leftShift(b1!, s8);
641
+ const b2s = ops.leftShift(b2!, s16);
642
+ s8.dispose(); s16.dispose();
643
+ const comb01 = ops.bitwiseOr(b0!, b1s); b1s.dispose();
644
+ const combined = ops.bitwiseOr(comb01, b2s); comb01.dispose(); b2s.dispose();
645
+ b0!.dispose(); b1!.dispose(); b2!.dispose();
646
+
647
+ const mask7 = u8(0x7, combined);
648
+ const vals: MlxArray[] = [];
649
+ for (let i = 0; i < 8; i++) {
650
+ const sh = u8(i * 3, combined);
651
+ const shifted = ops.rightShift(combined, sh);
652
+ sh.dispose();
653
+ const v = ops.bitwiseAnd(shifted, mask7);
654
+ shifted.dispose();
655
+ vals.push(ops.expandDims(v, -1));
656
+ v.dispose();
657
+ }
658
+ mask7.dispose();
659
+ combined.dispose();
660
+ const cat = ops.concatAxis(vals, -1);
661
+ vals.forEach((v) => v.dispose());
662
+ const outFlat = ops.reshape(cat, [...shape.slice(0, -1), origDim]);
663
+ cat.dispose();
664
+ const out = outFlat.astype(Dtype.uint8);
665
+ outFlat.dispose();
666
+ return out;
667
+ }
668
+
669
+ /** vals: [..., dim] uint8 (each using 4 bits). Returns [..., dim/2] uint8. */
670
+ function pack4bit(vals: MlxArray): MlxArray {
671
+ const { xg } = groupsOf(vals, 2);
672
+ const lanes = splitLanes(xg, [1]);
673
+ xg.dispose();
674
+ const [v0, v1] = lanes;
675
+ const mask = u8(0xf, v0!);
676
+ const m0 = ops.bitwiseAnd(v0!, mask);
677
+ const m1raw = ops.bitwiseAnd(v1!, mask);
678
+ const shift4 = u8(4, v0!);
679
+ const m1 = ops.leftShift(m1raw, shift4);
680
+ m1raw.dispose(); shift4.dispose(); mask.dispose();
681
+ v0!.dispose(); v1!.dispose();
682
+ const packed = ops.bitwiseOr(m0, m1);
683
+ m0.dispose(); m1.dispose();
684
+ return packed;
685
+ }
686
+
687
+ function unpack4bit(packed: MlxArray, origDim: number): MlxArray {
688
+ const shape = packed.shape;
689
+ const g = ops.reshape(packed, [...shape.slice(0, -1), packed.shape[packed.shape.length - 1]!, 1]);
690
+ const mask = u8(0xf, g);
691
+ const lo = ops.bitwiseAnd(g, mask);
692
+ const s4 = u8(4, g);
693
+ const g4 = ops.rightShift(g, s4);
694
+ const hi = ops.bitwiseAnd(g4, mask);
695
+ g4.dispose(); s4.dispose(); mask.dispose(); g.dispose();
696
+ const cat = ops.concatAxis([lo, hi], -1);
697
+ lo.dispose(); hi.dispose();
698
+ const out = ops.reshape(cat, [...shape.slice(0, -1), origDim]);
699
+ cat.dispose();
700
+ return out;
701
+ }
702
+
703
+ // 5-bit pack/unpack: 8 lanes of 5 bits = 40 bits -> 5 bytes. mlx has no
704
+ // uint64 dtype exposed here (the reference combines via uint64), but since
705
+ // every output byte's contributing lane-bit-ranges independently fit
706
+ // within 8 bits once masked and shifted, the whole packing decomposes into
707
+ // a fixed table of (lane, lane_bit_lo, lane_bit_hi, out_bit_lo) triples per
708
+ // output byte — computed once below — with no wider-than-8-bit intermediate
709
+ // ever needed. This is bit-identical to the reference's 40-bit combine.
710
+ type FiveBitContrib = { lane: number; laneBitLo: number; width: number; outBitLo: number };
711
+ const FIVE_BIT_BYTE_TABLE: FiveBitContrib[][] = (() => {
712
+ const table: FiveBitContrib[][] = [[], [], [], [], []];
713
+ for (let byteIdx = 0; byteIdx < 5; byteIdx++) {
714
+ const byteLo = byteIdx * 8;
715
+ const byteHi = byteLo + 8;
716
+ for (let lane = 0; lane < 8; lane++) {
717
+ const laneLo = lane * 5;
718
+ const laneHi = laneLo + 5;
719
+ const ovLo = Math.max(laneLo, byteLo);
720
+ const ovHi = Math.min(laneHi, byteHi);
721
+ if (ovLo < ovHi) {
722
+ table[byteIdx]!.push({
723
+ lane, laneBitLo: ovLo - laneLo, width: ovHi - ovLo, outBitLo: ovLo - byteLo,
724
+ });
725
+ }
726
+ }
727
+ }
728
+ return table;
729
+ })();
730
+
731
+ /** vals: [..., dim] uint8 (each using 5 bits). Returns [..., dim*5/8] uint8. */
732
+ function pack5bit(vals: MlxArray): MlxArray {
733
+ const { xg } = groupsOf(vals, 8);
734
+ const xg32 = xg.astype(Dtype.uint32);
735
+ xg.dispose();
736
+ const lanes = splitLanes(xg32, [1, 2, 3, 4, 5, 6, 7]);
737
+ xg32.dispose();
738
+
739
+ const bytes: MlxArray[] = [];
740
+ for (const contribs of FIVE_BIT_BYTE_TABLE) {
741
+ let byteVal: MlxArray | null = null;
742
+ for (const c of contribs) {
743
+ const widthMask = u8((1 << c.width) - 1, lanes[c.lane]!);
744
+ const laneShift = u8(c.laneBitLo, lanes[c.lane]!);
745
+ const shiftedDown = ops.rightShift(lanes[c.lane]!, laneShift);
746
+ laneShift.dispose();
747
+ const bits = ops.bitwiseAnd(shiftedDown, widthMask);
748
+ shiftedDown.dispose();
749
+ widthMask.dispose();
750
+ const outShift = u8(c.outBitLo, bits);
751
+ const placed = ops.leftShift(bits, outShift);
752
+ outShift.dispose();
753
+ bits.dispose();
754
+ if (byteVal === null) {
755
+ byteVal = placed;
756
+ } else {
757
+ const next = ops.bitwiseOr(byteVal, placed);
758
+ byteVal.dispose();
759
+ placed.dispose();
760
+ byteVal = next;
761
+ }
762
+ }
763
+ bytes.push(ops.expandDims(byteVal!, -1));
764
+ byteVal!.dispose();
765
+ }
766
+ lanes.forEach((l) => l.dispose());
767
+
768
+ const cat = ops.concatAxis(bytes, -1);
769
+ bytes.forEach((b) => b.dispose());
770
+ const shape = vals.shape;
771
+ const dim = shape[shape.length - 1]!;
772
+ const packedFlat = ops.reshape(cat, [...shape.slice(0, -1), (dim / 8) * 5]);
773
+ cat.dispose();
774
+ const packed = packedFlat.astype(Dtype.uint8);
775
+ packedFlat.dispose();
776
+ return packed;
777
+ }
778
+
779
+ /** Inverse of pack5bit. packed: [..., dim*5/8] uint8 -> [..., dim] uint8. */
780
+ function unpack5bit(packed: MlxArray, origDim: number): MlxArray {
781
+ const shape = packed.shape;
782
+ const { xg } = groupsOf(packed, 5);
783
+ const xg32 = xg.astype(Dtype.uint32);
784
+ xg.dispose();
785
+ const bytes = splitLanes(xg32, [1, 2, 3, 4]);
786
+ xg32.dispose();
787
+
788
+ const lanes: MlxArray[] = [];
789
+ for (let lane = 0; lane < 8; lane++) {
790
+ const laneLo = lane * 5;
791
+ const laneHi = laneLo + 5;
792
+ let laneVal: MlxArray | null = null;
793
+ for (let byteIdx = 0; byteIdx < 5; byteIdx++) {
794
+ const byteLo = byteIdx * 8;
795
+ const byteHi = byteLo + 8;
796
+ const ovLo = Math.max(laneLo, byteLo);
797
+ const ovHi = Math.min(laneHi, byteHi);
798
+ if (ovLo >= ovHi) continue;
799
+ const width = ovHi - ovLo;
800
+ const byteBitLo = ovLo - byteLo;
801
+ const laneBitLo = ovLo - laneLo;
802
+ const widthMask = u8((1 << width) - 1, bytes[byteIdx]!);
803
+ const byteShift = u8(byteBitLo, bytes[byteIdx]!);
804
+ const shiftedDown = ops.rightShift(bytes[byteIdx]!, byteShift);
805
+ byteShift.dispose();
806
+ const bits = ops.bitwiseAnd(shiftedDown, widthMask);
807
+ shiftedDown.dispose();
808
+ widthMask.dispose();
809
+ const laneShift = u8(laneBitLo, bits);
810
+ const placed = ops.leftShift(bits, laneShift);
811
+ laneShift.dispose();
812
+ bits.dispose();
813
+ if (laneVal === null) {
814
+ laneVal = placed;
815
+ } else {
816
+ const next = ops.bitwiseOr(laneVal, placed);
817
+ laneVal.dispose();
818
+ placed.dispose();
819
+ laneVal = next;
820
+ }
821
+ }
822
+ lanes.push(ops.expandDims(laneVal!, -1));
823
+ laneVal!.dispose();
824
+ }
825
+ bytes.forEach((b) => b.dispose());
826
+
827
+ const cat = ops.concatAxis(lanes, -1);
828
+ lanes.forEach((l) => l.dispose());
829
+ const outFlat = ops.reshape(cat, [...shape.slice(0, -1), origDim]);
830
+ cat.dispose();
831
+ const out = outFlat.astype(Dtype.uint8);
832
+ outFlat.dispose();
833
+ return out;
834
+ }
835
+
836
+ const _PACK_FNS: Record<number, (v: MlxArray) => MlxArray> = {
837
+ 2: pack2bit, 3: pack3bit, 4: pack4bit, 5: pack5bit,
838
+ };
839
+ const _UNPACK_FNS: Record<number, (v: MlxArray, origDim: number) => MlxArray> = {
840
+ 2: unpack2bit, 3: unpack3bit, 4: unpack4bit, 5: unpack5bit,
841
+ };
842
+
843
+ /** Bit-pack sub-8-bit unpacked values (uint8, one per element, using only
844
+ * the low `bits` bits) into a flat little-endian bitstream, `bits/8`
845
+ * bytes per `bits`-wide group of 8 elements (mirrors pack_bits). bits===8
846
+ * is a no-op (matches the reference). */
847
+ export function packBits(values: MlxArray, bits: number): MlxArray {
848
+ if (bits === 8) return values;
849
+ const fn = _PACK_FNS[bits];
850
+ if (!fn) throw new Error(`turboquant packBits: unsupported bit width ${bits}`);
851
+ return fn(values);
852
+ }
853
+
854
+ /** Inverse of packBits. bits===8 is a no-op. */
855
+ export function unpackBits(packed: MlxArray, bits: number, origDim: number): MlxArray {
856
+ if (bits === 8) return packed;
857
+ const fn = _UNPACK_FNS[bits];
858
+ if (!fn) throw new Error(`turboquant unpackBits: unsupported bit width ${bits}`);
859
+ return fn(packed, origDim);
860
+ }