mlx-bun 0.3.0 → 0.5.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 (231) hide show
  1. package/README.md +57 -32
  2. package/docs/README.md +58 -42
  3. package/docs/archive/investigations/benchmark-ledger-through-v0.4.0.md +3617 -0
  4. package/docs/archive/investigations/openjarvis-fit.md +198 -0
  5. package/docs/archive/investigations/qwen38-27b-campaign-log.md +1092 -0
  6. package/docs/archive/planning/release-notes-v0.4.0.md +45 -0
  7. package/docs/archive/planning/release-notes-v0.5.0.md +37 -0
  8. package/docs/design/batching.md +1535 -50
  9. package/docs/design/decode-speed-program.md +394 -1171
  10. package/docs/design/generic-model-support.md +195 -3
  11. package/docs/design/kv-cache.md +538 -225
  12. package/docs/design/speculative-decoding.md +552 -50
  13. package/docs/design/turboquant.md +140 -17
  14. package/docs/design/unified-engine-frontier-plan.md +259 -150
  15. package/docs/planning/PRODUCT_ROADMAP.md +21 -6
  16. package/docs/planning/public-readiness-handoff.md +244 -0
  17. package/docs/planning/public-readiness.md +149 -0
  18. package/docs/reference/benchmarks.md +3537 -1112
  19. package/docs/reference/cli.md +102 -2
  20. package/docs/reference/distribution.md +45 -13
  21. package/docs/reference/environment.md +159 -13
  22. package/docs/reference/library-api.md +18 -4
  23. package/docs/reference/memory.md +1 -1
  24. package/docs/reference/models.md +28 -7
  25. package/docs/reference/server-api.md +257 -33
  26. package/docs/reference/server-config.md +372 -151
  27. package/docs/reference/troubleshooting.md +13 -21
  28. package/package.json +2 -2
  29. package/src/audio/audiotoolbox.ts +112 -0
  30. package/src/audio/conformer.ts +8 -0
  31. package/src/audio/mic-capture.ts +98 -0
  32. package/src/audio/silero-vad.ts +379 -0
  33. package/src/audio/whisper-decode.ts +774 -0
  34. package/src/audio/whisper-fast.ts +732 -0
  35. package/src/audio/whisper-format.ts +73 -0
  36. package/src/audio/whisper-mel.ts +185 -0
  37. package/src/audio/whisper-timing.ts +274 -0
  38. package/src/audio/whisper-tokenizer.ts +239 -0
  39. package/src/audio/whisper-transcribe.ts +410 -0
  40. package/src/backends/mlx/assistant-target.ts +46 -0
  41. package/src/backends/mlx/autoregressive-draft-rows.ts +120 -0
  42. package/src/backends/mlx/autoregressive.ts +22 -1
  43. package/src/backends/mlx/batch-group.ts +464 -236
  44. package/src/backends/mlx/cache-attachment.ts +67 -0
  45. package/src/backends/mlx/cache-layout.ts +31 -0
  46. package/src/backends/mlx/checkpoint-state.ts +53 -0
  47. package/src/backends/mlx/continuation-persistence.ts +107 -0
  48. package/src/backends/mlx/continuation-request.ts +43 -0
  49. package/src/backends/mlx/continuation.ts +77 -0
  50. package/src/backends/mlx/draft-target.ts +7 -22
  51. package/src/backends/mlx/encoder-cache.ts +25 -0
  52. package/src/backends/mlx/fill-append.ts +21 -8
  53. package/src/backends/mlx/fill-group.ts +497 -0
  54. package/src/backends/mlx/full-kv-row-append.ts +32 -0
  55. package/src/backends/mlx/full-kv-row-donor.ts +54 -0
  56. package/src/backends/mlx/full-transitioning-kv-rows.ts +65 -0
  57. package/src/backends/mlx/gateway-binding.ts +122 -19
  58. package/src/backends/mlx/kv-codec.ts +9 -0
  59. package/src/backends/mlx/kv-maintenance.ts +161 -0
  60. package/src/backends/mlx/kv-tensor-rows.ts +212 -0
  61. package/src/backends/mlx/mixed-iteration.ts +62 -0
  62. package/src/backends/mlx/model-prompt.ts +46 -32
  63. package/src/backends/mlx/model-serving.ts +5 -4
  64. package/src/backends/mlx/paged-cache-codec.ts +27 -0
  65. package/src/backends/mlx/prefill-cohort.ts +100 -0
  66. package/src/backends/mlx/prefill-policy.ts +26 -0
  67. package/src/backends/mlx/prefill-rows.ts +244 -0
  68. package/src/backends/mlx/prefill.ts +1 -1
  69. package/src/backends/mlx/projected-context-rows.ts +72 -0
  70. package/src/backends/mlx/prompt-input.ts +29 -0
  71. package/src/backends/mlx/qwen-prompt-input.ts +40 -0
  72. package/src/backends/mlx/request-state-policy.ts +54 -0
  73. package/src/backends/mlx/rollback.ts +45 -4
  74. package/src/backends/mlx/row-sampling.ts +49 -0
  75. package/src/backends/mlx/serial-executor.ts +51 -73
  76. package/src/backends/mlx/speculative-group.ts +438 -0
  77. package/src/backends/mlx/speculative-round.ts +161 -0
  78. package/src/backends/mlx/speculative.ts +24 -7
  79. package/src/backends/mlx/state-rows.ts +104 -0
  80. package/src/backends/mlx/state-views.ts +21 -1
  81. package/src/backends/mlx/target-layout-capability.ts +35 -0
  82. package/src/backends/mlx/transitioning-kv-rows.ts +173 -0
  83. package/src/cli.ts +333 -36
  84. package/src/contracts/execution.ts +21 -0
  85. package/src/contracts/object-cache.ts +8 -0
  86. package/src/contracts/pi-provider.ts +1 -1
  87. package/src/contracts/pi.ts +3 -1
  88. package/src/contracts/prefix-cache.ts +33 -0
  89. package/src/contracts/resources.ts +7 -0
  90. package/src/contracts/sampling.ts +23 -0
  91. package/src/contracts/scheduling.ts +27 -0
  92. package/src/engine/execution-plan.ts +38 -25
  93. package/src/engine/execution-tasks.ts +44 -0
  94. package/src/engine/namespaced-cache.ts +13 -0
  95. package/src/engine/resources.ts +12 -1
  96. package/src/engine/scheduler.ts +32 -7
  97. package/src/fill/fill-session.ts +14 -3
  98. package/src/fit.ts +29 -15
  99. package/src/generate.ts +105 -195
  100. package/src/grammar.ts +13 -0
  101. package/src/inference/draft-acceptance.ts +41 -0
  102. package/src/inference/draft-output.ts +49 -0
  103. package/src/inference/prefill.ts +6 -0
  104. package/src/inference/rollback.ts +2 -2
  105. package/src/kv-scheme.ts +92 -12
  106. package/src/kv-store.ts +183 -93
  107. package/src/lab/README.md +5 -1
  108. package/src/lab/paged-kv/paged-attention.ts +117 -0
  109. package/src/lab/paged-kv/paged-kv-rows.ts +111 -0
  110. package/src/lab/paged-kv/paged-kv.ts +126 -46
  111. package/src/md-modules.d.ts +5 -0
  112. package/src/mlx/array.ts +39 -1
  113. package/src/mlx/ffi.ts +19 -0
  114. package/src/mlx/normalized-argmax.ts +116 -0
  115. package/src/mlx/ops.ts +97 -10
  116. package/src/model/artifact-identity.ts +73 -0
  117. package/src/model/batched-kv.ts +235 -0
  118. package/src/model/batched-mask.ts +12 -4
  119. package/src/model/batched-quant.ts +8 -2
  120. package/src/model/batched-quantized-kv.ts +144 -0
  121. package/src/model/batched-rotating-quant.ts +76 -15
  122. package/src/model/batched-rotating-state.ts +76 -0
  123. package/src/model/batched-rotating.ts +64 -22
  124. package/src/model/batched-row-storage.ts +52 -0
  125. package/src/model/batched-ssm.ts +52 -0
  126. package/src/model/batched-turboquant-kv.ts +94 -0
  127. package/src/model/compiled-decode.ts +7 -1
  128. package/src/model/decoded-kv-donor.ts +12 -0
  129. package/src/model/delayed-quantized-kv.ts +72 -0
  130. package/src/model/delayed-rotating-quantized-kv.ts +93 -0
  131. package/src/model/delayed-turboquant-kv.ts +57 -0
  132. package/src/model/factory.ts +26 -0
  133. package/src/model/fingerprint.ts +12 -0
  134. package/src/model/full-prefill-padding.ts +56 -0
  135. package/src/model/full-prefill-row.ts +105 -0
  136. package/src/model/gemma4-base.ts +183 -82
  137. package/src/model/gemma4.ts +116 -28
  138. package/src/model/generated/gemma4-12b.ts +4 -1
  139. package/src/model/generated/gemma4-26b.ts +4 -1
  140. package/src/model/generated/gemma4-e4b.ts +4 -1
  141. package/src/model/glm52-cache.ts +80 -4
  142. package/src/model/glm52-mla.ts +12 -6
  143. package/src/model/glm52.ts +19 -40
  144. package/src/model/kv-attention-view.ts +70 -0
  145. package/src/model/minicpm5.ts +11 -7
  146. package/src/model/profile.ts +29 -4
  147. package/src/model/quantized-append-attention.ts +31 -0
  148. package/src/model/qwen3-delta-state.ts +74 -0
  149. package/src/model/qwen3-delta.ts +59 -36
  150. package/src/model/qwen3-mrope.ts +7 -9
  151. package/src/model/qwen3_5.ts +177 -75
  152. package/src/model/rotating-kv-donor.ts +35 -0
  153. package/src/model/rotating-kv-layout.ts +262 -0
  154. package/src/model/rotating-row-transaction.ts +35 -0
  155. package/src/model/speculative-rotating-kv.ts +101 -0
  156. package/src/model/ssm-prefill-padding.ts +39 -0
  157. package/src/model/support.ts +8 -0
  158. package/src/model/token-groups.ts +66 -0
  159. package/src/model/trellis-linear.ts +4 -4
  160. package/src/model/turboquant-codec.ts +89 -0
  161. package/src/model/universal/dense.ts +14 -13
  162. package/src/model/whisper.ts +435 -0
  163. package/src/native/mic_capture.swift +92 -0
  164. package/src/native-pack.ts +6 -5
  165. package/src/pi-web.ts +9 -1
  166. package/src/preflight.ts +31 -15
  167. package/src/prompt-cache.ts +306 -86
  168. package/src/runtime-config.ts +1 -5
  169. package/src/safetensors.ts +9 -2
  170. package/src/sampler.ts +37 -25
  171. package/src/serve/audio-routes.ts +323 -0
  172. package/src/serve/chat-request.ts +2 -0
  173. package/src/serve/chat-stage.ts +19 -14
  174. package/src/serve/completion-executor.ts +9 -1
  175. package/src/serve/discovery-routes.ts +17 -1
  176. package/src/serve/generated-token-history.ts +57 -0
  177. package/src/serve/generation-gateway.ts +88 -38
  178. package/src/serve/model-binding.ts +7 -1
  179. package/src/serve/model-host.ts +3 -4
  180. package/src/serve/preparation.ts +3 -3
  181. package/src/serve/prompt-response-trace.ts +14 -0
  182. package/src/serve/request-plan.ts +6 -3
  183. package/src/serve/request-prep.ts +40 -25
  184. package/src/serve/text-completion-stage.ts +2 -2
  185. package/src/serve/transcription-server.ts +64 -0
  186. package/src/serve/transcription-service.ts +502 -0
  187. package/src/server.ts +185 -261
  188. package/src/spec/assistant-rows.ts +93 -0
  189. package/src/spec/assistant-source.ts +28 -18
  190. package/src/spec/cache-identity.ts +22 -0
  191. package/src/spec/deepspec-rows.ts +29 -0
  192. package/src/spec/deepspec-source.ts +12 -10
  193. package/src/spec/dflash-source.ts +28 -4
  194. package/src/spec/drafter.ts +153 -142
  195. package/src/spec/dspark/deepspec-module.ts +95 -120
  196. package/src/spec/dspark/module-dflash.ts +126 -170
  197. package/src/spec/glm52-mtp-graph.ts +29 -0
  198. package/src/spec/glm52-mtp-rows.ts +132 -0
  199. package/src/spec/glm52-mtp-source.ts +54 -136
  200. package/src/spec/glm52-mtp-state.ts +33 -0
  201. package/src/spec/ngram-source.ts +115 -21
  202. package/src/spec/projected-draft-rows.ts +73 -0
  203. package/src/spec/qwen-mtp-module.ts +171 -0
  204. package/src/spec/qwen-mtp-rows.ts +230 -0
  205. package/src/spec/qwen-mtp-source.ts +84 -226
  206. package/src/spec/qwen-mtp-state.ts +30 -0
  207. package/src/spec/serve-loop.ts +73 -69
  208. package/src/spec/source.ts +93 -15
  209. package/src/spec/two-model-rows.ts +62 -0
  210. package/src/spec/two-model.ts +45 -103
  211. package/src/ssd-cache.ts +107 -36
  212. package/src/ssd-durability.ts +29 -27
  213. package/src/storage/host-buffer.ts +24 -0
  214. package/src/storage/kv-writer.ts +83 -0
  215. package/src/storage/kv-writer.worker.js +264 -0
  216. package/src/storage/retention-policy.ts +37 -0
  217. package/src/tiered-prompt-cache.ts +45 -0
  218. package/src/vision/embedder.ts +8 -0
  219. package/src/vision/prompt.ts +101 -65
  220. package/src/vision/qwen3vl-prompt.ts +101 -64
  221. package/src/vision/qwen3vl-tower.ts +11 -0
  222. package/src/vision/siglip.ts +8 -0
  223. package/src/web/app.html +12 -0
  224. package/src/web/app.js +217 -57
  225. package/src/web/src/chat.ts +4 -1
  226. package/src/web/src/composer.ts +3 -0
  227. package/src/web/src/voice.ts +141 -0
  228. package/src/web/sw.js +1 -1
  229. package/src/backends/mlx/memory-guard.ts +0 -40
  230. package/src/spec/prefix-state.ts +0 -45
  231. /package/docs/{planning → archive/planning}/release-notes-v0.3.0.md +0 -0
