@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,520 @@
1
+ // SigLIP-style vision tower — port of optiq's vlm/gemma4 SigLIP encoder
2
+ // (vision.py / frontend.py / merge.py, vendored from mlx-vlm, BSD-3).
3
+ //
4
+ // Lights up image input for the gemma4 family that ships a *full* vision
5
+ // encoder (e2b/e4b/26B-A4B/31B), as opposed to the 12B gemma4_unified
6
+ // "encoder-free" patch embedder in ./embedder.ts. The two share the same
7
+ // merge contract: `features()` returns language-space soft tokens
8
+ // [1, soft, textHidden] pre-divided by embed_scale (the language model
9
+ // re-multiplies), so both drop into ./prompt.ts unchanged.
10
+ //
11
+ // Pipeline (per image, batch 1):
12
+ // pixels → aspect-preserving resize (shared with ./preprocess.ts) →
13
+ // 16×16 patchify + 2*(x-0.5) → input_proj (+ 2D pos embedding) →
14
+ // 16× transformer blocks (clippable linears, q/k/v RMSNorm, 2D RoPE,
15
+ // fused SDPA scale=1.0, GeGLU MLP) → 3×3 avg-pool over the patch grid
16
+ // (×√hidden) → MultimodalEmbedder (RMSNormNoScale → Linear) → /embed_scale.
17
+ //
18
+ // Patch vectors, positions and the pooling matrix are precomputed host-side;
19
+ // the 2D-RoPE cos/sin tables are built on-device (op-for-op with optiq, so
20
+ // they're bit-identical). Single images run UNPADDED (no attention mask):
21
+ // every patch attends to every patch bidirectionally, which is numerically
22
+ // identical to optiq's padded+(-1e4)-masked path (masked keys underflow to
23
+ // exactly 0 in the softmax) but far cheaper than always running 2520²
24
+ // attention — verified: padded and unpadded give the same features to 4
25
+ // decimals.
26
+ //
27
+ // Parity: this matches optiq's computation op-for-op, INCLUDING its choices of
28
+ // decomposed (manual f32) RMS norm for the q/k/v attention norms vs the fused
29
+ // fast.rms_norm for the block layernorms. EVERY primitive is bit-identical to
30
+ // the oracle on this machine — verified model-free in
31
+ // `02d723a:scripts/oracle/op-parity-dump.py` + `02d723a:scripts/op-parity-check.ts`:
32
+ // rms_norm, gelu, matmul, clip, cos, sin, the full
33
+ // multidimensional RoPE, sdpa (no-mask AND array-mask), sdpa padded-vs-unpadded
34
+ // (a no-op), and the 3×3 pool (f32 matmul == optiq's einsum). There is NO
35
+ // kernel / "cross-build" divergence (an earlier claim of one was a bug in the
36
+ // op-test harness: toFloat32 mis-read a non-contiguous SDPA output — force
37
+ // ops.contiguous() before raw readback).
38
+ //
39
+ // Pre-transformer features are bit-exact (0.003%) and ONE encoder layer on
40
+ // bit-exact input is bit-exact (0.0007%). The full 16-layer features land at
41
+ // ~1.0-1.2% rel-RMSE vs optiq: a sub-bf16 (≈0.0007%/layer) composition
42
+ // difference that ACCUMULATES and is amplified by this encoder's design —
43
+ // scale=1.0 on RMS-normed q/k makes q·k ~N(0, head_dim) and the softmax
44
+ // sharply peaked, so tiny rounding flips attention weights. ~0.17% of it is the
45
+ // patchify input (JS `pixel/127.5-1` vs optiq's two-step f32 `2*(pixel/255 -
46
+ // 0.5)`); the rest is encoder bf16 non-associativity. It flips a downstream
47
+ // greedy argmax after a few tokens, so the test asserts exact spliced ids + a
48
+ // greedy prefix + grounded output (the tier-a bar), not full bit-exact greedy.
49
+ //
50
+ // TODO(revisit): full bit-exact vision IS achievable and is the bar for the
51
+ // rest of this codebase (0.0000% across the text models) — the technique is to
52
+ // match optiq's EXACT op / lazy-eval / fusion ordering in the full graph, which
53
+ // you can read straight from optiq/vlm/gemma4/{vision,merge}.py. Every PRIMITIVE
54
+ // already matches bit-for-bit (op-parity-*); the residual is purely full-graph
55
+ // composition order. Left at tier-a for now (good enough — grounded, exact ids,
56
+ // greedy prefix); revisit to drive the encoder to 0% by aligning the op order.
57
+
58
+ import { tensorFingerprint } from "../../artifacts/fingerprint";
59
+ import { ptr, read } from "bun:ffi";
60
+ import { MlxArray, cpuStream } from "@mlx-bun/mlx/array";
61
+ import { C, Dtype } from "@mlx-bun/mlx/ffi";
62
+ import * as ops from "@mlx-bun/mlx/ops";
63
+ import { decodeImage, resizeBicubic, targetSize } from "../../input/vision/preprocess";
64
+ import { applyRope2d, rope2dTables, type Rope2dTables } from "../../layers/rope-2d";
65
+
66
+ const cstr = (s: string) => Buffer.from(s + "\0", "utf8");
67
+ const dispose = (old: MlxArray, next: MlxArray): MlxArray => {
68
+ old.dispose();
69
+ return next;
70
+ };
71
+
72
+ export interface SiglipVisionConfig {
73
+ hiddenSize: number;
74
+ intermediateSize: number;
75
+ numLayers: number;
76
+ numHeads: number;
77
+ numKvHeads: number;
78
+ headDim: number;
79
+ ropeTheta: number;
80
+ rmsNormEps: number;
81
+ patchSize: number;
82
+ poolingKernelSize: number;
83
+ defaultOutputLength: number;
84
+ positionEmbeddingSize: number;
85
+ standardize: boolean;
86
+ useClippedLinears: boolean;
87
+ }
88
+
89
+ /** Parse a config.json `vision_config` block (gemma4_vision). */
90
+ export function parseSiglipConfig(raw: Record<string, any>): SiglipVisionConfig {
91
+ return {
92
+ hiddenSize: raw.hidden_size ?? 768,
93
+ intermediateSize: raw.intermediate_size ?? 3072,
94
+ numLayers: raw.num_hidden_layers ?? 16,
95
+ numHeads: raw.num_attention_heads ?? 12,
96
+ numKvHeads: raw.num_key_value_heads ?? raw.num_attention_heads ?? 12,
97
+ headDim: raw.head_dim ?? 64,
98
+ ropeTheta: raw.rope_parameters?.rope_theta ?? 100.0,
99
+ rmsNormEps: raw.rms_norm_eps ?? 1e-6,
100
+ patchSize: raw.patch_size ?? 16,
101
+ poolingKernelSize: raw.pooling_kernel_size ?? 3,
102
+ defaultOutputLength: raw.default_output_length ?? 280,
103
+ positionEmbeddingSize: raw.position_embedding_size ?? 10240,
104
+ standardize: raw.standardize ?? false,
105
+ useClippedLinears: raw.use_clipped_linears ?? false,
106
+ };
107
+ }
108
+
109
+ export interface SiglipPreprocessed {
110
+ /** [numReal, patchDim] f32 patch vectors, normalized 2*(x/255 - 0.5). */
111
+ patches: Float32Array;
112
+ /** [numReal] x grid position (column) of each patch, f32 — also the RoPE
113
+ * position for the first spatial dim. */
114
+ posX: Float32Array;
115
+ /** [numReal] y grid position (row) of each patch, f32 — RoPE second dim. */
116
+ posY: Float32Array;
117
+ /** [numReal] x grid position as int32, for the position-embedding gather. */
118
+ pxIdx: Int32Array;
119
+ /** [numReal] y grid position as int32, for the position-embedding gather. */
120
+ pyIdx: Int32Array;
121
+ /** [softTokens, numReal] 3×3 avg-pool weights (1/9 in-block, else 0). */
122
+ poolWeights: Float32Array;
123
+ /** Real (unpadded) 16×16 patch count = pH·pW. */
124
+ numReal: number;
125
+ /** Pooled soft-token count = (pH/3)·(pW/3). */
126
+ softTokens: number;
127
+ }
128
+
129
+ /** bytes → resized RGB → SigLIP patch vectors + host-precomputed positions,
130
+ * RoPE tables and pooling matrix. */
131
+ export async function preprocessSiglip(
132
+ bytes: Uint8Array, cfg: SiglipVisionConfig,
133
+ ): Promise<SiglipPreprocessed> {
134
+ let img = await decodeImage(bytes);
135
+ const t = targetSize(img.width, img.height);
136
+ if (t.width !== img.width || t.height !== img.height)
137
+ img = resizeBicubic(img, t.width, t.height);
138
+
139
+ const { width, height, data } = img;
140
+ const p = cfg.patchSize; // 16
141
+ const pH = Math.floor(height / p);
142
+ const pW = Math.floor(width / p);
143
+ const numReal = pH * pW;
144
+ if (numReal === 0) throw new Error("image smaller than one patch");
145
+ const k = cfg.poolingKernelSize; // 3
146
+ const maxPatches = cfg.defaultOutputLength * k * k;
147
+ if (numReal > maxPatches)
148
+ throw new Error(`image yields ${numReal} patches > budget ${maxPatches}`);
149
+ const softW = Math.floor(pW / k);
150
+ const softH = Math.floor(pH / k);
151
+ const softTokens = softW * softH;
152
+
153
+ const patchDim = 3 * p * p; // 768
154
+
155
+ const patches = new Float32Array(numReal * patchDim);
156
+ const posX = new Float32Array(numReal);
157
+ const posY = new Float32Array(numReal);
158
+ const pxIdx = new Int32Array(numReal);
159
+ const pyIdx = new Int32Array(numReal);
160
+ const poolWeights = new Float32Array(softTokens * numReal);
161
+ const invK2 = 1 / (k * k);
162
+
163
+ for (let py = 0; py < pH; py++) {
164
+ for (let px = 0; px < pW; px++) {
165
+ const L = py * pW + px;
166
+ pxIdx[L] = px;
167
+ pyIdx[L] = py;
168
+ posX[L] = px;
169
+ posY[L] = py;
170
+
171
+ // patch vector: [p_h, p_w, C] flattened (matches optiq's reshape/
172
+ // transpose), value 2*(pixel/255 - 0.5) = pixel/127.5 - 1.
173
+ const base = L * patchDim;
174
+ for (let dy = 0; dy < p; dy++) {
175
+ for (let dx = 0; dx < p; dx++) {
176
+ const src = ((py * p + dy) * width + px * p + dx) * 3;
177
+ const dst = base + (dy * p + dx) * 3;
178
+ patches[dst] = data[src]! / 127.5 - 1;
179
+ patches[dst + 1] = data[src + 1]! / 127.5 - 1;
180
+ patches[dst + 2] = data[src + 2]! / 127.5 - 1;
181
+ }
182
+ }
183
+
184
+ // pooling block index: px//k + (pW//k)*(py//k) (optiq kernel_idxs)
185
+ const block = Math.floor(px / k) + softW * Math.floor(py / k);
186
+ poolWeights[block * numReal + L] = invK2;
187
+ }
188
+ }
189
+
190
+ return { patches, posX, posY, pxIdx, pyIdx, poolWeights, numReal, softTokens };
191
+ }
192
+
193
+ export class SiglipVisionTower {
194
+ #weights = new Map<string, MlxArray>();
195
+ #cacheIdentity?: string;
196
+ /** Immutable encoder weights and computation settings, hashed once on use. */
197
+ get cacheIdentity(): string {
198
+ return this.#cacheIdentity ??= new Bun.CryptoHasher("sha256")
199
+ .update("gemma-siglip-v1").update(JSON.stringify([this.cfg, this.embedScale]))
200
+ .update(tensorFingerprint(this.#weights)).digest("hex");
201
+ }
202
+ readonly cfg: SiglipVisionConfig;
203
+ readonly embedScale: number;
204
+ #wdtype: Dtype = Dtype.bfloat16;
205
+
206
+ private constructor(cfg: SiglipVisionConfig, embedScale: number) {
207
+ this.cfg = cfg;
208
+ this.embedScale = embedScale;
209
+ }
210
+
211
+ /** Load the `vision_tower.*` + `embed_vision.*` tensors from the bf16
212
+ * sidecar. `embedScale` = the language model's embed_scale
213
+ * (= sqrt(textHidden)); features come out pre-divided by it. */
214
+ static load(
215
+ modelDir: string, cfg: SiglipVisionConfig, embedScale: number,
216
+ ): SiglipVisionTower {
217
+ const self = new SiglipVisionTower(cfg, embedScale);
218
+ // out-param slots read via read.u64, not [0] (DFG stale-read bug — see
219
+ // outArray in packages/mlx/src/ffi.ts).
220
+ const arrMap = new BigUint64Array([C.mlx_map_string_to_array_new()]);
221
+ const metaMap = new BigUint64Array([C.mlx_map_string_to_string_new()]);
222
+ const arrMapPtr = ptr(arrMap);
223
+ const metaMapPtr = ptr(metaMap);
224
+ const status = C.mlx_load_safetensors(
225
+ arrMapPtr, metaMapPtr,
226
+ ptr(cstr(`${modelDir}/optiq_vision.safetensors`)), cpuStream,
227
+ );
228
+ C.mlx_map_string_to_string_free(read.u64(metaMapPtr, 0));
229
+ if (status !== 0) throw new Error(`failed to load vision sidecar from ${modelDir}`);
230
+ const arrMapHandle = read.u64(arrMapPtr, 0);
231
+
232
+ const get = (name: string): MlxArray => {
233
+ const slot = new BigUint64Array([C.mlx_array_new()]);
234
+ const slotPtr = ptr(slot);
235
+ if (C.mlx_map_string_to_array_get(slotPtr, arrMapHandle, ptr(cstr(name))) !== 0)
236
+ throw new Error(`vision sidecar missing tensor ${name}`);
237
+ return new MlxArray(read.u64(slotPtr, 0));
238
+ };
239
+
240
+ const clipSuffixes = ["input_min", "input_max", "output_min", "output_max"];
241
+ const addLinear = (prefix: string) => {
242
+ self.#weights.set(`${prefix}.linear.weight`, get(`${prefix}.linear.weight`));
243
+ if (cfg.useClippedLinears)
244
+ for (const s of clipSuffixes)
245
+ self.#weights.set(`${prefix}.${s}`, get(`${prefix}.${s}`));
246
+ };
247
+
248
+ for (let i = 0; i < cfg.numLayers; i++) {
249
+ const p = `vision_tower.encoder.layers.${i}`;
250
+ for (const ln of [
251
+ "input_layernorm", "post_attention_layernorm",
252
+ "pre_feedforward_layernorm", "post_feedforward_layernorm",
253
+ ])
254
+ self.#weights.set(`${p}.${ln}.weight`, get(`${p}.${ln}.weight`));
255
+ self.#weights.set(`${p}.self_attn.q_norm.weight`, get(`${p}.self_attn.q_norm.weight`));
256
+ self.#weights.set(`${p}.self_attn.k_norm.weight`, get(`${p}.self_attn.k_norm.weight`));
257
+ for (const proj of ["q_proj", "k_proj", "v_proj", "o_proj"])
258
+ addLinear(`${p}.self_attn.${proj}`);
259
+ for (const proj of ["gate_proj", "up_proj", "down_proj"])
260
+ addLinear(`${p}.mlp.${proj}`);
261
+ }
262
+ self.#weights.set(
263
+ "vision_tower.patch_embedder.input_proj.weight",
264
+ get("vision_tower.patch_embedder.input_proj.weight"),
265
+ );
266
+ self.#weights.set(
267
+ "vision_tower.patch_embedder.position_embedding_table",
268
+ get("vision_tower.patch_embedder.position_embedding_table"),
269
+ );
270
+ self.#weights.set(
271
+ "embed_vision.embedding_projection.weight",
272
+ get("embed_vision.embedding_projection.weight"),
273
+ );
274
+
275
+ C.mlx_map_string_to_array_free(arrMapHandle);
276
+ self.#wdtype = self.#w("embed_vision.embedding_projection.weight").dtype;
277
+ return self;
278
+ }
279
+
280
+ async preprocess(bytes: Uint8Array): Promise<SiglipPreprocessed> {
281
+ return preprocessSiglip(bytes, this.cfg);
282
+ }
283
+
284
+ #w(name: string): MlxArray {
285
+ return this.#weights.get(name)!;
286
+ }
287
+
288
+ /** nn.Linear: x @ W.T (no bias). Casts x to the weight dtype first. */
289
+ #linear(x: MlxArray, weightName: string): MlxArray {
290
+ const w = this.#w(weightName);
291
+ const xc = x.astype(w.dtype);
292
+ const wT = ops.transposeAxes(w, [1, 0]);
293
+ const out = ops.matmul(xc, wT);
294
+ xc.dispose();
295
+ wT.dispose();
296
+ return out;
297
+ }
298
+
299
+ /** ClippableLinear: clip(x) → x @ W.T → clip(out). No bias. */
300
+ #clipLinear(x: MlxArray, prefix: string): MlxArray {
301
+ let xc: MlxArray = x;
302
+ let clippedIn = false;
303
+ if (this.cfg.useClippedLinears) {
304
+ xc = ops.clip(x, this.#w(`${prefix}.input_min`), this.#w(`${prefix}.input_max`));
305
+ clippedIn = true;
306
+ }
307
+ let out = this.#linear(xc, `${prefix}.linear.weight`);
308
+ if (clippedIn) xc.dispose();
309
+ if (this.cfg.useClippedLinears)
310
+ out = dispose(out, ops.clip(out, this.#w(`${prefix}.output_min`), this.#w(`${prefix}.output_max`)));
311
+ return out;
312
+ }
313
+
314
+ /** optiq's VisionRMSNorm / VisionRMSNormNoScale: a MANUAL float32 RMS norm
315
+ * (NOT the fused fast.rms_norm kernel). The q/k/v attention norms must use
316
+ * the same decomposed op sequence as optiq to stay bit-exact — the fused
317
+ * kernel diverges ~1 ULP per call, which compounds over 16 layers × 3
318
+ * norms. (The block layernorms DO use fast.rms_norm in both, so those keep
319
+ * ops.rmsNorm.) */
320
+ #visionRmsNorm(x: MlxArray, weight: MlxArray | null, eps: number): MlxArray {
321
+ const last = x.shape.length - 1;
322
+ const xf = x.astype(Dtype.float32);
323
+ const sq = ops.square(xf);
324
+ const varr = ops.meanAxis(sq, last, true);
325
+ sq.dispose();
326
+ const epsA = ops.scalarLike(eps, varr);
327
+ const vare = ops.add(varr, epsA);
328
+ varr.dispose();
329
+ epsA.dispose();
330
+ const r = ops.rsqrt(vare);
331
+ vare.dispose();
332
+ let normed = ops.mul(xf, r);
333
+ xf.dispose();
334
+ r.dispose();
335
+ if (weight) {
336
+ const wf = weight.astype(Dtype.float32);
337
+ normed = dispose(normed, ops.mul(normed, wf));
338
+ wf.dispose();
339
+ }
340
+ const out = normed.astype(x.dtype);
341
+ normed.dispose();
342
+ return out;
343
+ }
344
+
345
+ /** The 2D-RoPE tables for this image's patch grid (x, then y per patch). */
346
+ #ropeTables(pre: SiglipPreprocessed): Rope2dTables {
347
+ const grid = new Float32Array(pre.numReal * 2);
348
+ for (let i = 0; i < pre.numReal; i++) {
349
+ grid[i * 2] = pre.posX[i]!;
350
+ grid[i * 2 + 1] = pre.posY[i]!;
351
+ }
352
+ const positions = MlxArray.fromFloat32(grid, [1, pre.numReal, 2]);
353
+ try { return rope2dTables(positions, this.cfg.headDim, this.cfg.ropeTheta, this.#wdtype); }
354
+ finally { positions.dispose(); }
355
+ }
356
+
357
+ /** Self-attention. x: [1, L, hidden]. Single image, unpadded → full
358
+ * bidirectional attention (no mask). Consumes nothing, returns new. */
359
+ #attention(x: MlxArray, rope: Rope2dTables, prefix: string): MlxArray {
360
+ const L = x.shape[1]!;
361
+ const { numHeads, numKvHeads, headDim, rmsNormEps } = this.cfg;
362
+
363
+ const proj = (name: string, heads: number, norm: string | null): MlxArray => {
364
+ let t = this.#clipLinear(x, `${prefix}.${name}`);
365
+ t = dispose(t, ops.reshape(t, [1, L, heads, headDim]));
366
+ t = dispose(t, this.#visionRmsNorm(t, norm ? this.#w(`${prefix}.${norm}`) : null, rmsNormEps));
367
+ return t;
368
+ };
369
+ let q = proj("q_proj", numHeads, "q_norm.weight");
370
+ let k = proj("k_proj", numKvHeads, "k_norm.weight");
371
+ let v = proj("v_proj", numKvHeads, null); // VisionRMSNormNoScale
372
+
373
+ q = dispose(q, applyRope2d(q, rope));
374
+ k = dispose(k, applyRope2d(k, rope));
375
+
376
+ // [1, L, H, D] → [1, H, L, D]
377
+ const qT = ops.transposeAxes(q, [0, 2, 1, 3]);
378
+ const kT = ops.transposeAxes(k, [0, 2, 1, 3]);
379
+ const vT = ops.transposeAxes(v, [0, 2, 1, 3]);
380
+ q.dispose();
381
+ k.dispose();
382
+ v.dispose();
383
+
384
+ // scale=1.0 (the trained convention for this encoder) — note this makes
385
+ // the softmax very peaked (q/k are RMS-normed, so q·k has std ~sqrt(D)),
386
+ // which AMPLIFIES the small bf16 difference between mlx-bun's fast SDPA
387
+ // (ops.sdpa) and the reference into occasional argmax flips. That, not a
388
+ // port bug, is the bulk of the ~1.2% feature divergence (see header).
389
+ // ops.sdpa is the closest path (manual softmax(qkᵀ)v is ~2% — worse).
390
+ // Full bidirectional attention, no mask: numerically identical to optiq's
391
+ // padded+(-1e4)-masked path (masked keys underflow to 0) but cheaper.
392
+ let o = ops.sdpa(qT, kT, vT, 1.0, "", null);
393
+ qT.dispose();
394
+ kT.dispose();
395
+ vT.dispose();
396
+
397
+ o = dispose(o, ops.transposeAxes(o, [0, 2, 1, 3]));
398
+ o = dispose(o, ops.reshape(o, [1, L, numHeads * headDim]));
399
+ const out = this.#clipLinear(o, `${prefix}.o_proj`);
400
+ o.dispose();
401
+ return out;
402
+ }
403
+
404
+ /** GeGLU MLP (uncompiled: the reference vision MLP is plain `nn.gelu_approx(gate) * up`). x: [1, L, hidden]. */
405
+ #mlp(x: MlxArray, prefix: string): MlxArray {
406
+ let g = this.#clipLinear(x, `${prefix}.gate_proj`);
407
+ g = dispose(g, ops.geluApprox(g));
408
+ const u = this.#clipLinear(x, `${prefix}.up_proj`);
409
+ const prod = ops.mul(g, u);
410
+ g.dispose();
411
+ u.dispose();
412
+ const out = this.#clipLinear(prod, `${prefix}.down_proj`);
413
+ prod.dispose();
414
+ return out;
415
+ }
416
+
417
+ /** One transformer block. Returns a new hidden; caller disposes the input. */
418
+ #block(h: MlxArray, rope: Rope2dTables, i: number): MlxArray {
419
+ const eps = this.cfg.rmsNormEps;
420
+ const p = `vision_tower.encoder.layers.${i}`;
421
+
422
+ const normed = ops.rmsNorm(h, this.#w(`${p}.input_layernorm.weight`), eps);
423
+ let attn = this.#attention(normed, rope, `${p}.self_attn`);
424
+ normed.dispose();
425
+ attn = dispose(attn, ops.rmsNorm(attn, this.#w(`${p}.post_attention_layernorm.weight`), eps));
426
+ const h1 = ops.add(h, attn);
427
+ attn.dispose();
428
+
429
+ const normed2 = ops.rmsNorm(h1, this.#w(`${p}.pre_feedforward_layernorm.weight`), eps);
430
+ let ff = this.#mlp(normed2, `${p}.mlp`);
431
+ normed2.dispose();
432
+ ff = dispose(ff, ops.rmsNorm(ff, this.#w(`${p}.post_feedforward_layernorm.weight`), eps));
433
+ const h2 = ops.add(h1, ff);
434
+ h1.dispose();
435
+ ff.dispose();
436
+ return h2;
437
+ }
438
+
439
+ /** One preprocessed image → language-space soft tokens
440
+ * [1, softTokens, textHidden], pre-divided by embed_scale. */
441
+ features(pre: SiglipPreprocessed): MlxArray {
442
+ const { hiddenSize, positionEmbeddingSize, rmsNormEps } = this.cfg;
443
+ const { numReal, softTokens } = pre;
444
+ const patchDim = 3 * this.cfg.patchSize * this.cfg.patchSize;
445
+ const bf = this.#wdtype;
446
+
447
+ // --- patch embedding ---
448
+ const patchArr = MlxArray.fromFloat32(pre.patches, [1, numReal, patchDim]);
449
+ let h = this.#linear(patchArr, "vision_tower.patch_embedder.input_proj.weight");
450
+ patchArr.dispose();
451
+
452
+ // + 2D position embedding: table[0, px] + table[1, py]
453
+ const table = this.#w("vision_tower.patch_embedder.position_embedding_table");
454
+ const slicePlane = (i: number): MlxArray => {
455
+ const s = table.slice([i, 0, 0], [i + 1, positionEmbeddingSize, hiddenSize]);
456
+ const r = ops.reshape(s, [positionEmbeddingSize, hiddenSize]);
457
+ s.dispose();
458
+ return r;
459
+ };
460
+ const t0r = slicePlane(0);
461
+ const t1r = slicePlane(1);
462
+ const pxArr = MlxArray.fromInt32(pre.pxIdx, [numReal]);
463
+ const pyArr = MlxArray.fromInt32(pre.pyIdx, [numReal]);
464
+ const e0 = ops.takeAxis(t0r, pxArr, 0);
465
+ const e1 = ops.takeAxis(t1r, pyArr, 0);
466
+ t0r.dispose();
467
+ t1r.dispose();
468
+ pxArr.dispose();
469
+ pyArr.dispose();
470
+ let pos = ops.add(e0, e1);
471
+ e0.dispose();
472
+ e1.dispose();
473
+ pos = dispose(pos, ops.reshape(pos, [1, numReal, hiddenSize]));
474
+ h = dispose(h, ops.add(h, pos));
475
+ pos.dispose();
476
+
477
+ // --- transformer (device-built RoPE tables, full bidirectional attn) ---
478
+ const rope = this.#ropeTables(pre);
479
+ for (let i = 0; i < this.cfg.numLayers; i++) {
480
+ const next = this.#block(h, rope, i);
481
+ h.dispose();
482
+ h = next;
483
+ }
484
+ rope.dispose();
485
+
486
+ // --- 3×3 avg-pool over the patch grid (×√hidden) ---
487
+ // optiq computes the pool in f32 then casts back to bf16; match that.
488
+ const hf = h.astype(Dtype.float32);
489
+ h.dispose();
490
+ const h2 = ops.reshape(hf, [numReal, hiddenSize]);
491
+ hf.dispose();
492
+ const poolW = MlxArray.fromFloat32(pre.poolWeights, [softTokens, numReal]);
493
+ let pooled = ops.matmul(poolW, h2); // [soft, hidden] f32
494
+ poolW.dispose();
495
+ h2.dispose();
496
+ pooled = dispose(pooled, pooled.astype(bf));
497
+ pooled = dispose(pooled, ops.mulScalar(pooled, Math.sqrt(hiddenSize)));
498
+ pooled = dispose(pooled, ops.reshape(pooled, [1, softTokens, hiddenSize]));
499
+ // standardize (e2b/e4b: off) intentionally unsupported until a model needs it.
500
+ if (this.cfg.standardize)
501
+ throw new Error("SigLIP standardize=true not yet supported");
502
+
503
+ // --- MultimodalEmbedder: RMSNormNoScale → Linear(no bias) ---
504
+ pooled = dispose(pooled, ops.rmsNorm(pooled, null, rmsNormEps));
505
+ let feats = this.#linear(pooled, "embed_vision.embedding_projection.weight");
506
+ pooled.dispose();
507
+
508
+ // pre-divide by embed_scale (language model re-multiplies)
509
+ const scale = ops.scalarLike(this.embedScale, feats);
510
+ const out = ops.div(feats, scale);
511
+ feats.dispose();
512
+ scale.dispose();
513
+ return out; // [1, softTokens, textHidden]
514
+ }
515
+
516
+ dispose(): void {
517
+ for (const w of this.#weights.values()) w.dispose();
518
+ this.#weights.clear();
519
+ }
520
+ }
@@ -0,0 +1,176 @@
1
+ // Vision feature pipeline — port of optiq's gemma4_unified VisionEmbedder
2
+ // + MultimodalEmbedder (vendored from mlx-vlm, BSD-3).
3
+ //
4
+ // Encoder-free: patches [n, 6912] → LayerNorm → Linear(+bias) → LayerNorm
5
+ // → + 2D pos embedding → LayerNorm → RMSNormNoScale → Linear(no bias)
6
+ // → divide by embed_scale (the language model re-multiplies it).
7
+ //
8
+ // Sidecar weights stay bf16; features come out bf16 like text embeddings.
9
+
10
+ import { tensorFingerprint } from "../../artifacts/fingerprint";
11
+ import { ptr, read } from "bun:ffi";
12
+ import { MlxArray, cpuStream } from "@mlx-bun/mlx/array";
13
+ import { C } from "@mlx-bun/mlx/ffi";
14
+ import * as ops from "@mlx-bun/mlx/ops";
15
+ import type { PreprocessedImage } from "../../input/vision/preprocess";
16
+ import { NUM_SOFT_TOKENS, preprocessImage } from "../../input/vision/preprocess";
17
+
18
+ const cstr = (s: string) => Buffer.from(s + "\0", "utf8");
19
+
20
+ export class VisionTower {
21
+ #weights = new Map<string, MlxArray>();
22
+ #cacheIdentity?: string;
23
+ /** Immutable encoder weights and computation settings, hashed once on use. */
24
+ get cacheIdentity(): string {
25
+ return this.#cacheIdentity ??= new Bun.CryptoHasher("sha256")
26
+ .update("gemma-vision-v1").update(JSON.stringify([this.embedScale, this.rmsNormEps]))
27
+ .update(tensorFingerprint(this.#weights)).digest("hex");
28
+ }
29
+ readonly embedScale: number;
30
+ readonly rmsNormEps: number;
31
+
32
+ private constructor(embedScale: number, rmsNormEps: number) {
33
+ this.embedScale = embedScale;
34
+ this.rmsNormEps = rmsNormEps;
35
+ }
36
+
37
+ static load(modelDir: string, embedScale: number, rmsNormEps = 1e-6): VisionTower {
38
+ const self = new VisionTower(embedScale, rmsNormEps);
39
+ // out-param slots read back via read.u64, not [0] (DFG stale-read bug
40
+ // — see outArray in packages/mlx/src/ffi.ts).
41
+ const arrMap = new BigUint64Array([C.mlx_map_string_to_array_new()]);
42
+ const metaMap = new BigUint64Array([C.mlx_map_string_to_string_new()]);
43
+ const arrMapPtr = ptr(arrMap);
44
+ const metaMapPtr = ptr(metaMap);
45
+ const status = C.mlx_load_safetensors(
46
+ arrMapPtr, metaMapPtr, ptr(cstr(`${modelDir}/optiq_vision.safetensors`)), cpuStream,
47
+ );
48
+ C.mlx_map_string_to_string_free(read.u64(metaMapPtr, 0));
49
+ if (status !== 0) throw new Error(`failed to load vision sidecar from ${modelDir}`);
50
+ const arrMapHandle = read.u64(arrMapPtr, 0);
51
+ const names = [
52
+ "vision_embedder.patch_ln1.weight", "vision_embedder.patch_ln1.bias",
53
+ "vision_embedder.patch_dense.weight", "vision_embedder.patch_dense.bias",
54
+ "vision_embedder.patch_ln2.weight", "vision_embedder.patch_ln2.bias",
55
+ "vision_embedder.pos_embedding",
56
+ "vision_embedder.pos_norm.weight", "vision_embedder.pos_norm.bias",
57
+ "embed_vision.embedding_projection.weight",
58
+ ];
59
+ for (const name of names) {
60
+ const slot = new BigUint64Array([C.mlx_array_new()]);
61
+ const slotPtr = ptr(slot);
62
+ if (C.mlx_map_string_to_array_get(slotPtr, arrMapHandle, ptr(cstr(name))) !== 0)
63
+ throw new Error(`vision sidecar missing tensor ${name}`);
64
+ self.#weights.set(name, new MlxArray(read.u64(slotPtr, 0)));
65
+ }
66
+ C.mlx_map_string_to_array_free(arrMapHandle);
67
+ return self;
68
+ }
69
+
70
+ async preprocess(bytes: Uint8Array): Promise<PreprocessedImage> {
71
+ return preprocessImage(bytes);
72
+ }
73
+
74
+ #w(name: string): MlxArray {
75
+ return this.#weights.get(name)!;
76
+ }
77
+
78
+ /** nn.Linear: x @ W.T (+ bias). */
79
+ #linear(x: MlxArray, weight: MlxArray, bias: MlxArray | null): MlxArray {
80
+ const wT = ops.transposeAxes(weight, [1, 0]);
81
+ let out = ops.matmul(x, wT);
82
+ wT.dispose();
83
+ if (bias) {
84
+ const withBias = ops.add(out, bias);
85
+ out.dispose();
86
+ out = withBias;
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /** One image's preprocessed patches → language-space features
92
+ * [softTokens, hidden] (pre-divided by embed_scale). */
93
+ features(img: PreprocessedImage): MlxArray {
94
+ const eps = this.rmsNormEps;
95
+ const patchDim = img.patches.length / NUM_SOFT_TOKENS;
96
+ let h: MlxArray = MlxArray.fromFloat32(img.patches, [1, NUM_SOFT_TOKENS, patchDim]);
97
+
98
+ h = disposing(h, ops.layerNorm(h,
99
+ this.#w("vision_embedder.patch_ln1.weight"),
100
+ this.#w("vision_embedder.patch_ln1.bias"), eps));
101
+ h = disposing(h, this.#linear(h,
102
+ this.#w("vision_embedder.patch_dense.weight"),
103
+ this.#w("vision_embedder.patch_dense.bias")));
104
+ h = disposing(h, ops.layerNorm(h,
105
+ this.#w("vision_embedder.patch_ln2.weight"),
106
+ this.#w("vision_embedder.patch_ln2.bias"), eps));
107
+
108
+ // + 2D position embedding: posemb[clamped[:,0], 0] + posemb[clamped[:,1], 1]
109
+ // (clamp + validity mask precomputed host-side; padding rows get -1)
110
+ const n = NUM_SOFT_TOKENS;
111
+ const xIdx = new Int32Array(n);
112
+ const yIdx = new Int32Array(n);
113
+ const valid = new Float32Array(2 * n);
114
+ for (let i = 0; i < n; i++) {
115
+ const px = img.positions[i * 2]!;
116
+ const py = img.positions[i * 2 + 1]!;
117
+ xIdx[i] = Math.max(px, 0);
118
+ yIdx[i] = Math.max(py, 0);
119
+ valid[i] = px === -1 ? 0 : 1;
120
+ valid[n + i] = py === -1 ? 0 : 1;
121
+ }
122
+ const posemb = this.#w("vision_embedder.pos_embedding"); // [1120, 2, 3840]
123
+ const addPos = (idx: Int32Array, dim: number, validOff: number): MlxArray => {
124
+ const idxArr = MlxArray.fromInt32(idx, [n]);
125
+ const rows = ops.takeAxis(posemb, idxArr, 0); // [n, 2, 3840]
126
+ idxArr.dispose();
127
+ const sel = rows.slice([0, dim, 0], [n, dim + 1, 3840]);
128
+ rows.dispose();
129
+ const flat = ops.reshape(sel, [1, n, 3840]);
130
+ sel.dispose();
131
+ const v = MlxArray.fromFloat32(valid.subarray(validOff, validOff + n).slice(), [1, n, 1]);
132
+ const vCast = v.astype(flat.dtype);
133
+ v.dispose();
134
+ const masked = ops.mul(flat, vCast);
135
+ flat.dispose();
136
+ vCast.dispose();
137
+ return masked;
138
+ };
139
+ const xPos = addPos(xIdx, 0, 0);
140
+ const yPos = addPos(yIdx, 1, n);
141
+ const posSum = ops.add(xPos, yPos);
142
+ xPos.dispose();
143
+ yPos.dispose();
144
+ h = disposing(h, ops.add(h, posSum));
145
+ posSum.dispose();
146
+
147
+ h = disposing(h, ops.layerNorm(h,
148
+ this.#w("vision_embedder.pos_norm.weight"),
149
+ this.#w("vision_embedder.pos_norm.bias"), eps));
150
+
151
+ // MultimodalEmbedder: RMSNormNoScale → Linear(no bias)
152
+ h = disposing(h, ops.rmsNorm(h, null, eps));
153
+ h = disposing(h, this.#linear(h,
154
+ this.#w("embed_vision.embedding_projection.weight"), null));
155
+
156
+ // keep only real (unpadded) soft tokens; pre-divide by embed_scale
157
+ const hidden = h.shape[2]!;
158
+ const real = h.slice([0, 0, 0], [1, img.softTokens, hidden]);
159
+ h.dispose();
160
+ const scale = ops.scalarLike(this.embedScale, real);
161
+ const out = ops.div(real, scale);
162
+ real.dispose();
163
+ scale.dispose();
164
+ return out; // [1, softTokens, hidden]
165
+ }
166
+
167
+ dispose(): void {
168
+ for (const w of this.#weights.values()) w.dispose();
169
+ this.#weights.clear();
170
+ }
171
+ }
172
+
173
+ function disposing(old: MlxArray, next: MlxArray): MlxArray {
174
+ old.dispose();
175
+ return next;
176
+ }