mlx-bun 0.3.0 → 0.4.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 (150) hide show
  1. package/docs/README.md +4 -1
  2. package/docs/archive/investigations/openjarvis-fit.md +198 -0
  3. package/docs/archive/investigations/qwen38-27b-campaign-log.md +1092 -0
  4. package/docs/design/batching.md +1321 -49
  5. package/docs/design/decode-speed-program.md +331 -1163
  6. package/docs/design/generic-model-support.md +79 -3
  7. package/docs/design/kv-cache.md +198 -54
  8. package/docs/design/speculative-decoding.md +387 -24
  9. package/docs/design/turboquant.md +123 -13
  10. package/docs/design/unified-engine-frontier-plan.md +144 -142
  11. package/docs/planning/PRODUCT_ROADMAP.md +16 -0
  12. package/docs/planning/release-notes-v0.4.0.md +45 -0
  13. package/docs/reference/benchmarks.md +2457 -6
  14. package/docs/reference/cli.md +41 -2
  15. package/docs/reference/distribution.md +16 -9
  16. package/docs/reference/environment.md +55 -5
  17. package/docs/reference/models.md +13 -4
  18. package/docs/reference/server-api.md +79 -25
  19. package/docs/reference/server-config.md +178 -84
  20. package/docs/reference/troubleshooting.md +13 -21
  21. package/package.json +1 -1
  22. package/src/backends/mlx/assistant-target.ts +46 -0
  23. package/src/backends/mlx/autoregressive-draft-rows.ts +120 -0
  24. package/src/backends/mlx/batch-group.ts +368 -224
  25. package/src/backends/mlx/cache-attachment.ts +67 -0
  26. package/src/backends/mlx/cache-layout.ts +31 -0
  27. package/src/backends/mlx/checkpoint-state.ts +53 -0
  28. package/src/backends/mlx/continuation-persistence.ts +106 -0
  29. package/src/backends/mlx/continuation-request.ts +43 -0
  30. package/src/backends/mlx/continuation.ts +77 -0
  31. package/src/backends/mlx/draft-target.ts +7 -22
  32. package/src/backends/mlx/full-kv-row-append.ts +32 -0
  33. package/src/backends/mlx/full-kv-row-donor.ts +54 -0
  34. package/src/backends/mlx/full-transitioning-kv-rows.ts +65 -0
  35. package/src/backends/mlx/gateway-binding.ts +77 -18
  36. package/src/backends/mlx/kv-codec.ts +9 -0
  37. package/src/backends/mlx/kv-maintenance.ts +133 -0
  38. package/src/backends/mlx/kv-tensor-rows.ts +212 -0
  39. package/src/backends/mlx/model-serving.ts +1 -1
  40. package/src/backends/mlx/prefill-cohort.ts +89 -0
  41. package/src/backends/mlx/prefill-rows.ts +200 -0
  42. package/src/backends/mlx/prefill.ts +1 -1
  43. package/src/backends/mlx/projected-context-rows.ts +72 -0
  44. package/src/backends/mlx/request-state-policy.ts +41 -0
  45. package/src/backends/mlx/rollback.ts +41 -3
  46. package/src/backends/mlx/row-sampling.ts +49 -0
  47. package/src/backends/mlx/serial-executor.ts +35 -66
  48. package/src/backends/mlx/speculative-group.ts +359 -0
  49. package/src/backends/mlx/speculative-round.ts +161 -0
  50. package/src/backends/mlx/state-rows.ts +104 -0
  51. package/src/backends/mlx/state-views.ts +21 -1
  52. package/src/backends/mlx/target-layout-capability.ts +35 -0
  53. package/src/backends/mlx/transitioning-kv-rows.ts +165 -0
  54. package/src/cli.ts +11 -36
  55. package/src/contracts/execution.ts +11 -0
  56. package/src/contracts/prefix-cache.ts +23 -0
  57. package/src/contracts/resources.ts +7 -0
  58. package/src/contracts/sampling.ts +23 -0
  59. package/src/contracts/scheduling.ts +18 -0
  60. package/src/engine/execution-plan.ts +18 -16
  61. package/src/engine/resources.ts +12 -1
  62. package/src/engine/scheduler.ts +10 -5
  63. package/src/fit.ts +29 -15
  64. package/src/generate.ts +77 -173
  65. package/src/inference/draft-acceptance.ts +41 -0
  66. package/src/inference/draft-output.ts +49 -0
  67. package/src/inference/rollback.ts +2 -2
  68. package/src/kv-scheme.ts +70 -12
  69. package/src/kv-store.ts +70 -16
  70. package/src/lab/paged-kv/paged-kv-rows.ts +83 -0
  71. package/src/lab/paged-kv/paged-kv.ts +25 -11
  72. package/src/mlx/array.ts +2 -1
  73. package/src/model/artifact-identity.ts +73 -0
  74. package/src/model/batched-kv.ts +235 -0
  75. package/src/model/batched-mask.ts +12 -4
  76. package/src/model/batched-quant.ts +8 -2
  77. package/src/model/batched-quantized-kv.ts +144 -0
  78. package/src/model/batched-rotating-quant.ts +76 -15
  79. package/src/model/batched-rotating-state.ts +76 -0
  80. package/src/model/batched-rotating.ts +64 -22
  81. package/src/model/batched-row-storage.ts +52 -0
  82. package/src/model/batched-ssm.ts +52 -0
  83. package/src/model/batched-turboquant-kv.ts +93 -0
  84. package/src/model/compiled-decode.ts +7 -1
  85. package/src/model/decoded-kv-donor.ts +12 -0
  86. package/src/model/delayed-quantized-kv.ts +72 -0
  87. package/src/model/delayed-rotating-quantized-kv.ts +93 -0
  88. package/src/model/delayed-turboquant-kv.ts +55 -0
  89. package/src/model/full-prefill-padding.ts +56 -0
  90. package/src/model/full-prefill-row.ts +105 -0
  91. package/src/model/gemma4-base.ts +162 -80
  92. package/src/model/gemma4.ts +34 -26
  93. package/src/model/generated/gemma4-12b.ts +4 -1
  94. package/src/model/generated/gemma4-26b.ts +4 -1
  95. package/src/model/generated/gemma4-e4b.ts +4 -1
  96. package/src/model/glm52-cache.ts +80 -4
  97. package/src/model/glm52-mla.ts +12 -6
  98. package/src/model/glm52.ts +19 -40
  99. package/src/model/kv-attention-view.ts +67 -0
  100. package/src/model/minicpm5.ts +11 -7
  101. package/src/model/qwen3-delta-state.ts +74 -0
  102. package/src/model/qwen3-delta.ts +59 -36
  103. package/src/model/qwen3_5.ts +82 -42
  104. package/src/model/rotating-kv-donor.ts +35 -0
  105. package/src/model/rotating-kv-layout.ts +262 -0
  106. package/src/model/rotating-row-transaction.ts +35 -0
  107. package/src/model/speculative-rotating-kv.ts +101 -0
  108. package/src/model/ssm-prefill-padding.ts +39 -0
  109. package/src/model/trellis-linear.ts +2 -2
  110. package/src/model/turboquant-codec.ts +83 -0
  111. package/src/model/universal/dense.ts +14 -13
  112. package/src/preflight.ts +31 -15
  113. package/src/prompt-cache.ts +42 -44
  114. package/src/sampler.ts +36 -25
  115. package/src/serve/chat-stage.ts +2 -2
  116. package/src/serve/generation-gateway.ts +39 -30
  117. package/src/serve/model-host.ts +3 -4
  118. package/src/serve/request-plan.ts +4 -3
  119. package/src/serve/request-prep.ts +2 -4
  120. package/src/serve/text-completion-stage.ts +2 -2
  121. package/src/server.ts +64 -108
  122. package/src/spec/assistant-rows.ts +92 -0
  123. package/src/spec/assistant-source.ts +28 -18
  124. package/src/spec/cache-identity.ts +22 -0
  125. package/src/spec/deepspec-rows.ts +29 -0
  126. package/src/spec/deepspec-source.ts +12 -10
  127. package/src/spec/dflash-source.ts +28 -4
  128. package/src/spec/drafter.ts +153 -142
  129. package/src/spec/dspark/deepspec-module.ts +95 -120
  130. package/src/spec/dspark/module-dflash.ts +126 -170
  131. package/src/spec/glm52-mtp-graph.ts +29 -0
  132. package/src/spec/glm52-mtp-rows.ts +132 -0
  133. package/src/spec/glm52-mtp-source.ts +53 -136
  134. package/src/spec/glm52-mtp-state.ts +33 -0
  135. package/src/spec/ngram-source.ts +92 -20
  136. package/src/spec/projected-draft-rows.ts +73 -0
  137. package/src/spec/qwen-mtp-module.ts +171 -0
  138. package/src/spec/qwen-mtp-rows.ts +219 -0
  139. package/src/spec/qwen-mtp-source.ts +81 -226
  140. package/src/spec/qwen-mtp-state.ts +30 -0
  141. package/src/spec/serve-loop.ts +70 -68
  142. package/src/spec/source.ts +80 -15
  143. package/src/spec/two-model-rows.ts +61 -0
  144. package/src/spec/two-model.ts +43 -101
  145. package/src/ssd-cache.ts +33 -21
  146. package/src/ssd-durability.ts +11 -7
  147. package/src/web/app.js +57 -57
  148. package/src/backends/mlx/memory-guard.ts +0 -40
  149. package/src/spec/prefix-state.ts +0 -45
  150. /package/docs/{planning → archive/planning}/release-notes-v0.3.0.md +0 -0