@@ -1,3 +1,8 @@
1
+ import { speculativePrefixNamespace, captureSpeculativeOptions } from "../../spec/cache-identity";
2
+ import { createOrdinaryContinuationRequest } from "./continuation-request";
3
+ import type { MlxSerialServices } from "./serial-executor";
4
+ import { bindPagedRequestState, pagedPrefixNamespace, type MlxRequestStatePolicy } from "./request-state-policy";
5
+ import type { ExecutionContext } from "../../contracts/scheduling";
1
6
  import type { ModelConfig } from "../../config";
2
7
  import type { KvScheme } from "../../kv-scheme";
3
8
  import type { RuntimeModel } from "../../model/factory";
@@ -5,67 +10,165 @@ import { DiffusionGemmaModel } from "../../model/diffusion-gemma";
5
10
  import { UniversalDenseModel } from "../../model/universal/dense";
6
11
  import { KVCache, RotatingKVCache, isBatchableCache, isPlainKvCache, isRotatingPlainCache } from "../../model/gemma4-base";
7
12
  import { SSMCache } from "../../model/qwen3-delta";
13
+ import { Gemma4Model } from "../../model/gemma4";
8
14
  import { Qwen35Model } from "../../model/qwen3_5";
9
15
  import { runtimeConfig, type RuntimeConfig } from "../../runtime-config";
