@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,176 @@
1
+ // Drafter models as the draft sources see them. A drafter is a model: it is built
2
+ // and loaded in `models/` (`models/drafters.ts`), and the sources in
3
+ // `generation/speculative/` consume only these ports, never a concrete drafter.
4
+
5
+ import type { MlxArray } from "@mlx-bun/mlx/array";
6
+ import type { AssistantDonors } from "./attention";
7
+ import type { Cache } from "./cache";
8
+ import type { DraftProjection } from "./draft-projection";
9
+ import type { DraftProjectionKernels, ResidualBasis } from "./draft-target";
10
+ import type { MlxRowTable } from "./row-table";
11
+
12
+ export interface DrafterOperationRange<Operation> { readonly from: number; readonly to: number; readonly operation: Operation }
13
+ export type DrafterOperations<Operation> = MlxRowTable<Operation> | readonly DrafterOperationRange<Operation>[];
14
+
15
+ /** One drafted step of a KV-borrowing assistant: owned token ids and the post-projected hidden. */
16
+ export interface DrafterRowsStep { tokens: MlxArray; nextHidden: MlxArray }
17
+
18
+ /** One assistant draft step over B rows: the last token's embedding and the hidden it follows [B, 1, H]
19
+ * (borrowed), the donors, and the rows' position (one shared, or [B]); owned tokens and next hidden out. */
20
+ export type AssistantDraftStep = (lastTokenEmb: MlxArray, targetHidden: MlxArray, donors: AssistantDonors,
21
+ position: number | MlxArray) => DrafterRowsStep;
22
+
23
+ /** The optiq KV-borrowing assistant: no cache of its own, it reads the target's donor attention. */
24
+ export interface AssistantDrafterModel {
25
+ /** The draft step per row count or range of the rows it drafts for, each with the token selection its head
26
+ * bound for that class at construction; the caller indexes it by its rows (actual positive row count). */
27
+ readonly forwardRows: MlxRowTable<AssistantDraftStep>;
28
+ dispose(): void;
29
+ }
30
+
31
+ /** What a projected-context drafter (DSpark, DeepSpec) attends over the target's tapped hidden states. */
32
+ export interface ContextKV {
33
+ k: MlxArray; // [1, nKvHeads, ctxLen, headDim]
34
+ v: MlxArray; // [1, nKvHeads, ctxLen, headDim]
35
+ }
36
+
37
+ /** A projected-context drafter's context projection over B × L rows: the target's tapped hiddens
38
+ * [B, L, taps × H] (borrowed) to context rows [B, L, H] (owned). */
39
+ export type DrafterContextProjection = (targetHiddens: MlxArray) => MlxArray;
40
+
41
+ /** Each drafter layer's context K/V [B, kvHeads, L, headDim] (owned) of B × L context rows [B, L, H] (borrowed),
42
+ * at absolute positions from `position` (one shared, or [B] when the rows start apart). */
43
+ export type DrafterContextKV = (context: MlxArray, position: number | MlxArray) => ContextKV[];
44
+
45
+ /** Confidence-scheduled draft-length pruning and logits collection of one DSpark block. */
46
+ export interface DsparkDraftOptions {
47
+ thresholds?: number[];
48
+ minConf?: number;
49
+ /** Concatenate the per-position draft logits into the result; default true. */
50
+ collectLogits?: boolean;
51
+ collectConfidence?: boolean;
52
+ }
53
+
54
+ /** Storage owns context validity; the DSpark graph supplies only Q and the block's K/V. */
55
+ export interface DsparkContextAttention {
56
+ attend(layer: number, query: MlxArray, keys: MlxArray, values: MlxArray, scale: number): MlxArray;
57
+ }
58
+
59
+ /** Our trained DSpark module: block drafting over the target's multi-layer hidden context. */
60
+ export interface DsparkDrafterModel {
61
+ readonly cfg: {
62
+ readonly gamma: number;
63
+ readonly nLayers: number;
64
+ readonly tapLayers: number[];
65
+ readonly sts?: { readonly thresholds: number[] };
66
+ };
67
+ projectContextRows(hidden: MlxArray): { k: MlxArray; v: MlxArray }[];
68
+ forwardRows(model: DraftProjection, hCtx: MlxArray | null, anchors: readonly number[], gamma: number,
69
+ opts?: DsparkDraftOptions, context?: DsparkContextAttention): { tokens: number[][] };
70
+ dispose(): void;
71
+ }
72
+
73
+ /** Storage owns context validity; the DeepSpec graph supplies only Q and new block KV. */
74
+ export interface DeepspecContextAttention {
75
+ attend(layer: number, query: MlxArray, blockKeys: MlxArray, blockValues: MlxArray): MlxArray;
76
+ }
77
+
78
+ export interface DeepspecDraftRows {
79
+ tokens: number[][];
80
+ conf: number[][];
81
+ baseLogits?: MlxArray;
82
+ }
83
+
84
+ /** DeepSeek's released DSpark drafter (DeepSpec): a block forward over cached, already projected context K/V. */
85
+ export interface DeepspecDrafterModel {
86
+ readonly cfg: { readonly num_target_layers: number; readonly num_hidden_layers: number };
87
+ /** The target layers whose hiddens the drafter conditions on. */
88
+ readonly tapLayers: number[];
89
+ /** The trained block width. */
90
+ readonly gamma: number;
91
+ readonly hidden: number;
92
+ /** The context projection per row count or range of the rows projected (B × L), indexed by the caller
93
+ * (`B × L`): MLX's quantized matmul (matmul for a BF16 checkpoint) at every class. */
94
+ readonly projectContext: MlxRowTable<DrafterContextProjection>;
95
+ /** Each layer's context K/V per row count or range of the context rows (B × L), indexed like `projectContext`:
96
+ * the same kernel at every class. */
97
+ readonly projectContextKVRows: MlxRowTable<DrafterContextKV>;
98
+ draftRows(context: DeepspecContextAttention, anchors: readonly number[], position: number | MlxArray,
99
+ collectLogits?: boolean): DeepspecDraftRows;
100
+ dispose(): void;
101
+ }
102
+
103
+ /** One recurrent multi-token-prediction forward: token embeddings [B, S, H] paired with hiddens
104
+ * [B, S, H] (both borrowed) in, the module output (post final norm) [B, S, H] out, owned; appends S
105
+ * positions per row to `cache`, which supplies positions and storage. */
106
+ export type RecurrentMtpForward = (tokenEmbeds: MlxArray, hiddens: MlxArray, cache: Cache) => MlxArray;
107
+
108
+ /** The recurrent multi-token-prediction block split from a Qwen release, its phases named by the
109
+ * caller like a graph's: the draft step indexed by the rows it drafts for. */
110
+ export interface RecurrentMtpModule {
111
+ /** One position per row (a draft step, the round's bridge or full-accept row), by the rows' row count. */
112
+ readonly decode: MlxRowTable<RecurrentMtpForward>;
113
+ /** Several positions per row (prompt rows, a verified continuation). */
114
+ readonly window: RecurrentMtpForward;
115
+ }
116
+
117
+ /** The checkpoint-native multi-token-prediction row of a graph that declares `nativeDraft`, over
118
+ * compressed (MLA) attention state. The graph owns the numerics and the head's weights; the draft
119
+ * source owns sampling and state retention. */
120
+ export interface NativeMtpHead {
121
+ readonly hiddenSize: number;
122
+ /** Geometry of the compressed cache the head appends to. */
123
+ readonly cache: { readonly kvLoraRank: number; readonly ropeHeadDim: number; readonly maxTokens: number };
124
+ /** One draft step: `ids` [B, 1] (one token per sequence) over each row's anchor
125
+ * `hidden` [B, 1, hidden], appended to `cache`; the caller owns the output
126
+ * [B, 1, hidden]. */
127
+ decode(ids: MlxArray, hidden: MlxArray, cache: Cache): Promise<MlxArray>;
128
+ /** A window of two or more tokens per sequence, `ids` [B, L] over `hidden`
129
+ * [B, L, hidden], appended to `cache`; the caller owns the output. The caller
130
+ * names the phase from the window it built: one token per sequence is `decode`. */
131
+ window(ids: MlxArray, hidden: MlxArray, cache: Cache): Promise<MlxArray>;
132
+ /** Logits [B, positions, V] of the head's output. */
133
+ project(hidden: MlxArray): MlxArray;
134
+ }
135
+
136
+ /** DFlash 2's projected-context attention: block keys follow the context rows. */
137
+ export interface Dflash2ContextAttention {
138
+ attend(layer: number, query: MlxArray, blockKeys: MlxArray, blockValues: MlxArray, scale?: number): MlxArray;
139
+ }
140
+
141
+ /** The DFlash 2 block drafter: target taps → projected context K/V; one greedy block per anchor.
142
+ * It loads in the basis it was trained on and learns the target's when a draft group binds. */
143
+ export interface Dflash2DrafterModel {
144
+ readonly cfg: { readonly layers: number; readonly numTargetLayers: number };
145
+ readonly tapLayers: number[];
146
+ /** Draft tokens per block (block size minus the anchor). */
147
+ readonly gamma: number;
148
+ /** Apply the target's declarations before any projection: its residual basis (null: the trained basis) and
149
+ * the kernels its composition names for the drafter's 4-bit projections (null: the drafter's own rule). The
150
+ * first call applies them; every later call must pass the same declarations. */
151
+ bindTarget(basis: ResidualBasis | null, projections: DraftProjectionKernels | null): void;
152
+ /** The context projection (fc over the target's taps, then the hidden norm) per row count or range of the rows
153
+ * projected (B × L: a prompt's rows at prefill, a commit's accepted rows), indexed by the caller
154
+ * (`B × L`). A 4-bit fc runs the kernel the target declares for the class or, by the drafter's
155
+ * own rule, the simdgroup matrix unit (`Affine4MmaLinear`, where the weight's shape fits it) at 5..8
156
+ * and MLX's quantized matmul (`QuantizedLinear`) at every other class; a BF16 fc runs one matmul at every
157
+ * class. No entry runs before `bindTarget`. */
158
+ readonly projectContext: DrafterOperations<DrafterContextProjection>;
159
+ /** Each layer's k and v over the context rows (k norm, RoPE), per row count or range of those rows (B × L), indexed
160
+ * like `projectContext` and on the kernel it names for the class. */
161
+ readonly projectContextKVRows: DrafterOperations<DrafterContextKV>;
162
+ /** The columns of a block drafting `depth` tokens: its anchor and up to `depth` mask positions, at most the
163
+ * trained block size. */
164
+ blockColumns(depth: number): number;
165
+ /** The draft block per row count or range of its rows (anchors times columns), indexed by the scheduler: every 4-bit
166
+ * projection on the kernel `projectContext` runs for the class; BF16 projections run one matmul at every
167
+ * class. */
168
+ readonly draft: DrafterOperations<Dflash2DraftBlock>;
169
+ dispose(): void;
170
+ }
171
+
172
+ /** One DFlash 2 draft block: one row per anchor, each the anchor and `columns - 1` mask positions, over the
173
+ * projected context; the greedy proposals left on the device, [anchors, columns - 1] uint32 row-major. Every
174
+ * projection in the block runs the kernel its row count names. */
175
+ export type Dflash2DraftBlock = (context: Dflash2ContextAttention, projection: DraftProjection, anchors: readonly number[],
176
+ position: number | MlxArray, columns: number) => MlxArray;
@@ -0,0 +1,23 @@
1
+ import type { MlxArray } from "@mlx-bun/mlx/array";
2
+ import type { Cache } from "./cache";
3
+ import type { MlxLayerCapture, MlxPhaseGroup } from "./graph";
4
+
5
+ /** One forward a method hands to the mixed iteration: the phase its rows run
6
+ * in, their count and width class, the drafter's capture, and the forward
7
+ * those rows run on their own, which the iteration calls when it does not pack
8
+ * them with another group. */
9
+ export interface MlxForwardStep {
10
+ readonly phase: MlxPhaseGroup["phase"];
11
+ /** Rows: sequences times positions. */
12
+ readonly rows: number;
13
+ readonly capture: MlxLayerCapture | null;
14
+ own(): Promise<MlxArray>;
15
+ }
16
+
17
+ export type MlxForwardWork = (ids: MlxArray, cache: Cache[], step: MlxForwardStep) => Promise<MlxArray>;
18
+
19
+ export interface MlxPreparationWork {
20
+ /** Real prompt tokens across all rows, not a padded sequence width. */
21
+ readonly maxTokens?: number;
22
+ readonly forward?: MlxForwardWork;
23
+ }
@@ -0,0 +1,25 @@
1
+ import type { MlxArray } from "@mlx-bun/mlx/array";
2
+
3
+ /** Structural seam used by tiny fixtures as well as ColibriGlm52Weights. */
4
+ export interface Glm52MlaWeightSource {
5
+ tensor(name: string): MlxArray;
6
+ dequantized(name: string, outputRows: number, inputColumns: number): MlxArray;
7
+ linear(
8
+ x: MlxArray,
9
+ name: string,
10
+ outputRows: number,
11
+ inputColumns: number,
12
+ ): MlxArray;
13
+ }
14
+
15
+ export interface Glm52WeightSource extends Glm52MlaWeightSource {
16
+ readonly weightsBytes: number;
17
+ has(name: string): boolean;
18
+ embedding(
19
+ ids: MlxArray,
20
+ name: string,
21
+ vocabSize: number,
22
+ hiddenSize: number,
23
+ ): MlxArray;
24
+ dispose(): void;
25
+ }
@@ -0,0 +1,309 @@
1
+ import type { MlxHeadForward, MlxHeadRange } from "./head";
2
+ export type { MlxHeadForward, MlxHeadRange } from "./head";
3
+ import type { GraphDeclaration } from "../portable/graph";
4
+ import type { MlxArray } from "@mlx-bun/mlx/array";
5
+ import type { Cache } from "./cache";
6
+ import type { TargetView } from "./draft-target";
7
+ import type { NativeMtpHead } from "./drafter";
8
+ import type { TrainableGraph } from "./trainable";
9
+ import type { MediaEncoders, MediaSidecarProbes, MlxPromptInput, PixelInput, TextEmbeddingModel, Vision } from "./media";
10
+ import type { MlxRowTable } from "./row-table";
11
+ export type { MlxRowTable } from "./row-table";
12
+
13
+ /** Weight and expert-residency facts the wired-limit scope reads. */
14
+ export interface MlxModelMemory {
15
+ readonly weightsBytes: number;
16
+ /** The graph's composition measured that its weights are wired for a generation whatever their share of the
17
+ * recommended working set; absent: the share decides. */
18
+ readonly wiredWeights?: boolean;
19
+ readonly expertRuntime?: {
20
+ readonly plan: { readonly plannedBytes: number };
21
+ flushUsage?: () => void;
22
+ finishUsage?: () => Promise<void>;
23
+ } | null;
24
+ }
25
+
26
+ /** A verify forward's hidden-layer capture. The graph calls it once per
27
+ * decoder layer, in layer order, with that layer's residual output, then once
28
+ * with index `layerCount` (the decoder's layer count) and the post-final-norm
29
+ * output, all before the forward returns. `hidden` [sequences, tokens per
30
+ * sequence, hidden-width] is borrowed and possibly unevaluated: it is valid
31
+ * only during the call. The callback copies the layers it keeps (for example
32
+ * with `ops.contiguous`) and owns and disposes those copies. */
33
+ export type MlxLayerCapture = (layer: number, hidden: MlxArray) => void;
34
+
35
+ /** A prefill or decode forward. `ids` is integer token ids [sequences, tokens
36
+ * per sequence]. The caller owns `ids` and may dispose them once the call
37
+ * returns (or its promise settles); the result does not depend on the caller's
38
+ * handle. The graph borrows `state` and appends every position of `ids` to
39
+ * each layer's cache (keys and values, or recurrent state), advancing each
40
+ * sequence by its token count; it never rolls back. The returned post-final-norm
41
+ * hidden [sequences, tokens per sequence, hidden-width] is owned by the caller,
42
+ * who disposes it, and may be unevaluated, as may the appended cache state.
43
+ * A forward that throws may leave a partial append, which the caller discards
44
+ * or rolls back. */
45
+ export type MlxPhaseForward = (ids: MlxArray, state: Cache[]) => MlxArray | Promise<MlxArray>;
46
+
47
+ /** A forward that also hands the drafter the hidden layers it taps:
48
+ * `MlxPhaseForward`'s ownership and append, and `capture` receives each
49
+ * decoder layer's residual output and then the post-final-norm output (see
50
+ * `MlxLayerCapture`). `capture` is null when the composition's drafter reads
51
+ * none; only a graph that declares `hiddenLayerTaps` receives a non-null
52
+ * capture. Prompt chunks, prompt tails and verify windows take it. */
53
+ export type MlxCapturingForward = (ids: MlxArray, state: Cache[], capture: MlxLayerCapture | null) =>
54
+ MlxArray | Promise<MlxArray>;
55
+
56
+ /** A speculative verify forward (`MlxCapturingForward`). */
57
+ export type MlxVerifyForward = MlxCapturingForward;
58
+
59
+
60
+ /** The scoring and training forward, not a serving phase: every position of
61
+ * `ids` [sequences, tokens] as one causal window over the caller's caches (the
62
+ * stateless training caches, which own the mask of an unpadded or right-padded
63
+ * batch and the training attention kernel), on the kernels of `width`, the
64
+ * actual number of its rows. Returns the post-final-norm hidden the caller owns. */
65
+ export type MlxSequenceForward = (ids: MlxArray, state: Cache[], width: number) => MlxArray;
66
+
67
+ /** One contiguous range of positions in a single sequence's prompt piece.
68
+ * The scheduler selects the operation; the graph never inspects its shape. */
69
+ export interface MlxPromptRange {
70
+ readonly from: number;
71
+ readonly to: number;
72
+ readonly operation: MlxCapturingForward;
73
+ readonly unit?: "gpu" | "ane";
74
+ }
75
+
76
+ /** A whole accepted span uses one declared operation; callers must not split
77
+ * it to fit a verification table because that can change attention arithmetic. */
78
+ export interface MlxKnownRange { readonly from: number; readonly to: number; readonly operation: MlxPhaseForward }
79
+ export type MlxKnownOperations = MlxRowTable<MlxPhaseForward> | readonly MlxKnownRange[];
80
+
81
+ /** Operations selected by exact row count or prompt position range. */
82
+ export interface MlxTokenPhases {
83
+ readonly prompt: readonly MlxPromptRange[];
84
+ /** Optional chunk bindings when a file distinguishes chunks from prompt tails. */
85
+ readonly promptChunk?: readonly MlxPromptRange[];
86
+ readonly multiSequencePrompt: readonly MlxPromptRange[];
87
+ readonly multiSequencePromptChunk?: readonly MlxPromptRange[];
88
+ readonly decode: MlxRowTable<MlxCapturingForward>;
89
+ readonly verify: MlxRowTable<MlxVerifyForward>;
90
+ readonly appendKnown: MlxKnownOperations;
91
+ readonly logits: MlxRowTable<MlxHeadForward>;
92
+ }
93
+
94
+ /** How a graph whose composition qualifies committed known-token spans takes
95
+ * them (`MlxTokenPhases.appendKnown` over its committed read): how many
96
+ * positions one call takes. Every cache lego's committed read keeps the
97
+ * one-position arithmetic (the cache contract holds it to the same positions
98
+ * read one at a time), whatever the composition's KV scheme. A graph without
99
+ * it takes known tokens one position at a time. */
100
+ export interface MlxKnownSpans {
101
+ /** Positions one sequence's `appendKnown` call takes at the caches' current
102
+ * length. Recheck after each call: native arithmetic can change at a
103
+ * cache-length boundary. */
104
+ maxChunkSize(state: readonly Cache[]): number;
105
+ }
106
+
107
+ /** One group of a forward that serves several groups of rows at once, each in
108
+ * its own phase over its own caches. */
109
+ export interface MlxPhaseGroup {
110
+ /** `decode` (one position per sequence), `window` (a prompt piece) or
111
+ * `verify` (a speculative window, which keeps its own projection geometry). */
112
+ readonly phase: "decode" | "window" | "verify";
113
+ /** The actual number of rows in this group. */
114
+ readonly rows: number;
115
+ readonly ids: MlxArray;
116
+ readonly state: Cache[];
117
+ readonly capture: MlxLayerCapture | null;
118
+ }
119
+
120
+ /** Declared by a composition that serves mixed rows: decode, prompt and verify
121
+ * groups in one forward, each group's attention and recurrence over its own
122
+ * caches for its own phase, the row-wise layers over the groups' rows packed
123
+ * together unless a verify group keeps its geometry. `totalRows` is the full
124
+ * round's row count, including its separate verification groups. Borrows inputs and state; returns one
125
+ * owned post-final-norm hidden per group. */
126
+ export type MlxMixedForward = (groups: readonly MlxPhaseGroup[], totalRows: number) => MlxArray[];
127
+
128
+ /** A graph's compiled single-token decode step: the whole forward replayed from
129
+ * one recorded graph instead of rebuilt per token. The scheduler chooses it
130
+ * once, for a row whose caches all declare the compiled-decode capability and
131
+ * hold no batched layout; it has no fallback. */
132
+ export interface MlxCompiledDecodeStep {
133
+ /** Consume one pending uint32 [1] token (unevaluated is fine) and advance
134
+ * every cache one position. The returned logits [1,1,V] belong to the
135
+ * caller; `evalWith` holds cache updates that must ride the same async
136
+ * evaluation. A step that throws leaves `state` exactly as it was. */
137
+ step(token: MlxArray, state: Cache[]): { logits: MlxArray; evalWith: MlxArray[] };
138
+ }
139
+
140
+ /** method `denoising`: what the canvas denoiser drives over a graph's weights, with the prefill state
141
+ * an array of caches. A graph that declares the method implements these; binding refuses one that does not. */
142
+ export interface MlxDenoisingPrefillRange {
143
+ readonly from: number;
144
+ readonly to: number;
145
+ readonly operation: (promptIds: number[], pixels: MlxArray | null) => Cache[];
146
+ }
147
+
148
+ export interface MlxDenoisingDecodeRange {
149
+ readonly from: number;
150
+ readonly to: number;
151
+ readonly operation: (canvas: MlxArray, state: Cache[], feedback: MlxArray | null) => MlxArray;
152
+ }
153
+ export interface MlxDenoisingAppendRange {
154
+ readonly from: number;
155
+ readonly to: number;
156
+ readonly operation: (tokens: MlxArray, state: Cache[]) => void;
157
+ }
158
+
159
+ export interface MlxDenoisingOperations {
160
+ readonly denoisingDecode?: readonly MlxDenoisingDecodeRange[];
161
+ readonly denoisingAppend?: readonly MlxDenoisingAppendRange[];
162
+ readonly denoisingPrefill?: readonly MlxDenoisingPrefillRange[];
163
+ readonly config: { readonly text: { readonly vocabSize: number } };
164
+ readonly canvasLength: number;
165
+ readonly embedScale: number;
166
+ prefill?(promptIds: number[]): Cache[];
167
+ /** Image-conditioned prefill from channel-first pixels. */
168
+ prefillVision?(promptIds: number[], pixels: MlxArray): Cache[];
169
+ extendPrefill(tokens: MlxArray, state: Cache[]): void;
170
+ decoderLogits(canvas: MlxArray, state: Cache[], feedback: MlxArray | null): MlxArray;
171
+ dequantEmbedWeight(): MlxArray;
172
+ softEmbeddings(logits: MlxArray, weight: MlxArray): MlxArray;
173
+ }
174
+
175
+ /** The adaptive draft gate's constants for one drafter on one machine
176
+ * (`MlxDeclaredGraph.adaptiveDraftGates`); each absent one keeps the gate's
177
+ * default (`AdaptiveDraftGateOptions`). */
178
+ export interface AdaptiveDraftGateSettings {
179
+ /** Accepted and rejected counts every draft position starts from: their ratio
180
+ * is the acceptance the gate assumes before it observes the text, their sum
181
+ * how many rounds of evidence that assumption weighs. */
182
+ readonly priorAccepted?: number;
183
+ readonly priorRejected?: number;
184
+ /** The factor a position's counts keep per round that observes it, and every
185
+ * count per round without drafts. */
186
+ readonly decay?: number;
187
+ readonly idleDecay?: number;
188
+ /** How much a round's expected rate must exceed a step without drafts. */
189
+ readonly margin?: number;
190
+ /** Rounds without drafts before a probe, doubling after each probe that
191
+ * leaves the gate drafting nothing, up to `maxProbeInterval`. */
192
+ readonly probeInterval?: number;
193
+ readonly maxProbeInterval?: number;
194
+ /** The depth of a probe a drafter proposes without a verify round. */
195
+ readonly probeDepth?: number;
196
+ }
197
+
198
+ /** The graph's operations and construction facts. Pooled embedding support is
199
+ * declared by its operation alone. Other operations accompany the promises in
200
+ * `graphCapabilities`; composition checks their pairing when it binds
201
+ * (`declaredGraph`). */
202
+ export interface MlxDeclaredGraph {
203
+ readonly graphCapabilities: GraphDeclaration;
204
+ /** Release what the graph built at construction (computed constants, Neural
205
+ * Engine programs, its own weight source where it opened one) once every
206
+ * execution and compiled runner has stopped. A graph that built nothing
207
+ * releases nothing. Its owner (the host, a draft provider) calls it before
208
+ * releasing the weights it supplied. */
209
+ dispose(): void;
210
+ /** Unscaled token embeddings, for media prompts that splice embeddings. */
211
+ readonly embed?: TextEmbeddingModel["embed"];
212
+ /** media `embeddings`/`embeddings+positions`: bind one request's prepared
213
+ * embeddings into an input whose prefill is indivisible. */
214
+ bindMediaInput?(input: Vision): MlxPromptInput;
215
+ /** Presence declares pooled embeddings; there is no separate support flag.
216
+ * The pooled, L2-normalized sentence vector of one sequence,
217
+ * ids [1, L] to [1, hidden]. The caller appends the pooling token the
218
+ * profile declares and owns the result. */
219
+ embedPooled?(ids: MlxArray): MlxArray;
220
+ /** media: the lazy encoders this graph loads from the checkpoint at `modelDir`. */
221
+ mediaEncoders?(modelDir: string, probes: MediaSidecarProbes): Promise<MediaEncoders>;
222
+ /** media `pixels`: the pixel input a denoising method consumes; null when the checkpoint has none. */
223
+ pixelInput?(): PixelInput | null;
224
+ /** Ports over this graph's live caches that draft sources may consume. */
225
+ draftTarget?(caches: Cache[]): TargetView;
226
+ /** `nativeDraft`: the checkpoint's own multi-token-prediction head, refused when its tier is not loaded. */
227
+ nativeDraftHead?(): NativeMtpHead;
228
+
229
+ /** What the trainer consumes: the head, segmented backward, prefix sharing,
230
+ * gradient checkpointing, flash-attention constraint and denoising objective
231
+ * this graph implements. Undeclared parts make the trainer refuse. */
232
+ readonly trainable?: TrainableGraph;
233
+ /** `compiledDecode`: the graph's compiled decode step, created on first use
234
+ * and owned by the graph until `releaseCompiledDecode`. */
235
+ compiledDecodeStep?(): MlxCompiledDecodeStep;
236
+ /** Retire the compiled step before the graph unloads: its recorded graph
237
+ * borrows the graph's weights and constants. Safe to call when none exists. */
238
+ releaseCompiledDecode?(): void;
239
+ /** Snapshot of the streamed expert residency, for diagnostics; null when the graph streams none. */
240
+ expertResidency?(): Record<string, unknown> | null;
241
+ /** Measured cost of a verify forward by its row count, relative to one
242
+ * single-row decode step (rows 1 = 1). Declared only by a graph measured on
243
+ * the hardware it serves; speculative depth scheduling reads it. */
244
+ readonly verifyRoundCosts?: ReadonlyMap<number, number>;
245
+ /** The widest adaptive round per draft provider kind, measured on the hardware
246
+ * it serves: an adaptive drafter of a listed kind drafts up to it instead of
247
+ * its own width, unless the request names a width. Absent, or a kind it does
248
+ * not list: the drafter's own width. */
249
+ readonly adaptiveDraftWidths?: ReadonlyMap<string, number>;
250
+ /** The adaptive draft gate's settings per draft provider kind, measured on the
251
+ * hardware it serves (an adaptive drafter of a listed kind gates with them).
252
+ * Absent, or a kind it does not list: the gate's defaults. */
253
+ readonly adaptiveDraftGates?: ReadonlyMap<string, AdaptiveDraftGateSettings>;
254
+ /** Committed known-token spans, declared when the composition qualifies them
255
+ * (`appendKnown` then reads committed). */
256
+ readonly knownSpans?: MlxKnownSpans;
257
+ /** Mixed rows in one forward, declared by a composition that serves them. */
258
+ readonly mixed?: readonly MlxMixedRange[];
259
+ /** Mixed groups that retain their own projection geometry. The scheduler
260
+ * routes each group independently when a verify group is present. */
261
+ readonly mixedSeparate?: MlxSeparateMixed;
262
+ /** Full-sequence scoring operations, indexed by total token rows. */
263
+ readonly sequence?: readonly MlxSequenceRange[];
264
+ readonly sequenceLogits?: readonly MlxHeadRange[];
265
+ /** Prepared embeddings without explicit positions, indexed by total rows. */
266
+ readonly embeddingPrompt?: readonly import("./media").MlxEmbeddingsRange[];
267
+ }
268
+
269
+ /** Cache layout written by the graph, independent of request storage policy. */
270
+ export type MlxCacheLayer =
271
+ | { readonly kind: "full"; readonly turboQuant: "dense" | "deferred"; readonly kv4Head256?: boolean; readonly kv4DecodeBlock?: number; readonly windowRead?: "folded" }
272
+ | { readonly kind: "sliding"; readonly window: number }
273
+ | { readonly kind: "recurrent" }
274
+ | { readonly kind: "latent"; readonly geometry: {
275
+ readonly kvLoraRank: number; readonly ropeHeadDim: number; readonly maxTokens?: number; readonly indexHeadDim?: number;
276
+ } };
277
+
278
+ /** Fixed mixed operation for a contiguous range of packed token rows. */
279
+ export interface MlxMixedRange {
280
+ readonly from: number;
281
+ readonly to: number;
282
+ /** Optional bounds on all round rows, including independently routed verify groups. */
283
+ readonly totalFrom?: number;
284
+ readonly totalTo?: number;
285
+ readonly operation: MlxMixedForward;
286
+ }
287
+
288
+
289
+ /** A full-sequence forward fixed for a contiguous range of token rows. */
290
+ export interface MlxSequenceRange {
291
+ readonly from: number;
292
+ readonly to: number;
293
+ readonly operation: (ids: MlxArray, state: Cache[]) => MlxArray;
294
+ }
295
+
296
+ /** One mixed group using its own fixed projection geometry. */
297
+ export interface MlxMixedGroupRange {
298
+ readonly from: number;
299
+ readonly to: number;
300
+ readonly operation: (group: MlxPhaseGroup) => MlxArray;
301
+ }
302
+
303
+ export interface MlxSeparateMixed {
304
+ /** Optional packing of multiple nonverify groups alongside separately routed verification. */
305
+ readonly packed?: readonly MlxMixedRange[];
306
+ readonly decode: readonly MlxMixedGroupRange[];
307
+ readonly window: readonly MlxMixedGroupRange[];
308
+ readonly verify: readonly MlxMixedGroupRange[];
309
+ }
@@ -0,0 +1,6 @@
1
+ import type { MlxArray } from "@mlx-bun/mlx/array";
2
+
3
+ /** The output head over a post-final-norm hidden [.., hidden-width] (borrowed)
4
+ * to logits [.., vocabulary] the caller owns, possibly unevaluated. */
5
+ export type MlxHeadForward = (hidden: MlxArray) => MlxArray;
6
+ export interface MlxHeadRange { readonly from: number; readonly to: number; readonly operation: MlxHeadForward }
@@ -0,0 +1,15 @@
1
+ export * from "./attention";
2
+ export * from "./cache";
3
+ export * from "./checkpoint";
4
+ export * from "./draft-checkpoint";
5
+ export * from "./draft-projection";
6
+ export * from "./draft-target";
7
+ export * from "./drafter";
8
+ export * from "./forward-work";
9
+ export * from "./glm52-weights";
10
+ export * from "./graph";
11
+ export * from "./kv-codec";
12
+ export * from "./media";
13
+ export * from "./positions";
14
+ export * from "./trainable";
15
+ export * from "./whisper";
@@ -0,0 +1,9 @@
1
+ import type { MlxArray } from "@mlx-bun/mlx/array";
2
+
3
+ /** A backend KV representation independent of row storage and scheduling.
4
+ * Inputs are borrowed. Encoding and decoding return caller-owned arrays.
5
+ * A codec may retain values in a rotated domain for attention to invert once. */
6
+ export interface KvCodec<Encoded> {
7
+ encode(keys: MlxArray, values: MlxArray): Encoded;
8
+ decode(encoded: Encoded, length: number, headDim: number, deferValues?: boolean): [MlxArray, MlxArray];
9
+ }