@@ -1,3 +1,7 @@
1
+ import { createOrdinaryContinuationRequest } from "./continuation-request";
2
+ import type { MlxSerialServices } from "./serial-executor";
3
+ import { bindPagedRequestState, type MlxRequestStatePolicy } from "./request-state-policy";
4
+ import type { ExecutionContext } from "../../contracts/scheduling";
1
5
  import type { ModelConfig } from "../../config";
2
6
  import type { KvScheme } from "../../kv-scheme";
3
7
  import type { RuntimeModel } from "../../model/factory";
@@ -5,11 +9,15 @@ import { DiffusionGemmaModel } from "../../model/diffusion-gemma";
5
9
  import { UniversalDenseModel } from "../../model/universal/dense";
6
10
  import { KVCache, RotatingKVCache, isBatchableCache, isPlainKvCache, isRotatingPlainCache } from "../../model/gemma4-base";
7
11
  import { SSMCache } from "../../model/qwen3-delta";
12
+ import { Gemma4Model } from "../../model/gemma4";
8
13
  import { Qwen35Model } from "../../model/qwen3_5";
9
14
  import { runtimeConfig, type RuntimeConfig } from "../../runtime-config";
10
15
  import { disposeResources } from "../../engine/resources";
11
16
  import { legacyCompiledDecodeAvailable } from "./autoregressive";