10
16
  import { disposeResources } from "../../engine/resources";
11
17
  import { legacyCompiledDecodeAvailable } from "./autoregressive";
12
- import { MlxBatchExecutionGroup, type MlxBatchExecutionGroupOptions } from "./batch-group";
18
+ import { MlxBatchExecutionGroup, type MlxBatchExecutionGroupOptions, type MlxGroupMethodRequest } from "./batch-group";
19
+ import type { DraftProvider } from "../../spec/source";
20
+ import { constraintDraftProvider } from "../../spec/ngram-source";
21
+ import { targetRowLayoutFactory } from "./target-layout-capability";
22
+ import { bindSpeculativeGroupRequests } from "./speculative-group";
23
+ import { bindFillGroupRequests } from "./fill-group";
13
24
  import type { GenerateOptions } from "../../generate";
14
25
  import type { ExecutionRequirements, ResolvedExecution } from "../../contracts/execution";
15
26
  import { resolveExecution } from "../../engine/execution-plan";
27
+ import { bindEmbeddingsInput, type MlxPromptInput } from "./prompt-input";
28
+ import { bindQwenMediaInput } from "./qwen-prompt-input";
29
+ import type { Vision } from "../../serve/generation-gateway";
16
30
 
17
31
  export interface MlxBatchGroup extends Pick<MlxBatchExecutionGroup,
18
- "activeRows" | "pendingRows" | "projectedKvBytes" | "kvBudgetBytes" | "submit" | "kick" | "close"> {}
32
+ "activeRows" | "pendingRows" | "projectedKvBytes" | "kvBudgetBytes" | "submit" | "kick" | "close"> {
33
+ runPreparation?<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T>;
34
+ }
19
35
 
20
36
  /** A model implementation owns capability checks and the execution group.
21
37
  * Scheduling never inspects concrete model/cache classes. */
22
38
  export interface MlxGatewayBinding {
39
+ mediaInput?(input: Vision): MlxPromptInput;
40
+ configureContinuation?(services: MlxSerialServices): void;
41
+ continuationRequest?(execution: ResolvedExecution | undefined, options: GenerateOptions, prompt: number[],
42
+ onToken: Parameters<typeof createOrdinaryContinuationRequest>[0]["onToken"]): ReturnType<typeof createOrdinaryContinuationRequest> | undefined;
23
43
  readonly config: ModelConfig;
24
44
  readonly runtime: RuntimeConfig;
25
45
  plan(request: ExecutionRequirements, options: GenerateOptions,
26
46
  scheduling: { continuous: boolean; quantizedBatch: boolean; checkpoints: boolean }): ResolvedExecution;
47
+ bindAdapterContext?(adapters: string[], key: string): ExecutionContext;
27
48
  cachesBatchable(): boolean;
28
49
  kvBatchable(scheme: KvScheme): boolean;
50
+ statePolicy?(execution: ResolvedExecution | undefined, options: GenerateOptions, capacityTokens: number): MlxRequestStatePolicy | undefined;
51
+ prefixNamespace?(execution: ResolvedExecution | undefined, options: GenerateOptions, adapters: string): string | null;
52
+ methodRequest?(execution: ResolvedExecution | undefined, options: GenerateOptions): MlxGroupMethodRequest | undefined;
29
53
  createBatchGroup(options: MlxBatchExecutionGroupOptions): MlxBatchGroup;
30
54
  }
31
55
 