12
- import { MlxBatchExecutionGroup, type MlxBatchExecutionGroupOptions } from "./batch-group";
17
+ import { MlxBatchExecutionGroup, type MlxBatchExecutionGroupOptions, type MlxGroupMethodRequest } from "./batch-group";
18
+ import type { DraftProvider } from "../../spec/source";
19
+ import { targetRowLayoutFactory } from "./target-layout-capability";
20
+ import { bindSpeculativeGroupRequests } from "./speculative-group";
13
21
  import type { GenerateOptions } from "../../generate";
14
22
  import type { ExecutionRequirements, ResolvedExecution } from "../../contracts/execution";
15
23
  import { resolveExecution } from "../../engine/execution-plan";
@@ -20,52 +28,103 @@ export interface MlxBatchGroup extends Pick<MlxBatchExecutionGroup,
20
28
  /** A model implementation owns capability checks and the execution group.
21
29
  * Scheduling never inspects concrete model/cache classes. */
22
30
  export interface MlxGatewayBinding {
31
+ configureContinuation?(services: MlxSerialServices): void;
32
+ continuationRequest?(execution: ResolvedExecution | undefined, options: GenerateOptions, prompt: number[],
33
+ onToken: Parameters<typeof createOrdinaryContinuationRequest>[0]["onToken"]): ReturnType<typeof createOrdinaryContinuationRequest> | undefined;
23
34
  readonly config: ModelConfig;
24
35
  readonly runtime: RuntimeConfig;
25
36
  plan(request: ExecutionRequirements, options: GenerateOptions,
26
37
  scheduling: { continuous: boolean; quantizedBatch: boolean; checkpoints: boolean }): ResolvedExecution;
38
+ bindAdapterContext?(adapters: string[], key: string): ExecutionContext;
27
39
  cachesBatchable(): boolean;
28
40
  kvBatchable(scheme: KvScheme): boolean;
41
+ statePolicy?(execution: ResolvedExecution | undefined, options: GenerateOptions, capacityTokens: number): MlxRequestStatePolicy | undefined;
42
+ methodRequest?(execution: ResolvedExecution | undefined, options: GenerateOptions): MlxGroupMethodRequest | undefined;
29
43
  createBatchGroup(options: MlxBatchExecutionGroupOptions): MlxBatchGroup;
30
44
  }
31
45
 
32
- export function bindMlxGateway(model: RuntimeModel): MlxGatewayBinding {
46
+ export function bindMlxGateway(model: RuntimeModel, draft?: { provider: DraftProvider; numDraftTokens: number }): MlxGatewayBinding {
33
47
  const runtime = runtimeConfig();
48
+ let continuationServices: MlxSerialServices | undefined;
49
+ const kvBatchCapabilities = { delayedAffine: model instanceof Qwen35Model || model instanceof Gemma4Model };
50
+ const cachesBatchable = () => {
51
+ if (model instanceof UniversalDenseModel)
52
+ return !model.args.maskArray && !model.args.layerTypes?.includes("sliding_attention");
53
+ const caches = model.makeCache();
54
+ try {
55
+ const ssm = runtime.value("MLX_BUN_BATCH_SSM") !== "0";
56
+ return caches.every((cache) => cache instanceof KVCache || cache instanceof RotatingKVCache ||
57
+ isBatchableCache(cache) || (ssm && cache instanceof SSMCache));
58
+ } finally { disposeResources(caches); }
59
+ };
60
+ const supportsTargetRows = () => {
61
+ const caches = model.makeCache();
62
+ try { return caches.every(cache => targetRowLayoutFactory(cache) !== undefined); }
63
+ finally { disposeResources(caches); }
64
+ };
65
+ const speculative = draft?.provider.grouped && cachesBatchable() && supportsTargetRows()
66
+ ? bindSpeculativeGroupRequests(model, draft.provider, draft.numDraftTokens) : undefined;
67
+ const adapterState = "loraState" in model ? model.loraState : undefined;
34
68
  return {
35
69
  config: model.config, runtime,
70
+ configureContinuation: services => { continuationServices = services; },
71
+ continuationRequest(execution, options, prompt, onToken) {
72
+ if (!execution?.checkpoint || execution.mechanism !== "continuous") return undefined;
73
+ const services = continuationServices;
74
+ if (!services?.checkpoints || !services.checkpointPersistence)
75
+ throw new Error("qualified continuation requires bound persistence services");
76
+ return createOrdinaryContinuationRequest({ options, prompt, onToken, execution,
77
+ store: services.checkpoints, persistence: services.checkpointPersistence,
78
+ restore: entry => services.checkpoints!.restore(entry, model),
79
+ interval: services.checkpointEveryTokens!, identity: services.identity });
80
+ },
81
+ statePolicy: (execution, options, capacity) => execution?.pagedKv ? bindPagedRequestState(model, options, capacity) : undefined,
82
+ methodRequest: (execution, options) => execution?.method === "speculative" ? speculative?.(options) : undefined,
83
+ ...(adapterState ? { bindAdapterContext(adapters: string[], key: string): ExecutionContext {
84
+ const selected = [...adapters];
85
+ return { key, enter() {
86
+ const previous = adapterState.active;
87
+ adapterState.active = selected;
88
+ return () => { adapterState.active = previous; };
89
+ } };
90
+ } } : {}),
36
91
  plan(request, options, scheduling) {
37
92
  return resolveExecution(request, {
38
93
  ...scheduling,
94
+ sharedCheckpoints: !!continuationServices?.checkpointPersistence &&
95
+ !request.hasDraft && !request.hasVision && !request.hasGrammar &&
96
+ !request.wantsLogprobs && !options.fill && !options.pagedKv,
97
+ adapterBatch: !!adapterState, pagedBatch: model instanceof Gemma4Model,
98
+ groupedMethods: speculative ? ["autoregressive", "speculative"] : ["autoregressive"],
99
+ speculativeLogprobs: scheduling.continuous && !!speculative,
100
+ sharedSpeculativeAdapters: scheduling.continuous && !!speculative && !!adapterState &&
101
+ draft?.provider.grouped?.supportsTargetAdapters === true,
102
+ turboQuantBatch: scheduling.quantizedBatch,
103
+ speculativeTurboQuant: scheduling.continuous && !!speculative && !!options.turboQuant,
39
104
  method: model instanceof DiffusionGemmaModel ? "denoising" : "autoregressive",
40
105
  compiledDecode: legacyCompiledDecodeAvailable(model),
41
106
  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),
107
+ speculativeKvQuant: (!(model instanceof Qwen35Model) || runtime.flag("MLX_BUN_QWEN_SPEC_KV4", true)) && (
108
+ (scheduling.continuous && !!speculative && (options.kvBits === 4 || options.kvBits === 8 || !!options.kvConfig?.length)) ||
109
+ (!options.kvConfig?.length && model instanceof Qwen35Model &&
110
+ (options.kvBits === 4 || (scheduling.continuous && !!speculative && options.kvBits === 8)) &&
111
+ (options.quantizedKvStart === 0 || (scheduling.continuous && !!speculative)))
112
+ ),
45
113
  }, {
46
114
  pagedKv: !!options.pagedKv, fill: !!options.fill,
47
115
  compiledDecode: runtime.flag("MLX_BUN_COMPILED_DECODE", true),
48
116
  grammarJump: runtime.flag("MLX_BUN_GRAMMAR_JUMP", false),
49
117
  });
50
118
  },
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
- },
119
+ cachesBatchable,
61
120
  kvBatchable(scheme) {
62
- if (scheme.kind !== "affine-config") return false;
63
121
  const caches = model.makeCache();
64
122
  try {
65
123
  return scheme.batchable(model.config,
66
- (layer) => isPlainKvCache(caches[layer]) || isRotatingPlainCache(caches[layer]));
124
+ (layer) => isPlainKvCache(caches[layer]) || isRotatingPlainCache(caches[layer]), caches.length,
125
+ kvBatchCapabilities);
67
126
  } finally { disposeResources(caches); }
68
127
  },