32
- export function bindMlxGateway(model: RuntimeModel): MlxGatewayBinding {
56
+ export function bindMlxGateway(model: RuntimeModel, draft?: { provider: DraftProvider; numDraftTokens: number }): MlxGatewayBinding {
33
57
  const runtime = runtimeConfig();
58
+ let continuationServices: MlxSerialServices | undefined;
59
+ const kvBatchCapabilities = { delayedAffine: model instanceof Qwen35Model || model instanceof Gemma4Model };
60
+ const cachesBatchable = () => {
61
+ if (model instanceof UniversalDenseModel)
62
+ return !model.args.maskArray && !model.args.layerTypes?.includes("sliding_attention");
63
+ const caches = model.makeCache();
64
+ try {
65
+ const ssm = runtime.value("MLX_BUN_BATCH_SSM") !== "0";
66
+ return caches.every((cache) => cache instanceof KVCache || cache instanceof RotatingKVCache ||
67
+ isBatchableCache(cache) || (ssm && cache instanceof SSMCache));
68
+ } finally { disposeResources(caches); }
69
+ };
70
+ const supportsTargetRows = () => {
71
+ const caches = model.makeCache();
72
+ try { return caches.every(cache => targetRowLayoutFactory(cache) !== undefined); }
73
+ finally { disposeResources(caches); }
74
+ };
75
+ const speculative = draft?.provider.grouped && cachesBatchable() && supportsTargetRows()
76
+ ? bindSpeculativeGroupRequests(model, draft.provider, draft.numDraftTokens) : undefined;
77
+ const grammarProvider = runtime.flag("MLX_BUN_GRAMMAR_JUMP", false) && cachesBatchable() && supportsTargetRows()
78
+ ? constraintDraftProvider() : undefined;
79
+ const grammarProposals = grammarProvider ? bindSpeculativeGroupRequests(model, grammarProvider,
80
+ Math.max(1, Math.trunc(runtime.number("MLX_BUN_GRAMMAR_DRAFT_TOKENS", 3)))) : undefined;
81
+ const adapterState = "loraState" in model ? model.loraState : undefined;
82
+ const fillRequests = supportsTargetRows() ? bindFillGroupRequests(model) : undefined;
83
+ const mediaInput = model instanceof Gemma4Model ? (input: Vision) =>
84
+ bindEmbeddingsInput((ids, caches, start) => start > 0 ? model.forwardHidden(ids, caches)
85
+ : model.forwardEmbeddings(input.embeddings,
86
+ caches, input.imageMask ?? null, ids, input.multimodalMask ?? null))
87
+ : model instanceof Qwen35Model ? (input: Vision) => bindQwenMediaInput(model, input.embeddings, input.mrope!)
88
+ : undefined;
34
89
  return {
90
+ mediaInput,
35
91
  config: model.config, runtime,
92
+ configureContinuation: services => { continuationServices = services; },
93
+ continuationRequest(execution, options, prompt, onToken) {
94
+ if (!execution?.checkpoint || execution.mechanism !== "continuous") return undefined;
95
+ const services = continuationServices;
96
+ if (!services?.checkpoints || !services.checkpointPersistence)
97
+ throw new Error("qualified continuation requires bound persistence services");
98
+ return createOrdinaryContinuationRequest({ options, prompt, onToken, execution,
99
+ store: services.checkpoints, persistence: services.checkpointPersistence,
100
+ restore: entry => services.checkpoints!.restore(entry, model),
101
+ interval: services.checkpointEveryTokens!, identity: services.identity });
102
+ },
103
+ statePolicy: (execution, options, capacity) => {
104
+ // Media token IDs alone do not identify the prepared embeddings.
105
+ // Preserve the existing uncached media policy through the state port.
106
+ if (execution?.method === "autoregressive" && !execution.promptCache)
107
+ return { key: "uncached-prepared-input", create: () => model.makeCache() };
108
+ return execution?.pagedKv ? bindPagedRequestState(model, options, capacity, continuationServices?.promptCache, runtime) : undefined;
109
+ },
110
+ prefixNamespace: (execution, options, adapters) => {
111
+ if (execution?.pagedKv) return pagedPrefixNamespace(options, adapters, runtime.flag("MLX_BUN_PAGED_ATTN", false));
112
+ if (execution?.method !== "speculative") return adapters;
113
+ const namespace = (execution.grammarJump ? grammarProvider : draft?.provider)?.grouped?.checkpointNamespace?.();
114
+ return namespace === undefined ? null : speculativePrefixNamespace(namespace, adapters, captureSpeculativeOptions(options));
115
+ },
116
+ methodRequest: (execution, options) => execution?.method === "speculative"
117
+ ? (execution.grammarJump ? grammarProposals : speculative)?.(
118
+ options.fill && !execution.fill ? { ...options, fill: undefined } : options)
119
+ : execution?.fill ? fillRequests?.(options) : undefined,
120
+ ...(adapterState ? { bindAdapterContext(adapters: string[], key: string): ExecutionContext {
121
+ const selected = [...adapters];
122
+ return { key, enter() {
123
+ const previous = adapterState.active;
124
+ adapterState.active = selected;
125
+ return () => { adapterState.active = previous; };
126
+ } };
127
+ } } : {}),
36
128
  plan(request, options, scheduling) {
129
+ const sharedMethod = request.hasDraft ? speculative : grammarProposals;
130
+ const provider = request.hasDraft ? draft?.provider : grammarProvider;
37
131
  return resolveExecution(request, {
38
132
  ...scheduling,
133
+ sharedCheckpoints: !!continuationServices?.checkpointPersistence &&
134
+ !request.hasDraft && !request.hasVision && !request.hasGrammar &&
135
+ !request.wantsLogprobs && !options.fill && !options.pagedKv,
136
+ adapterBatch: !!adapterState, pagedBatch: model instanceof Gemma4Model,
137
+ mediaBatch: !!mediaInput,
138
+ mediaPrefixCache: runtime.flag("MLX_BUN_MEDIA_PREFIX_CACHE", true),
139
+ groupedMethods: sharedMethod ? ["autoregressive", "speculative"] : ["autoregressive"],
140
+ sharedGrammarProposals: !!grammarProposals,
141
+ sharedFill: !!fillRequests && !!options.fill,
142
+ sharedSpeculativeEcho: !!options.fill?.plan.echo && provider?.grouped?.supportsExternalTokens === true,
143
+ speculativeLogprobs: scheduling.continuous && !!sharedMethod,
144
+ sharedSpeculativeAdapters: scheduling.continuous && !!sharedMethod && !!adapterState &&
145
+ provider?.grouped?.supportsTargetAdapters === true,
146
+ turboQuantBatch: scheduling.quantizedBatch,
147
+ speculativeTurboQuant: scheduling.continuous && !!sharedMethod && !!options.turboQuant,
39
148
  method: model instanceof DiffusionGemmaModel ? "denoising" : "autoregressive",
40
149
  compiledDecode: legacyCompiledDecodeAvailable(model),
41
150
  grammarBatch: runtime.value("MLX_BUN_GRAMMAR_BATCH") !== "0",
42
- speculativeKvQuant: model instanceof Qwen35Model && options.kvBits === 4 &&
43
- !options.kvConfig?.length && options.quantizedKvStart === 0 &&
44
- runtime.flag("MLX_BUN_QWEN_SPEC_KV4", false),
151
+ speculativeKvQuant: (!(model instanceof Qwen35Model) || runtime.flag("MLX_BUN_QWEN_SPEC_KV4", true)) && (
152
+ (scheduling.continuous && !!sharedMethod && (options.kvBits === 4 || options.kvBits === 8 || !!options.kvConfig?.length)) ||
153
+ (!options.kvConfig?.length && model instanceof Qwen35Model &&
154
+ (options.kvBits === 4 || (scheduling.continuous && !!sharedMethod && options.kvBits === 8)) &&
155
+ (options.quantizedKvStart === 0 || (scheduling.continuous && !!sharedMethod)))
156
+ ),
45
157
  }, {
46
158
  pagedKv: !!options.pagedKv, fill: !!options.fill,
47
159
  compiledDecode: runtime.flag("MLX_BUN_COMPILED_DECODE", true),
48
160
  grammarJump: runtime.flag("MLX_BUN_GRAMMAR_JUMP", false),
49
161
  });
50
162
  },
51
- cachesBatchable() {
52
- if (model instanceof UniversalDenseModel)
53
- return !model.args.maskArray && !model.args.layerTypes?.includes("sliding_attention");
54
- const caches = model.makeCache();
55
- try {
56
- const ssm = runtime.value("MLX_BUN_BATCH_SSM") !== "0";
57
- return caches.every((cache) => cache instanceof KVCache || cache instanceof RotatingKVCache ||
58
- isBatchableCache(cache) || (ssm && cache instanceof SSMCache));
59
- } finally { disposeResources(caches); }
60
- },
163
+ cachesBatchable,
61
164
  kvBatchable(scheme) {
62
- if (scheme.kind !== "affine-config") return false;
63
165
  const caches = model.makeCache();
64
166
  try {
65
167
  return scheme.batchable(model.config,
66
- (layer) => isPlainKvCache(caches[layer]) || isRotatingPlainCache(caches[layer]));
168
+ (layer) => isPlainKvCache(caches[layer]) || isRotatingPlainCache(caches[layer]), caches.length,
169
+ kvBatchCapabilities);
67
170
  } finally { disposeResources(caches); }
68
171
  },
69
- createBatchGroup: (options) => new MlxBatchExecutionGroup(model, options),
172
+ createBatchGroup: (options) => new MlxBatchExecutionGroup(model, { ...options, kvBatchCapabilities }),
70
173
  };
71
174
  }
@@ -0,0 +1,9 @@
1
+ import type { MlxArray } from "../../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
+ }
@@ -0,0 +1,161 @@
1
+ import { turboQuantFusedDecode } from "../../model/turboquant-codec";
2
+ import { runtimeConfig, withRuntimeConfig } from "../../runtime-config";
3
+ import type { KvSchemeOptions } from "../../kv-scheme";
4
+ import { KVCache, QuantizedKVCache, RotatingKVCache, RotatingQuantizedKVCache, TurboQuantKVCache, type Cache } from "../../model/gemma4-base";
5
+ import type { KvQuantSpec, TurboQuantScheme } from "../../config";
6
+ import * as ops from "../../mlx/ops";
7
+ import { clearCache } from "../../mlx/ffi";
8
+
9
+ import { DelayedRotatingQuantizedKVCache } from "../../model/delayed-rotating-quantized-kv";
10
+ import { DelayedQuantizedKVCache } from "../../model/delayed-quantized-kv";
11
+ import { DelayedTurboQuantKVCache } from "../../model/delayed-turboquant-kv";
12
+
13
+ export interface KvMaintenance {
14
+ (cache: Cache[]): void;
15
+ /** Limit committed work at a pending precision transition. */
16
+ maxAppendTokens?(cache: readonly Cache[]): number;
17
+ /** Bind state requiring row-local maintenance before shared decode. */
18
+ prepareBatch?(cache: Cache[]): void;
19
+ /** Bind all precision policies before a prefill cohort owns row boundaries. */
20
+ preparePrefill?(cache: Cache[]): void;
21
+ }
22
+
23
+ const unchanged = (_cache: Cache[]): void => {};
24
+ let warnedTurboRotating = false;
25
+
26
+ /** Port of mlx-lm maybe_quantize_kv_cache + BOTH halves of optiq serve's
27
+ * per-layer patched variant (incl. patch_rotating_to_quantized: rotating
28
+ * caches convert too — Phase 9):
29
+ * - per-layer bits/group_size selection (kvConfig overrides kvBits,
30
+ * matching optiq's --kv-config precedence; shipped kv_config.json
31
+ * files cover EVERY cache-owning layer, sliding ones included —
32
+ * verified 12B 48/48, 26B 30/30, e4b 24/24 distinct caches — so
33
+ * rotating quantization engages straight from the config; uniform
34
+ * kvBits — like optiq --kv-bits — reaches them too), and
35
+ * - STREAMING conversion (optiq streaming_kv_quant / serve.py
36
+ * patched_maybe_quantize): eval each layer's quantized triples and
37
+ * clear the buffer pool before building the next layer's conversion.
38
+ * Lazily batching every layer's toQuantized into one eval pins ALL
39
+ * layers' bf16 K/V as graph inputs alongside ALL quantized outputs —
40
+ * the exact transient optiq's fix kills (16.35 → 7.60 GB at 32k on a
41
+ * 24 GB Mac). Numerics untouched: same quantize math, only the eval
42
+ * ordering is forced (tests/parity/kv-quant.test.ts, tests/parity/rotating-kvq.test.ts). */
43
+ export function createKvMaintenance(options: Readonly<Omit<KvSchemeOptions, "kvConfig">> & {
44
+ readonly kvConfig?: readonly Readonly<KvQuantSpec>[];
45
+ }): KvMaintenance {
46
+ const { kvBits, kvConfig, turboQuant } = options;
47
+ if (turboQuant) {
48
+ const start = options.quantizedKvStart ?? 0;
49
+ const scheme = { ...turboQuant };
50
+ const runtime = runtimeConfig();
51
+ const fusedDecode = turboQuantFusedDecode(runtime);
52
+ const maintain: KvMaintenance = (cache) => withRuntimeConfig(runtime, () => maybeTurboQuantizeKv(cache, scheme, start));
53
+ if (start > 0) maintain.maxAppendTokens = (cache) => {
54
+ let remaining = Number.POSITIVE_INFINITY;
55
+ for (const c of cache) {
56
+ remaining = Math.min(remaining, c.maxAppendTokens?.() ?? Infinity);
57
+ const conversion = c.turboConversion ?? (c instanceof KVCache ? c : undefined);
58
+ if (conversion && conversion.offset < start)
59
+ remaining = Math.min(remaining, start - conversion.offset);
60
+ }
61
+ return remaining;
62
+ };
63
+ maintain.preparePrefill = (cache) => {
64
+ for (let layer = 0; layer < cache.length; layer++) {
65
+ const row = cache[layer]!;
66
+ if (row instanceof KVCache || row instanceof TurboQuantKVCache)
67
+ cache[layer] = new DelayedTurboQuantKVCache(scheme.kBits, scheme.vBits, start, maintain, row, fusedDecode);
68
+ }
69
+ };
70
+ if (start > 0) maintain.prepareBatch = maintain.preparePrefill;
71
+ return maintain;
72
+ }
73
+ if (!kvBits && !kvConfig?.length) return unchanged;
74
+ const start = options.quantizedKvStart ?? (kvConfig?.length ? 0 : 5000);
75
+ const groupSize = options.kvGroupSize ?? 64;
76
+ // Resolve layer policy once when composing execution, never per token.
77
+ const byLayer = kvConfig?.length
78
+ ? new Map(kvConfig.map((entry) => [entry.layerIdx, { ...entry }]))
79
+ : null;
80
+ const maintain: KvMaintenance = (cache) => {
81
+ for (let i = 0; i < cache.length; i++) {
82
+ const c = cache[i]!;
83
+ const conversion = c.affineConversion ?? (c instanceof KVCache || c instanceof RotatingKVCache ? c : undefined);
84
+ if (!conversion || conversion.offset < start || conversion.offset === 0) continue;
85
+ const conversionOffset = conversion.offset;
86
+ // The populated-cache boundary is part of oracle parity: quantizing an
87
+ // empty cache would also quantize the first prefill.
88
+ if (byLayer) {
89
+ const entry = byLayer.get(i);
90
+ if (!entry) continue;
91
+ cache[i] = conversion.toQuantized(entry.groupSize, entry.bits);
92
+ } else {
93
+ cache[i] = conversion.toQuantized(groupSize, kvBits!);
94
+ }
95
+ if (start > 0) cache[i]!.minimumReusableOffset = conversionOffset;
96
+ // Materialize one layer before converting the next to bound the live
97
+ // bf16 source plus quantized destination to one conversion at a time.
98
+ ops.evalAll(cache[i]!.state());
99
+ clearCache();
100
+ }
101
+ };
102
+ if (start > 0) maintain.maxAppendTokens = (cache) => {
103
+ let remaining = Number.POSITIVE_INFINITY;
104
+ for (let layer = 0; layer < cache.length; layer++) {
105
+ if (byLayer && !byLayer.has(layer)) continue;
106
+ const c = cache[layer]!;
107
+ remaining = Math.min(remaining, c.maxAppendTokens?.() ?? Infinity);
108
+ const conversion = c.affineConversion ?? (c instanceof KVCache || c instanceof RotatingKVCache ? c : undefined);
109
+ if (conversion && conversion.offset < start)
110
+ remaining = Math.min(remaining, start - conversion.offset);
111
+ }
112
+ return remaining;
113
+ };
114
+ maintain.preparePrefill = (cache) => {
115
+ for (let layer = 0; layer < cache.length; layer++) {
116
+ const row = cache[layer]!;
117
+ if (!(row instanceof KVCache || row instanceof QuantizedKVCache || row instanceof RotatingKVCache || row instanceof RotatingQuantizedKVCache)) continue;
118
+ const spec = byLayer ? byLayer.get(layer) : { bits: kvBits!, groupSize };
119
+ if (!spec) continue;
120
+ const rowMaintenance = createKvMaintenance({ kvBits: spec.bits, kvGroupSize: spec.groupSize, quantizedKvStart: start });
121
+ cache[layer] = row instanceof RotatingKVCache || row instanceof RotatingQuantizedKVCache
122
+ ? new DelayedRotatingQuantizedKVCache(row.maxSize, spec.groupSize, spec.bits, start, rowMaintenance, row)
123
+ : new DelayedQuantizedKVCache(spec.groupSize, spec.bits, start, rowMaintenance, row);
124
+ }
125
+ };
126
+ if (start > 0) maintain.prepareBatch = maintain.preparePrefill;
127
+ return maintain;
128
+ }
129
+
130
+ function maybeTurboQuantizeKv(cache: Cache[], scheme: TurboQuantScheme, start: number): void {
131
+ for (let i = 0; i < cache.length; i++) {
132
+ const c = cache[i]!;
133
+ if (c instanceof RotatingKVCache) {
134
+ if (!warnedTurboRotating) {
135
+ warnedTurboRotating = true;
136
+ console.warn(
137
+ "[turbo-quant] sliding-window (RotatingKVCache) layers stay bf16 in v1 " +
138
+ "(full-attention only) — docs/design/turboquant.md.",
139
+ );
140
+ }
141
+ continue;
142
+ }
143
+ const conversion = c.turboConversion ?? (c instanceof KVCache ? c : undefined);
144
+ if (!conversion || conversion.offset < start || conversion.offset === 0) continue;
145
+ const conversionOffset = conversion.offset;
146
+ const tq = c.turboConversion ? c.turboConversion.toTurboQuantized(scheme.kBits, scheme.vBits)
147
+ : TurboQuantKVCache.fromKVCache(c as KVCache, scheme.kBits, scheme.vBits);
148
+ if (start > 0) tq.minimumReusableOffset = conversionOffset;
149
+ cache[i] = tq;
150
+ // state() allocates fresh trimmed slice views for this cache kind
151
+ // (see evalCacheState) — dispose after materializing (throw included),
152
+ // or they leak.
153
+ const state = tq.state();
154
+ try {
155
+ ops.evalAll(state);
156
+ } finally {
157
+ for (const a of state) a.dispose();
158
+ }
159
+ clearCache();
160
+ }
161
+ }
@@ -0,0 +1,212 @@
1
+ import type { MlxArray } from "../../mlx/array";
2
+ import { Dtype } from "../../mlx/ffi";
3
+ import * as ops from "../../mlx/ops";
4
+ import { materializeCopy } from "../../mlx/materialize";
5
+ import { FullPrefillPadding } from "../../model/full-prefill-padding";
6
+ import type { Mask, PrefillPadding } from "../../model/gemma4-base";
7
+ import { cleanupFailure, disposeResources } from "../../engine/resources";
8
+
9
+ /** Borrowed tensor planes with shared token positions. Plane shapes may differ
10
+ * in head width and dtype. Every plane uses [row, head, token, field]. */
11
+ export interface KvTensorRowView {
12
+ readonly planes: readonly MlxArray[];
13
+ readonly rowOffsets: readonly number[];
14
+ readonly leftPad: readonly number[];
15
+ }
16
+
17
+ /** Position and membership operations shared by packed KV representations.
18
+ * A codec supplies tensor planes; this owner never encodes or decodes them. */
19
+ export class KvTensorRows implements KvTensorRowView {
20
+ planes: MlxArray[] = [];
21
+ rowOffsets: number[] = [];
22
+ leftPad: number[] = [];
23
+ #rope: MlxArray | undefined;
24
+ #beforeRound: number[] | undefined;
25
+ readonly #padding = new FullPrefillPadding();
26
+
27
+ restorePrefillEnds(ends: readonly number[] | undefined): void { this.#padding.restoreEnds(ends); }
28
+ preparePrefill(padding: PrefillPadding): void {
29
+ this.#padding.prepare(this, padding); this.#positionsChanged();
30
+ }
31
+ finalizePrefill(): void {
32
+ const next = this.#padding.finalize(this.planes, this);
33
+ if (next) this.#replace(next, this.rowOffsets, this.leftPad);
34
+ }
35
+
36
+ /** Snapshot logical validity without changing physical row alignment. */
37
+ captureDonorValidity(): Pick<import("../../model/gemma4-base").KvDonorRows, "offsets" | "starts" | "ends"> {
38
+ const offsets = this.rowOffsets.map((offset, row) => Math.max(0, this.#padding.validOffset(offset, row)));
39
+ return { offsets, starts: [...this.leftPad], ends: offsets.map((offset, row) => offset + this.leftPad[row]!) };
40
+ }
41
+ get offset(): number { return Math.max(0, ...this.#ends()); }
42
+ get batchSize(): number | null { return this.rowOffsets.length || null; }
43
+ #ends(): number[] { return this.rowOffsets.map((offset, row) => offset + this.leftPad[row]!); }
44
+ get ropeOffsetArr(): MlxArray | undefined {
45
+ if (this.leftPad.every(pad => pad === 0) && this.rowOffsets.every(offset => offset === this.rowOffsets[0])) return undefined;
46
+ return this.#rope ??= ops.fromInt32(this.rowOffsets, [this.rowOffsets.length]);
47
+ }
48
+ #positionsChanged(): void { this.#rope?.dispose(); this.#rope = undefined; }
49
+ bytesPerToken(): number {
50
+ return this.planes.length && this.rowOffsets.length ? this.planes.reduce((bytes, plane) => bytes + plane.nbytes, 0) /
51
+ (this.rowOffsets.length * this.planes[0]!.shape[2]!) : 0;
52
+ }
53
+ trim(count: number): void {
54
+ this.rowOffsets = this.rowOffsets.map(offset => offset - count); this.#positionsChanged();
55
+ }
56
+ specRoundBegin(): void { this.#beforeRound = [...this.rowOffsets]; }
57
+ specRoundCommit(): void { this.#beforeRound = undefined; }
58
+ specRoundRollback(keep: number | readonly number[]): void {
59
+ this.rowOffsets = this.#beforeRound!.map((offset, row) => offset + (typeof keep === "number" ? keep : keep[row]!));
60
+ this.#beforeRound = undefined; this.#positionsChanged();
61
+ }
62
+ makeMask(N: number, window: number | null): Mask {
63
+ const B = this.rowOffsets.length, ends = this.#ends(), S = this.offset + N;
64
+ if (window === null && this.leftPad.every(pad => pad === 0) && ends.every(end => end === ends[0]))
65
+ return { mode: N === 1 ? "" : "causal", arr: null };
66
+ using starts = ops.fromInt32(ends, [B, 1, 1, 1]);
67
+ using relative = ops.arange(0, N, 1, Dtype.int32);
68
+ using queries = ops.reshape(relative, [1, 1, N, 1]);
69
+ using position = ops.add(starts, queries);
70
+ using indices = ops.arange(0, S, 1, Dtype.int32);
71
+ using keys = ops.reshape(indices, [1, 1, 1, S]);
72
+ using pads = ops.fromInt32(this.leftPad, [B, 1, 1, 1]);
73
+ using causal = ops.lessEqual(keys, position);
74
+ using valid = ops.greaterEqual(keys, pads);
75
+ const mask = ops.logicalAnd(causal, valid);
76
+ if (window === null) return { mode: "array", arr: mask };
77
+ using windowSize = ops.fromInt32([window], []);
78
+ using limit = ops.add(keys, windowSize);
79
+ using within = ops.less(position, limit);
80
+ try { return { mode: "array", arr: ops.logicalAnd(mask, within) }; }
81
+ finally { mask.dispose(); }
82
+ }
83
+ #replace(planes: MlxArray[], offsets: number[], pads: number[]): void {
84
+ const previous = this.planes;
85
+ this.planes = planes; this.rowOffsets = offsets; this.leftPad = pads;
86
+ this.#positionsChanged(); disposeResources(previous);
87
+ }
88
+ append(inputs: readonly MlxArray[]): void {
89
+ const B = this.rowOffsets.length, N = inputs[0]!.shape[2]!, ends = this.#ends();
90
+ const needed = Math.max(...ends) + N, capacity = Math.ceil(needed / 256) * 256;
91
+ const common = ends.every(end => end === ends[0]);
92
+ using positions = common ? null : ops.fromInt32(ends.flatMap(end =>
93
+ Array.from({ length: N }, (_, position) => end + position)), [B, 1, N, 1]);
94
+ const next: MlxArray[] = [];
95
+ try {
96
+ for (const [index, input] of inputs.entries()) {
97
+ const old = this.planes[index];
98
+ let base: MlxArray;
99
+ if (!old) base = ops.zeros([B, input.shape[1]!, capacity, input.shape[3]!], input.dtype);
100
+ else if (old.shape[2]! >= needed) base = old;
101
+ else {
102
+ using padding = ops.zeros([B, old.shape[1]!, capacity - old.shape[2]!, old.shape[3]!], old.dtype);
103
+ base = ops.concatAxis([old, padding], 2);
104
+ }
105
+ try {
106
+ const updated = common
107
+ ? ops.sliceUpdate(base, input, [0, 0, ends[0]!, 0], [B, base.shape[1]!, ends[0]! + N, base.shape[3]!])
108
+ : ops.putAlongAxis(base, positions!, input, 2);
109
+ next.push(updated);
110
+ } finally { if (base !== old) base.dispose(); }
111
+ }
112
+ } catch (error) { return cleanupFailure(error, () => disposeResources(next)); }
113
+ this.#replace(next, this.rowOffsets.map(offset => offset + N), this.leftPad);
114
+ }
115
+ mergeRows(rows: readonly KvTensorRowView[]): void {
116
+ const next: MlxArray[] = [], held: MlxArray[] = [];
117
+ let offsets: number[], pads: number[];
118
+ try {
119
+ if (rows.length === 1) {
120
+ const row = rows[0]!;
121
+ for (const plane of row.planes) next.push(ops.copyOf(plane));
122
+ offsets = [...row.rowOffsets]; pads = [...row.leftPad];
123
+ } else {
124
+ const widths = rows.map(row => Math.max(0, ...row.rowOffsets.map((offset, i) => offset + row.leftPad[i]!)));
125
+ const width = Math.max(0, ...widths);
126
+ if (width) {
127
+ const prototype = rows.find((_, index) => widths[index]! > 0)!;
128
+ for (const [field, geometry] of prototype.planes.entries()) {
129
+ const pieces = rows.map((row, index) => {
130
+ const active = widths[index]!;
131
+ if (!active) {
132
+ const empty = ops.zeros([row.rowOffsets.length, geometry.shape[1]!, width, geometry.shape[3]!], geometry.dtype);
133
+ held.push(empty); return empty;
134
+ }
135
+ const plane = row.planes[field]!;
136
+ const view = plane.slice([0, 0, 0, 0], [row.rowOffsets.length, plane.shape[1]!, active, plane.shape[3]!]);
137
+ held.push(view);
138
+ if (active === width) return view;
139
+ using padding = ops.zeros([row.rowOffsets.length, plane.shape[1]!, width - active, plane.shape[3]!], plane.dtype);
140
+ const padded = ops.concatAxis([padding, view], 2); held.push(padded); return padded;
141
+ });
142
+ next.push(ops.concatAxis(pieces, 0));
143
+ }
144
+ }
145
+ offsets = rows.flatMap(row => [...row.rowOffsets]);
146
+ pads = rows.flatMap((row, index) => row.leftPad.map(pad => pad + width - widths[index]!));
147
+ }
148
+ } catch (error) { return cleanupFailure(error, () => disposeResources(next)); }
149
+ finally { disposeResources(held); }
150
+ this.#replace(next, offsets, pads);
151
+ }
152
+ /** Preserve caller-owned physical positions when changing representation.
153
+ * Live tensor bytes are copied; padding never participates in a codec. */
154
+ alignRows(leftPad: readonly number[]): void {
155
+ if (leftPad.every((pad, row) => pad === this.leftPad[row])) return;
156
+ const width = Math.max(0, ...this.rowOffsets.map((offset, row) => offset + leftPad[row]!));
157
+ const rows: MlxArray[][] = [], planes: MlxArray[] = [];
158
+ try {
159
+ for (let row = 0; row < this.rowOffsets.length; row++) rows.push(this.extractRow(row));
160
+ for (let field = 0; field < this.planes.length; field++) {
161
+ const parts: MlxArray[] = [];
162
+ try {
163
+ for (let row = 0; row < rows.length; row++) {
164
+ const geometry = this.planes[field]!, live = rows[row]![field];
165
+ using before = ops.zeros([1, geometry.shape[1]!, leftPad[row]!, geometry.shape[3]!], geometry.dtype);
166
+ using after = ops.zeros([1, geometry.shape[1]!, width - leftPad[row]! - this.rowOffsets[row]!, geometry.shape[3]!], geometry.dtype);
167
+ parts.push(ops.concatAxis(live ? [before, live, after] : [before, after], 2));
168
+ }
169
+ planes.push(ops.concatAxis(parts, 0));
170
+ } finally { disposeResources(parts); }
171
+ }
172
+ } catch (error) { return cleanupFailure(error, () => disposeResources(planes)); }
173
+ finally { disposeResources(rows.flat()); }
174
+ this.#replace(planes, [...this.rowOffsets], [...leftPad]);
175
+ }
176
+ filterRows(keep: readonly number[]): void {
177
+ if (!keep.length) { this.dispose(); return; }
178
+ const next: MlxArray[] = [];
179
+ using indices = this.planes.length ? ops.fromInt32([...keep], [keep.length]) : null;
180
+ const pads = keep.map(row => this.leftPad[row]!);
181
+ const sharedPadding = Math.min(...pads);
182
+ try {
183
+ for (const plane of this.planes) {
184
+ const selected = ops.takeAxis(plane, indices!, 0);
185
+ if (!sharedPadding) next.push(selected);
186
+ else {
187
+ try { next.push(selected.slice([0, 0, sharedPadding, 0], [...selected.shape])); }
188
+ finally { selected.dispose(); }
189
+ }
190
+ }
191
+ }
192
+ catch (error) { return cleanupFailure(error, () => disposeResources(next)); }
193
+ this.#replace(next, keep.map(row => this.rowOffsets[row]!), pads.map(pad => pad - sharedPadding));
194
+ this.#padding.filter(keep);
195
+ }
196
+ extractRow(row: number): MlxArray[] {
197
+ const start = this.leftPad[row]!, count = this.rowOffsets[row]!, result: MlxArray[] = [];
198
+ if (!count) return result;
199
+ try {
200
+ for (const plane of this.planes) {
201
+ using view = plane.slice([row, 0, start, 0], [row + 1, plane.shape[1]!, start + count, plane.shape[3]!]);
202
+ result.push(materializeCopy(view));
203
+ }
204
+ return result;
205
+ } catch (error) { return cleanupFailure(error, () => disposeResources(result)); }
206
+ }
207
+ dispose(): void {
208
+ const previous = this.planes;
209
+ this.planes = []; this.rowOffsets = []; this.leftPad = []; this.#beforeRound = undefined; this.#padding.clear();
210
+ this.#positionsChanged(); disposeResources(previous);
211
+ }
212
+ }
@@ -0,0 +1,62 @@
1
+ import type { MlxArray } from "../../mlx/array";
2
+ import type { Cache } from "../../model/gemma4-base";
3
+ import type { TokenGroup, TokenWorkOptions } from "../../model/token-groups";
4
+
5
+ export type MlxForwardWork = (ids: MlxArray, cache: Cache[], options?: TokenWorkOptions) => Promise<MlxArray>;
6
+ export interface MlxPreparationWork {
7
+ /** Real prompt tokens across all rows, not a padded sequence width. */
8
+ readonly maxTokens?: number;
9
+ readonly forward?: MlxForwardWork;
10
+ }
11
+
12
+ /** Join two method-owned work producers at their forward boundary. Decode
13
+ * finishes sampling/publication/retirement before preparation can join rows.
14
+ * The model owns packing; this coordinator never merges caches or samples.
15
+ * A restored/cancelled preparation need not produce a forward at all. */
16
+ export async function runMixedTokenIteration(options: {
17
+ prepare(forward: MlxForwardWork): Promise<void>;
18
+ decode(forward: MlxForwardWork): Promise<void>;
19
+ forward: MlxForwardWork;
20
+ mixed(groups: readonly TokenGroup[]): MlxArray[];
21
+ }): Promise<boolean> {
22
+ let notify!: () => void;
23
+ const offered = new Promise<void>(resolve => { notify = resolve; });
24
+ let pending: { group: TokenGroup; resolve(hidden: MlxArray): void; reject(error: unknown): void } | undefined;
25
+ let captured = false;
26
+ let preparationError: unknown;
27
+ let preparationFailed = false;
28
+ const preparing = options.prepare(async (ids, cache, policy) => {
29
+ if (captured) return options.forward(ids, cache, policy);
30
+ captured = true;
31
+ return new Promise<MlxArray>((resolve, reject) => {
32
+ pending = { group: { ids, cache, ...policy }, resolve, reject }; notify();
33
+ });
34
+ }).catch(error => { preparationFailed = true; preparationError = error; }).finally(notify);
35
+ await offered;
36
+ if (!pending) {
37
+ await preparing;
38
+ if (preparationFailed) throw preparationError;
39
+ return false;
40
+ }
41
+ const held = pending;
42
+ let preparedHidden: MlxArray | undefined;
43
+ let mixed = false;
44
+ try {
45
+ await options.decode(async (ids, cache, policy) => {
46
+ if (mixed) return options.forward(ids, cache, policy);
47
+ const outputs = options.mixed([{ ids, cache, ...policy }, held.group]);
48
+ mixed = true; preparedHidden = outputs[1]!;
49
+ return outputs[0]!;
50
+ });
51
+ // A final unread token can retire decode without another model call.
52
+ preparedHidden ??= await options.forward(held.group.ids, held.group.cache, held.group);
53
+ held.resolve(preparedHidden); preparedHidden = undefined;
54
+ await preparing;
55
+ if (preparationFailed) throw preparationError;
56
+ return true;
57
+ } catch (error) {
58
+ preparedHidden?.dispose(); held.reject(error);
59
+ await preparing;
60
+ throw error;
61
+ }
62
+ }