69
- createBatchGroup: (options) => new MlxBatchExecutionGroup(model, options),
128
+ createBatchGroup: (options) => new MlxBatchExecutionGroup(model, { ...options, kvBatchCapabilities }),
70
129
  };
71
130
  }
@@ -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,133 @@
1
+ import type { KvSchemeOptions } from "../../kv-scheme";
2
+ import { KVCache, QuantizedKVCache, RotatingKVCache, RotatingQuantizedKVCache, TurboQuantKVCache, type Cache } from "../../model/gemma4-base";
3
+ import type { KvQuantSpec, TurboQuantScheme } from "../../config";
4
+ import * as ops from "../../mlx/ops";
5
+ import { clearCache } from "../../mlx/ffi";
6
+
7
+ import { DelayedRotatingQuantizedKVCache } from "../../model/delayed-rotating-quantized-kv";
8
+ import { DelayedQuantizedKVCache } from "../../model/delayed-quantized-kv";
9
+ import { DelayedTurboQuantKVCache } from "../../model/delayed-turboquant-kv";
10
+
11
+ export interface KvMaintenance {
12
+ (cache: Cache[]): void;
13
+ /** Bind state requiring row-local maintenance before shared decode. */
14
+ prepareBatch?(cache: Cache[]): void;
15
+ /** Bind all precision policies before a prefill cohort owns row boundaries. */
16
+ preparePrefill?(cache: Cache[]): void;
17
+ }
18
+
19
+ const unchanged = (_cache: Cache[]): void => {};
20
+ let warnedTurboRotating = false;
21
+
22
+ /** Port of mlx-lm maybe_quantize_kv_cache + BOTH halves of optiq serve's
23
+ * per-layer patched variant (incl. patch_rotating_to_quantized: rotating
24
+ * caches convert too — Phase 9):
25
+ * - per-layer bits/group_size selection (kvConfig overrides kvBits,
26
+ * matching optiq's --kv-config precedence; shipped kv_config.json
27
+ * files cover EVERY cache-owning layer, sliding ones included —
28
+ * verified 12B 48/48, 26B 30/30, e4b 24/24 distinct caches — so
29
+ * rotating quantization engages straight from the config; uniform
30
+ * kvBits — like optiq --kv-bits — reaches them too), and
31
+ * - STREAMING conversion (optiq streaming_kv_quant / serve.py
32
+ * patched_maybe_quantize): eval each layer's quantized triples and
33
+ * clear the buffer pool before building the next layer's conversion.
34
+ * Lazily batching every layer's toQuantized into one eval pins ALL
35
+ * layers' bf16 K/V as graph inputs alongside ALL quantized outputs —
36
+ * the exact transient optiq's fix kills (16.35 → 7.60 GB at 32k on a
37
+ * 24 GB Mac). Numerics untouched: same quantize math, only the eval
38
+ * ordering is forced (tests/parity/kv-quant.test.ts, tests/parity/rotating-kvq.test.ts). */
39
+ export function createKvMaintenance(options: Readonly<Omit<KvSchemeOptions, "kvConfig">> & {
40
+ readonly kvConfig?: readonly Readonly<KvQuantSpec>[];
41
+ }): KvMaintenance {
42
+ const { kvBits, kvConfig, turboQuant } = options;
43
+ if (turboQuant) {
44
+ const start = options.quantizedKvStart ?? 0;
45
+ const scheme = { ...turboQuant };
46
+ const maintain: KvMaintenance = (cache) => maybeTurboQuantizeKv(cache, scheme, start);
47
+ maintain.preparePrefill = (cache) => {
48
+ for (let layer = 0; layer < cache.length; layer++) {
49
+ const row = cache[layer]!;
50
+ if (row instanceof KVCache || row instanceof TurboQuantKVCache)
51
+ cache[layer] = new DelayedTurboQuantKVCache(scheme.kBits, scheme.vBits, start, maintain, row);
52
+ }
53
+ };
54
+ if (start > 0) maintain.prepareBatch = maintain.preparePrefill;
55
+ return maintain;
56
+ }
57
+ if (!kvBits && !kvConfig?.length) return unchanged;
58
+ const start = options.quantizedKvStart ?? (kvConfig?.length ? 0 : 5000);
59
+ const groupSize = options.kvGroupSize ?? 64;
60
+ // Resolve layer policy once when composing execution, never per token.
61
+ const byLayer = kvConfig?.length
62
+ ? new Map(kvConfig.map((entry) => [entry.layerIdx, { ...entry }]))
63
+ : null;
64
+ const maintain: KvMaintenance = (cache) => {
65
+ for (let i = 0; i < cache.length; i++) {
66
+ const c = cache[i]!;
67
+ const conversion = c.affineConversion ?? (c instanceof KVCache || c instanceof RotatingKVCache ? c : undefined);
68
+ if (!conversion || conversion.offset < start || conversion.offset === 0) continue;
69
+ const conversionOffset = conversion.offset;
70
+ // The populated-cache boundary is part of oracle parity: quantizing an
71
+ // empty cache would also quantize the first prefill.
72
+ if (byLayer) {
73
+ const entry = byLayer.get(i);
74
+ if (!entry) continue;
75
+ cache[i] = conversion.toQuantized(entry.groupSize, entry.bits);
76
+ } else {
77
+ cache[i] = conversion.toQuantized(groupSize, kvBits!);
78
+ }
79
+ if (start > 0) cache[i]!.minimumReusableOffset = conversionOffset;
80
+ // Materialize one layer before converting the next to bound the live
81
+ // bf16 source plus quantized destination to one conversion at a time.
82
+ ops.evalAll(cache[i]!.state());
83
+ clearCache();
84
+ }
85
+ };
86
+ maintain.preparePrefill = (cache) => {
87
+ for (let layer = 0; layer < cache.length; layer++) {
88
+ const row = cache[layer]!;
89
+ if (!(row instanceof KVCache || row instanceof QuantizedKVCache || row instanceof RotatingKVCache || row instanceof RotatingQuantizedKVCache)) continue;
90
+ const spec = byLayer ? byLayer.get(layer) : { bits: kvBits!, groupSize };
91
+ if (!spec) continue;
92
+ const rowMaintenance = createKvMaintenance({ kvBits: spec.bits, kvGroupSize: spec.groupSize, quantizedKvStart: start });
93
+ cache[layer] = row instanceof RotatingKVCache || row instanceof RotatingQuantizedKVCache
94
+ ? new DelayedRotatingQuantizedKVCache(row.maxSize, spec.groupSize, spec.bits, start, rowMaintenance, row)
95
+ : new DelayedQuantizedKVCache(spec.groupSize, spec.bits, start, rowMaintenance, row);
96
+ }
97
+ };
98
+ if (start > 0) maintain.prepareBatch = maintain.preparePrefill;
99
+ return maintain;
100
+ }
101
+
102
+ function maybeTurboQuantizeKv(cache: Cache[], scheme: TurboQuantScheme, start: number): void {
103
+ for (let i = 0; i < cache.length; i++) {
104
+ const c = cache[i]!;
105
+ if (c instanceof RotatingKVCache) {
106
+ if (!warnedTurboRotating) {
107
+ warnedTurboRotating = true;
108
+ console.warn(
109
+ "[turbo-quant] sliding-window (RotatingKVCache) layers stay bf16 in v1 " +
110
+ "(full-attention only) — docs/design/turboquant.md.",
111
+ );
112
+ }
113
+ continue;
114
+ }
115
+ const conversion = c.turboConversion ?? (c instanceof KVCache ? c : undefined);
116
+ if (!conversion || conversion.offset < start || conversion.offset === 0) continue;
117
+ const conversionOffset = conversion.offset;
118
+ const tq = c.turboConversion ? c.turboConversion.toTurboQuantized(scheme.kBits, scheme.vBits)
119
+ : TurboQuantKVCache.fromKVCache(c as KVCache, scheme.kBits, scheme.vBits);
120
+ if (start > 0) tq.minimumReusableOffset = conversionOffset;
121
+ cache[i] = tq;
122
+ // state() allocates fresh trimmed slice views for this cache kind
123
+ // (see evalCacheState) — dispose after materializing (throw included),
124
+ // or they leak.
125
+ const state = tq.state();
126
+ try {
127
+ ops.evalAll(state);
128
+ } finally {
129
+ for (const a of state) a.dispose();
130
+ }
131
+ clearCache();
132
+ }
133
+ }
@@ -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
+ }
@@ -25,7 +25,7 @@ export function modelServingBinding(context: ServingContext): ModelServingBindin
25
25
  const embedding = isEmbeddingModel(model);
26
26
  return {
27
27
  stateCompatibility: `mlx-${MLX_VERSION}-${deviceArchitecture()}`,
28
- gateway: bindMlxGateway(model),
28
+ gateway: bindMlxGateway(model, ctx.draft ?? undefined),
29
29
  createSerial: (services) => createMlxSerialExecutor(serial, services),
30
30
  buildPrompt: (body, tools, ownership, prep) => buildModelPrompt(ctx, prep, body, tools, ownership),
31
31
  restore: (store, entry) => store.restore(entry, model),
@@ -0,0 +1,89 @@
1
+ import type { Cache } from "../../model/gemma4-base";
2
+ import type { RuntimeModel } from "../../model/factory";
3
+ import type { MlxArray } from "../../mlx/array";
4
+ import { nextPrefillStep } from "../../inference/prefill";
5
+ import type { CacheCodecProvider } from "../../kv-store";
6
+ import { disposeResources, cleanupFailure } from "../../engine/resources";
7
+ import type { Row, RowPromptCache } from "./batch-group";
8
+ import type { KvMaintenance } from "./kv-maintenance";
9
+ import { MlxPrefillRows, type MlxPrefillState } from "./prefill-rows";
10
+
11
+ export interface PrefillState extends MlxPrefillState {
12
+ snapAt: number | null;
13
+ continuation?: import("./continuation").OrdinaryContinuationState;
14
+ closePrefill?: () => void;
15
+ }
16
+
17
+ interface PrefillHost {
18
+ model: RuntimeModel;
19
+ chunkSize: number;
20
+ tailSplit: boolean;
21
+ promptCache?: RowPromptCache;
22
+ stateCodecs?: CacheCodecProvider;
23
+ maintain?: KvMaintenance;
24
+ forward(ids: MlxArray, caches: Cache[]): Promise<MlxArray>;
25
+ /** Target projection preserves the forward batch geometry before sampling. */
26
+ project(hidden: MlxArray, caches: Cache[], completed: readonly PrefillState[]): MlxArray;
27
+ /** Borrows [1,1,V] logits; takes ownership of the completed request caches. */
28
+ complete(state: PrefillState, logits: MlxArray): Promise<void>;
29
+ resume?(state: PrefillState): Promise<void>;
30
+ reject(row: Row, error: unknown): void;
31
+ }
32
+
33
+ /** Ordinary sampling/cache policy over the shared target preparation driver. */
34
+ export class MlxPrefillCohort extends MlxPrefillRows<PrefillState> {
35
+ constructor(readonly host: PrefillHost) {
36
+ super({
37
+ stateCodecs: host.stateCodecs, maintain: host.maintain,
38
+ open(row) {
39
+ let owned: { caches: Cache[]; retain?: () => void } | undefined;
40
+ let closeCache: (() => void) | undefined;
41
+ let closePrefill: (() => void) | undefined;
42
+ try {
43
+ closeCache = row.req.trace?.begin("cache.lookup_restore", { mechanism: "continuous" });
44
+ const continuation = row.req.continuation?.restore(row.cacheNamespace ?? "");
45
+ if (continuation) {
46
+ owned = { caches: continuation.caches };
47
+ return { row, solo: continuation.caches, pos: row.req.promptIds.length,
48
+ snapAt: null, continuation };
49
+ }
50
+ const hit = host.promptCache?.take(row.req.promptIds, row.cacheNamespace) ?? null;
51
+ if (hit) owned = hit;
52
+ closeCache?.(); closeCache = undefined;
53
+ if (hit) row.cachedTokens = hit.tokens.length;
54
+ const length = row.req.promptIds.length;
55
+ const boundary = Math.min(row.req.snapshotAt ?? length, length - 1);
56
+ const snapAt = host.promptCache && boundary >= 256 && boundary > (hit?.tokens.length ?? 0) ? boundary : null;
57
+ closePrefill = row.req.trace?.begin("prefill.total", {
58
+ mechanism: "continuous", promptTokens: row.promptTokens, cachedTokens: row.cachedTokens,
59
+ });
60
+ const closeSetup = row.req.trace?.begin("prefill.batch_setup", { mechanism: "continuous" });
61
+ owned ??= { caches: row.req.statePolicy?.create() ?? host.model.makeCache() }; closeSetup?.();
62
+ return { row, solo: owned.caches, pos: hit?.tokens.length ?? 0, retain: owned.retain, snapAt, closePrefill };
63
+ } catch (error) {
64
+ return cleanupFailure(error, () => disposeResources([...(owned?.caches ?? []),
65
+ { dispose: () => owned?.retain?.() }, { dispose: () => closePrefill?.() }]));
66
+ } finally { closeCache?.(); }
67
+ },
68
+ ready: state => !!state.continuation,
69
+ plan(state) { return nextPrefillStep({ length: state.row.promptTokens, position: state.pos,
70
+ chunkSize: state.row.req.prefillChunkSize ?? host.chunkSize,
71
+ tailSplit: host.tailSplit, snapshotAt: state.snapAt }); },
72
+ forward: host.forward.bind(host), project: host.project.bind(host),
73
+ complete: (state, logits) => state.continuation ? host.resume!(state) : host.complete(state, logits!), reject: host.reject.bind(host),
74
+ checkpoint(state, capture) {
75
+ let snapshot: Cache[] | undefined;
76
+ try {
77
+ snapshot = capture();
78
+ host.promptCache!.put(state.row.req.promptIds.slice(0, state.pos), snapshot, state.row.cacheNamespace);
79
+ snapshot = undefined;
80
+ } catch (error) {
81
+ if (snapshot) disposeResources(snapshot);
82
+ console.warn(`batch-lane boundary snapshot skipped: ${(error as Error).message}`);
83
+ }
84
+ state.snapAt = null;
85
+ },
86
+ close(state) { const close = state.closePrefill; state.closePrefill = undefined; close?.(); },
87
+ });
88
+ }
89
+ }